import {addContainer, editContainer, getContainerInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {useQueryDataInfo, usePutData} from '@hooks';
import {AddContainerParams} from '@models';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {number, object, string} from 'yup';

type FormState = {
  containerName: string,
  containerType: string,
  containerDepartment: string,
  containerNum: number,
};

const validate = object({
  containerName: string().required('请输入容器名称'),
  containerType: string().required('请输入容器类型'),
  containerDepartment: string().required('请选择容器所属部门'),
  containerNum: number().typeError('请输入数字类型').required('请输入容器数量')
    .min(0, '容器数量不能小于0个'),
});

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

  const {clearErrors, handleSubmit} = formInstance;

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

  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addContainer,
    editFn: editContainer,
    onFetch,
    onClose,
  });
  const onSubmit = handleSubmit(function({
    containerName,
    containerNum,
    containerDepartment,
    containerType,
  }) {
    const params: AddContainerParams = {
      containerName,
      num: String(containerNum),
      department: containerDepartment,
      type: containerType,
    };

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

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

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

  return control;
}

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

  useEffect(function() {
    setValue('containerDepartment', data?.departmentId ?? '');
    setValue('containerName', data?.containerName ?? '');
    setValue('containerNum', Number(data?.num ?? '0'));
    setValue('containerType', data?.type ?? '');
  }, [data, setValue]);
}
