import {addMenu, editMenu, getMenuInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {useContextSection} from '@hooks';
import {pIdContext} from '@pages/menu-id/context';
import {useMutation, useQuery} from '@tanstack/react-query';
import {message} from 'antd';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

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

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

function useAdd(onClose: () => void, onFetch: () => void) {
  const {isLoading, mutate} = useMutation(
    addMenu,
    {
      onSuccess(data) {
        if (data.msg === '200') {
          onClose();
          onFetch();
          message.success('新增成功');
        }
      },
    },
  );

  return [isLoading, mutate] as const;
}

function useEdit(onClose: () => void, onFetch: () => void) {
  const {isLoading, mutate} = useMutation(
    editMenu,
    {
      onSuccess(data) {
        if (data.msg === '200') {
          onClose();
          onFetch();
          message.success('修改成功');
        }
      },
    },
  );

  return [isLoading, mutate] as const;
}

export function useFormState(
  {onClose, id, visible, onFetch}:
  {
    id: string, visible: boolean,
    onFetch: () => void, onClose: () => void,
  },
) {
  const isEdit = Boolean(id);
  const pid = useContextSection(pIdContext, ([pid]) => pid);
  const formInstance = useForm<FormState>({
    defaultValues: {
      menuName: '',
      menuUrl: '',
      menuOrderBy: '0',
    },
    resolver: yupResolver(validate),
  });
  const {handleSubmit, clearErrors} = formInstance;
  const [addIsLoading, addMutate] = useAdd(onClose, onFetch);
  const [editIsLoaindg, editMutate] = useEdit(onClose, onFetch);
  const isLoading = addIsLoading || editIsLoaindg;

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

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

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

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

export function useFormValues(id: string) {
  const {setValue} = useFormContext<FormState>();
  const pId = useContextSection(pIdContext, state => state[0]);

  const {data} = useQuery(
    [getMenuInfo.name, id, 'PC', pId],
    async function() {
      const data = await getMenuInfo(pId, id, 'PC');

      if (data.msg === '200') {
        if (data.data.list.length) return data.data.list[0];

        throw new Error('未获取到菜单信息');
      }

      throw new Error(data.errMsg);
    },
    {
      enabled: Boolean(id),
      suspense: true,
      cacheTime: 0,
    },
  );

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