import {useTableModalEvent, useTableDeleteEvent} from '@hooks';
import {deleteMaterial} from '@apis';
import {Button} from 'antd';
import {MaterialListData} from '@models';
import {ColumnsType} from 'antd/es/table';
import {
  DOUBLE_BTN_WIDTH,
  MATERIAL_CODE_COL_WIDTH,
  MATERIAL_NAME_COL_WIDTH,
  MIDDLE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
} from '@utils';

const tableColumns: ColumnsType<MaterialListData> = [
  {
    title: '物料编号',
    dataIndex: 'wllbCode',
    key: 'wllbCode',
    width: MATERIAL_CODE_COL_WIDTH,
  },
  {
    title: '物料名称',
    dataIndex: 'wllbName',
    key: 'wllbName',
    width: MATERIAL_NAME_COL_WIDTH,
  },
  {
    title: '库位编号',
    dataIndex: 'storageLocationName',
    key: 'storageLocationName',
    width: NORMAL_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(deleteMaterial, refetch, {
    label: '库位绑定',
  });

  const columns: ColumnsType<MaterialListData> = [
    ...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={id === pendingId}
              onClick={onEdit(id)}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              loading={id === pendingId}
              onClick={onDelete(id, wllbCode)}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

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