import {useBoolean} from 'ahooks';
import {context, pIdContext, pageContext, searchContext} from '../context';
import {useState} from 'react';
import {useMutation} 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, useQueryTableList} from '@hooks';
import {deleteConfirm} from '@utils';

export function useList() {
  const pId = useContextSection(pIdContext, ([pid]) => pid);
  const params = useContextSection(
    context,
    function([{name}]) {
      return {pId, name};
    },
  );

  const [{isFetching, data, count}, {refetch}] = useQueryTableList({
    queryFn: getMenuList,
    params,
    pageContext,
    searchContext,
  });

  return [{count, isFetching, data}, {refetch}] 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;
}

