import {addMaterial, editMaterial, getMaterialInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {AddMaterialParams} from '@models';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

type FormState = {
  storageLocationCode: string;
  wllbCode: string;
  warehouseId: string;
};

const validate = object({
  wllbCode: string().required('请选择物料编号'),
  storageLocationCode: string().required('请选择库位编号'),
  warehouseId: string().required('请选择仓库信息'),
});

export function useFormState({
  visible,
  id,
  onClose,
  onFetch,
}: {
  visible: boolean;
  id: string;
  onClose: () => void;
  onFetch: () => void;
}) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      wllbCode: '',
      storageLocationCode: '',
      warehouseId: '',
    },
    resolver: yupResolver(validate),
  });
  const {clearErrors, handleSubmit, reset} = formInstance;

  useEffect(
    function () {
      if (!visible) {
        clearErrors();
        // 关闭modal后所有值重置
        // 确保第二次进入后仓库id为空 不会触发库位id清空
        reset();
      }
    },
    [clearErrors, reset, visible],
  );

  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addMaterial,
    editFn: editMaterial,
    onClose,
    onFetch,
  });
  const onSubmit = handleSubmit(function ({storageLocationCode, wllbCode}) {
    const params: AddMaterialParams = {storageLocationCode, wllbCode};

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

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

export function useFormContextState() {
  return useFormContext<FormState>();
}

export function useWatchId(id: string, onSearch: (value: string) => void) {
  const {setValue} = useFormContext<FormState>();

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

  useEffect(
    function () {
      setValue('wllbCode', data?.wllbCode ?? '');
      setValue('storageLocationCode', data?.storageLocationCode ?? '');
      setValue('warehouseId', data?.warehouseWhere ?? '');
      onSearch(data?.wllbCode ?? '');
    },
    [data, setValue, onSearch],
  );
}
