import {deleteMenu} from '@apis';
import {MenuListData} from '@models';
import {Button} from 'antd';
import {ColumnsType} from 'antd/es/table';
import {
  DOUBLE_BTN_WIDTH,
  MIDDLE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
} from '@utils';
import {useTableModalEvent, useTableDeleteEvent} from '@hooks';

const tableColumns: ColumnsType<MenuListData> = [
  {
    title: '菜单名称',
    dataIndex: 'name',
    key: 'name',
    width: NORMAL_TABLE_WIDTH,
  },
  {title: '菜单路径', dataIndex: 'url', key: 'url', width: NORMAL_TABLE_WIDTH},
  {
    title: '菜单排序',
    dataIndex: 'orderBy',
    key: 'orderBy',
    width: SMALL_TABLE_WIDTH,
  },
  {
    title: '修改人',
    dataIndex: 'modifyUser',
    key: 'modifyUser',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '修改时间',
    dataIndex: 'modifyTime',
    key: 'modifyTime',
    width: MIDDLE_TABLE_WIDTH,
  },
];

export function useHandle(refetch: () => void) {
  const [{visible, editId}, {onAdd, onEdit, onClose: onModalClose}] =
    useTableModalEvent();
  const [pendingId, onDelete] = useTableDeleteEvent(deleteMenu, refetch, {
    label: '菜单',
  });

  const columns: ColumnsType<MenuListData> = [
    ...tableColumns,
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: DOUBLE_BTN_WIDTH,
      fixed: 'right',
      render(_, {id, name}) {
        return (
          <>
            <Button
              type='text'
              className='ant-text-btn-color-primary'
              disabled={pendingId === id}
              onClick={onEdit(id)}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              loading={pendingId === id}
              onClick={onDelete(id, name)}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

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