import {addPDAMenu, editMenu, getMenuInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

type FormState = {
  menuName: string;
  menuID: string;
  menuOrderBy: string;
};

const validate = object({
  menuName: string().required('请输入菜单名称'),
  menuID: string().required('请输入菜单id'),
  menuOrderBy: string().required('请输入菜单排序'),
});

export function useFormState({
  onClose,
  id,
  visible,
  onFetch,
}: {
  id: string;
  visible: boolean;
  onFetch: () => void;
  onClose: () => void;
}) {
  const isEdit = Boolean(id);

  const formInstance = useForm<FormState>({
    defaultValues: {
      menuName: '',
      menuID: '',
      menuOrderBy: '0',
    },
    resolver: yupResolver(validate),
  });
  const {handleSubmit, clearErrors} = formInstance;
  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addPDAMenu,
    editFn: editMenu,
    onClose,
    onFetch,
  });

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

  const onSubmit = handleSubmit(function ({menuName, menuID, menuOrderBy}) {
    isEdit
      ? editMutate({
          name: menuName,
          url: menuID,
          id,
          pId: '0',
          orderBy: menuOrderBy,
          img: '',
        })
      : addMutate({
          name: menuName,
          url: menuID,
          pId: '0',
          orderBy: menuOrderBy,
          img: '',
        });
  });

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

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

  return [{control}] as const;
}

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

  const data = useQueryDataInfo({
    queryFn: getMenuInfo,
    params: ['0', id, 'PDA'],
    enabled: Boolean(id),
  });

  useEffect(
    function () {
      setValue('menuID', data?.url ?? '');
      setValue('menuName', data?.name ?? '');
      setValue('menuOrderBy', data?.orderBy ?? '0');
    },
    [data, setValue],
  );
}
