import {deleteMenu} from '@apis';
import {LDColumnsType, LDTableButton} from '@components';
import {useTableDeleteEvent, useTableModalEvent} from '@hooks';
import {MenuListData} from '@models';
import {TABLE_CELL_WIDTH} from '@utils';

const tableColumns: LDColumnsType<MenuListData>[] = [
  {
    title: '菜单名称',
    dataIndex: 'name',
  },
  {
    title: '菜单路径',
    dataIndex: 'url',
  },
  {
    title: '菜单排序',
    dataIndex: 'orderBy',
    width: TABLE_CELL_WIDTH.small,
  },
  {
    title: '最后修改人',
    dataIndex: 'modifyUser',
    width: TABLE_CELL_WIDTH.normal,
  },
  {
    title: '最后修改时间',
    dataIndex: 'modifyTime',
    width: TABLE_CELL_WIDTH.date,
  },
];

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

  const columns: LDColumnsType<MenuListData>[] = [
    ...tableColumns,
    {
      dataIndex: 'id',
      title: '操作',
      width: TABLE_CELL_WIDTH.doubleBtn,
      fixed: 'right',
      render({id, name}) {
        const loading = deleteId === id;

        return (
          <>
            <LDTableButton
              disabled={loading}
              onClick={onEdit(id)}
            >
              修改
            </LDTableButton>
            <LDTableButton
              danger
              loading={loading}
              onClick={onDelete(id, name)}
            >
              删除
            </LDTableButton>
          </>
        );
      },
    },
  ];

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