import {useBoolean} from 'ahooks';
import {context, pIdContext, pageContext} from '../context';
import {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 {useContextSection, usePage} from '@hooks';
import {deleteConfirm} from '@utils';

export function useList() {
  const [{page, pageSize}, {onPageChange}] = usePage(pageContext);
  const name = useContextSection(context, state => state[0].name);
  const [count, setCount] = useState(0);
  const pid = useContextSection(pIdContext, ([pid]) => pid);

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

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

      return [] as MenuListData[];
    },
    {
      initialData: [],
      enabled: pid !== '0',
    },
  );

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

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

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

  function onAdd() {
    setTrue();
    setEditId('');
  }

  function onEdit(id: string) {
    return function() {
      setEditId(id);
      setTrue();
    };
  }

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

  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>
          </>
        );
      },
    },
  ];

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

