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

const tableColumns: ColumnsType<MenuListData> = [
  {
    title: '菜单名称',
    dataIndex: 'name',
    key: 'name',
    width: HUGE_TABLE_WIDTH,
  },
  {
    title: '菜单排序',
    dataIndex: 'orderBy',
    key: 'orderBy',
    width: SMALL_TABLE_WIDTH,
  },
  {
    title: '图标',
    dataIndex: 'img',
    key: 'img',
    render(_, {img}) {
      return <FontIcon name={img} />;
    },
    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}] = useTableModalEvent();
  const [pendingId, onDelete] = useTableDeleteEvent(deleteMenu, refetch, {
    label: '菜单',
  });

  const [
    {visible: childVisible, editId: pid},
    {onEdit: onChildMenu, onClose: closeChildModal},
  ] = useTableModalEvent();

  const columns: ColumnsType<MenuListData> = [
    ...tableColumns,
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: LARGE_TABLE_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'
              className='ant-text-btn-color-primary'
              disabled={pendingId === id}
              onClick={onChildMenu(id)}
            >
              子菜单
            </Button>
            <Button
              type='text'
              danger
              loading={pendingId === id}
              onClick={onDelete(id, name)}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

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