import {deleteStorage} from '@apis';
import {ColumnsType} from 'antd/es/table';
import {StorageListData} from '@models';
import {Button} from 'antd';
import {
  DOUBLE_BTN_WIDTH,
  LARGE_TABLE_WIDTH,
  MIDDLE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
} from '@utils';
import {useTableModalEvent, useTableDeleteEvent} from '@hooks';

const tableColumns: ColumnsType<StorageListData> = [
  {
    title: '库位编号',
    dataIndex: 'storageLocationCode',
    key: 'storageLocationCode',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '库位名称',
    dataIndex: 'storageLocationName',
    key: 'storageLocationName',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '所在仓库',
    dataIndex: 'wareHouseName',
    key: 'wareHouseName',
    width: LARGE_TABLE_WIDTH,
  },
  {
    title: '物料类型',
    dataIndex: 'materialName',
    key: 'materialName',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '是否是混合库位',
    dataIndex: 'isNotDisable',
    key: 'isNotDisable',
    render(_, {isNotDisable}) {
      return isNotDisable === '1' ? '是' : '否';
    },
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '是否是产成品库位',
    dataIndex: 'isProduct',
    key: 'isProduct',
    render(_, {isProduct}) {
      return isProduct === '1' ? '是' : '否';
    },
    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,
  },
];

export function useHandle(refetch: () => void) {
  const [{visible, editId}, {onClose, onAdd, onEdit}] = useTableModalEvent();
  const [pendingId, onDelete] = useTableDeleteEvent(deleteStorage, refetch, {
    label: '库位',
  });

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

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