import {LDColumnsType, LDTableButton, modifyDataColumns} from '@components';
import {useTableDeleteEvent, useTableModalEvent} from '@hooks';
import {RoleListData} from '@models';
import {TABLE_CELL_WIDTH} from '@utils';
import {deleteRole} from '@apis';

const tableColumns: LDColumnsType<RoleListData>[] = [
  {
    title: '角色名称',
    dataIndex: 'roleName',
    width: TABLE_CELL_WIDTH.normal,
    sort: true,
  },
  {
    title: '备注信息',
    dataIndex: 'remarks',
    width: TABLE_CELL_WIDTH.maximal,
  },
  ...modifyDataColumns,
];

export function useColumns(refetch: () => void) {
  const [deleteId, onDelete] = useTableDeleteEvent(
    deleteRole,
    refetch,
    {label: '角色'},
  );
  const [{visible, editId}, {onAdd, onClose, onEdit}] = useTableModalEvent();
  const [
    {visible: authVisible, editId: authId},
    {onClose: onAuthClose, onEdit: onAuthClick},
  ] = useTableModalEvent();

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

        return (
          <>
            <LDTableButton
              onClick={onEdit(String(id))}
              disabled={loading}
            >
              修改
            </LDTableButton>
            <LDTableButton
              onClick={onAuthClick(String(id))}
              disabled={loading}
            >
              菜单权限
            </LDTableButton>
            <LDTableButton
              danger
              loading={loading}
              onClick={onDelete(String(id), roleName)}
            >
              删除
            </LDTableButton>
          </>
        );
      },
    },
  ];

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