import {deleteRole} from '@apis';
import {ColumnsType} from 'antd/es/table';
import {RoleListData} from '@models';
import {Button} from 'antd';
import {
  MAXIMAL_TABLE_WIDTH,
  MIDDLE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
} from '@utils';
import {useTableModalEvent, useTableDeleteEvent} from '@hooks';

const tableColumns: ColumnsType<RoleListData> = [
  {
    title: '角色编号',
    dataIndex: 'roleCode',
    key: 'roleCode',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '修改人',
    dataIndex: 'modifyUser',
    key: 'modifyUser',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '修改时间',
    dataIndex: 'modifyTime',
    key: 'modifyTime',
    width: MIDDLE_TABLE_WIDTH,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: MIDDLE_TABLE_WIDTH,
  },
  {
    title: '备注',
    dataIndex: 'remarks',
    key: 'remarks',
    width: MIDDLE_TABLE_WIDTH,
  },
];

export function useHandle(data: RoleListData[], refetch: () => void) {
  const [deleteId, onDelete] = useTableDeleteEvent(deleteRole, refetch, {
    label: '角色',
  });
  const [{visible, editId}, {onClose, onAdd, onEdit}] = useTableModalEvent();
  const [
    {visible: roleVisible, editId: roleId},
    {onClose: onRoleClose, onEdit: onSetRole},
  ] = useTableModalEvent();
  const [
    {visible: pdaVisible, editId: pdaId},
    {onClose: onPdaClose, onEdit: onSetPda},
  ] = useTableModalEvent();

  const columns: ColumnsType<RoleListData> = [
    ...tableColumns,
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: MAXIMAL_TABLE_WIDTH,
      fixed: 'right',
      render(_, {id, roleName}) {
        return (
          <>
            <Button
              type='text'
              className='ant-text-btn-color-primary'
              disabled={deleteId === String(id)}
              onClick={onEdit(String(id))}
            >
              修改
            </Button>
            <Button
              type='text'
              className='ant-text-btn-color-primary'
              disabled={deleteId === String(id)}
              onClick={onSetRole(String(id))}
            >
              菜单权限
            </Button>
            <Button
              type='text'
              className='ant-text-btn-color-primary'
              disabled={deleteId === String(id)}
              onClick={onSetPda(String(id))}
            >
              PDA菜单权限
            </Button>
            <Button
              type='text'
              danger
              onClick={onDelete(String(id), roleName)}
              loading={deleteId === String(id)}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

  return [
    {columns, visible, editId, roleVisible, roleId, pdaVisible, pdaId},
    {onAdd, onClose, onRoleClose, onPdaClose},
  ] as const;
}
