import {useDictionaryOptions, useDictionaryWidthCode} from '@hooks';
import {FC} from 'react';
import {useFormState} from './hooks';
import {Modal, ModalDate, ModalField, ModalSelect} from '@components';

type Props = {
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
};

const deloveryGoodsTypeOptions = [
  {label: '交货', value: 'DE'},
  {label: '退货', value: 'RD'},
];

const AddModal: FC<Props> = function (props) {
  const [
    {data: materialOptions, isFetching: isMaterialFetching},
    onMaterialSearch,
  ] = useDictionaryWidthCode('物料字典');
  const [
    {data: customerOptions, isFetching: isCustomerFetching},
    onCustomerSearch,
  ] = useDictionaryWidthCode('供应商/客户', {
    findValue: state => state.code,
  });
  const [{isLoading, control}, {onSubmit}] = useFormState({
    ...props,
    onSearch() {
      onMaterialSearch('');
      onCustomerSearch('');
    },
  });
  const {data: companyOptions, isFetching: isCompanyFetching} =
    useDictionaryOptions('公司', false, state => state.code);
  const {data: utilsOptions, isFetching: isUnitsFetching} =
    useDictionaryOptions('计量单位');

  return (
    <Modal
      {...props}
      isLoading={isLoading}
      onSubmit={onSubmit}
      title='新增销售单'
      testId='sell_order_modal'
    >
      <ModalField control={control} label='销售单ID' name='deliveryOrderId' />
      <ModalField control={control} label='销售单编号' name='deliveryOrderNo' />
      <ModalSelect
        control={control}
        label='物料'
        name='materialId'
        data={materialOptions}
        onSearch={onMaterialSearch}
        loading={isMaterialFetching}
      />
      <ModalSelect
        control={control}
        label='计量单位'
        name='measUnitId'
        data={utilsOptions}
        loading={isUnitsFetching}
      />
      <ModalField
        control={control}
        label='交货数量'
        name='gsDeliveryCount'
        type='number'
      />
      <ModalField
        control={control}
        label='取消交货数量'
        name='gsCancelDeliveryCount'
        type='number'
      />
      <ModalSelect
        control={control}
        label='客户'
        name='customerNo'
        data={customerOptions}
        onSearch={onCustomerSearch}
        loading={isCustomerFetching}
      />
      <ModalSelect
        control={control}
        label='公司'
        name='companyNumber'
        data={companyOptions}
        loading={isCompanyFetching}
      />
      <ModalDate control={control} label='单据日期' name='docDate' />
      <ModalSelect
        control={control}
        label='交货类型'
        name='deloveryGoodsType'
        data={deloveryGoodsTypeOptions}
      />
      <ModalField control={control} label='分录号' name='entryNumber' />
      <ModalField
        control={control}
        label='WBS编号'
        name='WBS'
        required={false}
      />
    </Modal>
  );
};

export default AddModal;
