import {useBoolean} from 'ahooks';
import {context, pageContext} from '../context';
import {useEffect, useState} from 'react';
import {useMutation, useQuery} from '@tanstack/react-query';
import {deleteMenu, getMenuList} from '@apis';
import {MenuListData} from '@models';
import {Button, message} from 'antd';
import {ColumnsType} from 'antd/es/table';
import {useContext, usePage} from '@hooks';
import {deleteConfirm} from '@utils';

export function useList() {
  const [{page, pageSize}, {onPageChange}] = usePage(pageContext);
  const [{name}, dispatch] = useContext(context);
  const [count, setCount] = useState(0);

  const {data, isFetching, refetch} = useQuery<MenuListData[]>(
    [getMenuList.name, page, pageSize, name],
    async function() {
      const data = await getMenuList({
        pId: '0',
        page: page.toString(),
        limit: pageSize.toString(),
        name,
      });

      if (data.msg === '200') {
        setCount(data.data.total);
        return data.data.list;
      }

      return [] as MenuListData[];
    },
    {
      initialData: [],
    },
  );

  useEffect(function() {
    dispatch({type: 'CHANGE_SEARCH_STATE', payload: isFetching});
  }, [dispatch, isFetching]);

  return [{count, isFetching, data, page, pageSize}, {refetch, onPageChange}] as const;
}

export function useHandle(refetch: () => void) {
  const [editId, setEditId] = useState('');
  const [pendingId, setPendingId] = useState<string | null>(null);
  const {mutate} = useMutation(
    deleteMenu,
    {
      onSuccess({msg}) {
        setPendingId(null);

        if (msg === '200') {
          message.success('删除成功');
          refetch();
        }
      },
    },
  );

  const [visible, {setTrue, setFalse}] = useBoolean();
  function onAdd() {
    setEditId('');
    setTrue();
  }
  function onEdit(id: string) {
    return function() {
      setEditId(id);
      setTrue();
    };
  }

  function onDelete(id: string) {
    return function() {
      deleteConfirm(
        '菜单',
        function() {
          mutate(id);
          setPendingId(id);
        },
      );
    };
  }

  const [childVisible, {set: setChildVisible, setFalse: closeChildModal}] = useBoolean();
  const [pid, setPid] = useState('');
  function onChildMenu(id: string) {
    return function() {
      setPid(id);
      setChildVisible(true);
    };
  }

  const columns: ColumnsType<MenuListData> = [
    {title: '菜单名称', dataIndex: 'name', key: 'name'},
    {title: '菜单路径', dataIndex: 'url', key: 'url'},
    {title: '菜单排序', dataIndex: 'orderBy', key: 'orderBy'},
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 260,
      render(_, {id}) {
        return (
          <>
            <Button
              type='link'
              disabled={pendingId === id}
              onClick={onEdit(id)}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              loading={pendingId === id}
              onClick={onDelete(id)}
            >
              删除
            </Button>
            <Button
              type='text'
              loading={pendingId === id}
              onClick={onChildMenu(id)}
            >
              子菜单
            </Button>
          </>
        );
      },
    },
  ];

  return [
    {columns, visible, editId, childVisible, pid},
    {onModalClose: setFalse, onAdd, closeChildModal},
  ] as const;
}

