import {addStorage, editStorage, getStorageInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {AddStorageParams} from '@models';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

type FormState = {
  storageLocationCode: string;
  storageLocationName: string;
  storageIsNotDisable: string;
  storageWarehouse: string;
  storageMaterialType: string[];
  storageIsProduct: string;
};

const validate = object({
  storageLocationCode: string().required('请输入库位编号'),
  storageLocationName: string().required('请输入库位名称'),
  storageIsNotDisable: string().required('请选择是否是混合库位'),
  storageWarehouse: string().required('请选择所在仓库'),
  storageIsProduct: string().required('请选择是否是产成品库位'),
});

export function useFormState({
  onClose,
  onFetch,
  id,
  visible,
}: {
  onClose: () => void;
  onFetch: () => void;
  id: string;
  visible: boolean;
}) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      storageLocationCode: '',
      storageLocationName: '',
      storageIsNotDisable: '',
      storageWarehouse: '',
      storageMaterialType: [],
      storageIsProduct: '',
    },
    resolver: yupResolver(validate),
  });

  const {handleSubmit, clearErrors} = formInstance;

  useEffect(
    function () {
      visible && clearErrors();
    },
    [clearErrors, visible],
  );

  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addStorage,
    editFn: editStorage,
    onClose,
    onFetch,
  });

  const onSubmit = handleSubmit(function ({
    storageLocationName,
    storageLocationCode,
    storageIsNotDisable,
    storageWarehouse,
    storageMaterialType,
    storageIsProduct,
  }) {
    const params: AddStorageParams = {
      storageLocationName,
      storageLocationCode,
      isNotDisable: storageIsNotDisable,
      warehouseWhere: storageWarehouse,
      storageLocationType: storageMaterialType.join(','),
      isProduct: storageIsProduct,
    };

    id ? editMutate({...params, id}) : addMutate(params);
  });

  return [{formInstance, isLoading}, {onSubmit}] as const;
}

export function useFormInstance() {
  const {control} = useFormContext<FormState>();

  return control;
}

export function useFormInfoValue(id: string) {
  const {setValue} = useFormContext<FormState>();

  const data = useQueryDataInfo({
    queryFn: getStorageInfo,
    params: [id],
    enabled: Boolean(id),
  });

  useEffect(
    function () {
      setValue('storageLocationCode', data?.storageLocationCode ?? '');
      setValue('storageLocationName', data?.storageLocationName ?? '');
      setValue('storageIsNotDisable', data?.isNotDisable ?? '');
      setValue('storageIsProduct', data?.isProduct ?? '');
      setValue('storageWarehouse', data?.warehouseWhere ?? '');
      setValue(
        'storageMaterialType',
        data?.storageLocationType?.split(',').filter(Boolean) ?? [],
      );
      setValue('storageIsProduct', data?.isProduct ?? '');
    },
    [data, setValue],
  );
}
