<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="物料选择"
    :width="1000"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable, FormSchema, BasicColumn } from '/@/components/Table';
  import { getMaterialList } from '/@/api/erp/material/list';
  import { getVerification } from '/@/api/erp/bom/product';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isBoolean } from 'lodash-es';

  const { notification } = useMessage();
  const { t } = useI18n();
  const emits = defineEmits(['success', 'register']);
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入要查询的关键字',
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: '物料编码',
      dataIndex: 'code',
    },
    {
      title: '物料名称',
      dataIndex: 'name',
    },
    {
      title: '物料属性',
      dataIndex: 'propertyName',
    },
    {
      title: '物料类别',
      dataIndex: 'typeName',
      width: 150,
    },
  ];
  const shouldVerify = ref<boolean>(false);
  const selectType = ref<any>('radio');
  const [registerModal, { closeModal, setModalProps }] = useModalInner((data) => {
    setModalProps({ destroyOnClose: true });
    if (isBoolean(data.shouldVerify)) shouldVerify.value = data.shouldVerify;
    selectType.value = data.type || 'radio';
    setProps({
      rowSelection: {
        type: selectType.value,
      },
    });
  });
  const [registerTable, { getSelectRowKeys, getSelectRows, setProps }] = useTable({
    api: getMaterialList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    striped: false,
    pagination: false,
    rowSelection: {
      type: 'radio',
    },
  });
  const handleSubmit = async () => {
    if (!getSelectRowKeys()?.length) {
      notification.warning({
        message: t('提示'),
        description: '请选择物料！',
      });
      return;
    }
    if (shouldVerify.value) await getVerification(getSelectRowKeys()[0]);
    closeModal();
    const emitInfo = selectType.value === 'checkbox' ? getSelectRows() : getSelectRowKeys()[0];
    emits('success', emitInfo);
  };
</script>
