import {useTableModalEvent, useTableDeleteEvent} from '@hooks';
import {delMaterialBind} from '@apis';
import {ColumnsType} from 'antd/es/table';
import {MaterialBindListData} from '@models';
import {Button} from 'antd';
import {
  DOUBLE_BTN_WIDTH,
  HUGE_TABLE_WIDTH,
  MIDDLE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
} from '@utils';

const tableColumns: ColumnsType<MaterialBindListData> = [
  {
    title: '物料编号',
    dataIndex: 'wllbCode',
    key: 'wllbCode',
    width: MIDDLE_TABLE_WIDTH,
  },
  {
    title: '物料名称',
    dataIndex: 'materialName',
    key: 'materialName',
    width: HUGE_TABLE_WIDTH,
  },
  {
    title: '工号',
    dataIndex: 'userName',
    key: 'userName',
    width: MIDDLE_TABLE_WIDTH,
  },
  {
    title: '姓名',
    dataIndex: 'realName',
    key: 'realName',
    width: MIDDLE_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, onClose, onEdit}] = useTableModalEvent();
  const [pendingId, onDelete] = useTableDeleteEvent(delMaterialBind, refetch, {
    label: '物料绑定',
  });

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

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