import {ColumnsType} from 'antd/es/table';
import {ReceiveListData} from '@models';
import {
  COMPANY_COL_WIDTH,
  GS_CODE_COL_WIDTH,
  MATERIAL_CODE_COL_WIDTH,
  MATERIAL_NAME_COL_WIDTH,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
  SUPPLIER_COL_WIDTH,
  WBS_COL_WIDTH,
} from '@utils';
import {useSupertube, useTableDeleteEvent} from '@hooks';
import {delReceiveOrder} from '@apis';
import {Button} from 'antd';

const columns: ColumnsType<ReceiveListData> = [
  {
    title: '采购单编号',
    dataIndex: 'orderCode',
    key: 'orderCode',
    width: GS_CODE_COL_WIDTH,
  },
  {
    title: '物料编号',
    dataIndex: 'wllbCode',
    key: 'wllbCode',
    width: MATERIAL_CODE_COL_WIDTH,
  },
  {
    title: '物料名称',
    dataIndex: 'materialName',
    key: 'materialName',
    width: MATERIAL_NAME_COL_WIDTH,
  },
  {
    title: '采购数量',
    dataIndex: 'purchaseNum',
    key: 'purchaseNum',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '到货数量',
    dataIndex: 'arrivalNum',
    key: 'arrivalNum',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '合格数量',
    dataIndex: 'qualifiedNum',
    key: 'qualifiedNum',
    render(_, {qualifiedNum}) {
      return qualifiedNum ?? '0';
    },
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '不合格数量',
    dataIndex: 'disqualificationNum',
    key: 'disqualificationNum',
    render(_, {disqualificationNum}) {
      return disqualificationNum ?? '0';
    },
    width: NORMAL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '供应商',
    dataIndex: 'supplierName',
    key: 'supplierName',
    width: SUPPLIER_COL_WIDTH,
  },
  {title: '所属公司', dataIndex: 'compName', width: COMPANY_COL_WIDTH},
  {title: 'WBS编号', dataIndex: 'wbs', width: WBS_COL_WIDTH},
];

export function useColumns(refetch: () => void) {
  const [pendingId, onDelete] = useTableDeleteEvent(delReceiveOrder, refetch, {
    label: '质检单',
  });

  const delColumns: ColumnsType<ReceiveListData> = [
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      fixed: 'right',
      width: SMALL_TABLE_WIDTH,
      render(_, {id, orderCode}) {
        return (
          <>
            <Button
              type='text'
              danger
              loading={pendingId === id}
              onClick={onDelete(id, orderCode)}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

  const isSuper = useSupertube();
  return isSuper ? [...columns, ...delColumns] : columns;
}
