import {addMaterialBind, editMaterialBind, getMaterialBindInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {AddMaterialBindListParams} from '@models';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

export type FormState = {
  userId: string;
  materialId: string;
};

const validate = object({
  userId: string().required('请选择用户信息'),
  materialId: string().required('请选择物料信息'),
});

export function useFormState({
  onClose,
  visible,
  onFetch,
  id,
}: {
  visible: boolean;
  id: string;
  onClose: () => void;
  onFetch: () => void;
}) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      userId: '',
      materialId: '',
    },
    resolver: yupResolver(validate),
  });

  const {clearErrors, handleSubmit} = formInstance;

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

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

  const onSubmit = handleSubmit(function ({userId, materialId}) {
    const params: AddMaterialBindListParams = {
      userId,
      materialId,
    };

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

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

export function useWatchId(id: string, onSearch: (value: string) => void) {
  const data = useQueryDataInfo({
    queryFn: getMaterialBindInfo,
    params: [id],
    enabled: Boolean(id),
  });
  const {setValue} = useFormContext<FormState>();

  useEffect(
    function () {
      setValue('userId', data?.userId ?? '');
      setValue('materialId', data?.wllbCode ?? '');
      onSearch(data?.wllbCode ?? '');
    },
    [data, onSearch, setValue],
  );
}
