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

type Props = {
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
  id: string;
  code: string;
  softwareCode: string;
};

const PutModal: FC<Props> = function({
  visible,
  onClose,
  onFetch,
  id,
  code,
  softwareCode,
}) {
  const [{data: materialOptions, isFetching}, onMaterialSearch]
  = useDictionaryWidthCode(
    '物料字典',
    {findValue: state => state.code},
  );
  const [
    {data: SearviceMaterialOptions, isFetching: searviceMaterialFetching},
    onServiceMaterialSearch,
  ]
  = useDictionaryWidthCode(
    '物料字典',
    {findValue: state => state.code},
  );

  useEffect(
    function() {
      onMaterialSearch(code);
      onServiceMaterialSearch(softwareCode);
    },
    [code, onMaterialSearch, onServiceMaterialSearch, softwareCode],
  );

  const [
    {control, isLoading},
    {onSubmit},
  ] = useFormState({
    visible,
    id,
    onFetch,
    onClose,
    code,
    softwareCode,
  });

  return (
    <Modal
      visible={visible}
      title={`${id ? '修改' : '新增'}软件类绑定`}
      onClose={onClose}
      testId='software_modal'
      onSubmit={onSubmit}
      isLoading={isLoading}
      height='500px'
    >
      <ModalSelect
        control={control}
        name='materialCode'
        label='物料编号'
        data={materialOptions}
        onSearch={onMaterialSearch}
        loading={isFetching}
      />
      <ModalSelect
        control={control}
        name='softwareCode'
        label='服务类编号'
        data={SearviceMaterialOptions}
        onSearch={onServiceMaterialSearch}
        loading={searviceMaterialFetching}
      />
    </Modal>
  );
};

export default PutModal;
