import {ColumnsType} from 'antd/es/table';
import {ProductionRequisitionListData} from '@models';
import {
  HUGE_TABLE_WIDTH,
  LARGE_TABLE_WIDTH,
  MIDDLE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
} from '@utils';
import {useContextSection, useSupertube, useTableDeleteEvent} from '@hooks';
import {Button} from 'antd';
import {delProductionRequisition, delUnProductionRequisition} from '@apis';
import {context} from '../context';

const columns: ColumnsType<ProductionRequisitionListData> = [
  {
    title: '领用编号',
    dataIndex: 'askGoodsCode',
    key: 'askGoodsCode',
    width: MIDDLE_TABLE_WIDTH,
  },
  {
    title: '生产订单编号',
    dataIndex: 'productionCode',
    width: MIDDLE_TABLE_WIDTH,
  },
  {
    title: '物料编号',
    dataIndex: 'materialCode',
    key: 'materialCode',
    width: MIDDLE_TABLE_WIDTH,
  },
  {
    title: '物料名称',
    dataIndex: 'materialName',
    key: 'materialName',
    width: HUGE_TABLE_WIDTH,
  },
  {
    title: '要料数量',
    dataIndex: 'num',
    key: 'num',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '出库数量',
    dataIndex: 'outNum',
    key: 'outNum',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '库存数量',
    dataIndex: 'amount',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '所属公司',
    dataIndex: 'companyName',
    key: 'companyName',
    width: LARGE_TABLE_WIDTH,
  },
  {
    title: '领用部门',
    dataIndex: 'departmentName',
    key: 'departmentName',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '移动类型',
    dataIndex: 'moveType',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '来源类型',
    dataIndex: 'sourceType',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '分录号',
    dataIndex: 'entryNumber',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: 'WBS编号',
    dataIndex: 'wbs',
    width: NORMAL_TABLE_WIDTH,
  },
  {
    title: '申请日期',
    dataIndex: 'sqrq',
    key: 'sqrq',
    width: NORMAL_TABLE_WIDTH,
  },
];

export function useColumns(refetch: () => void) {
  const type = useContextSection(context, state => state[0].type);
  const [pendingId, onDelete] = useTableDeleteEvent(
    type === '1' ? delProductionRequisition : delUnProductionRequisition,
    refetch,
    {
      label: `${type === '1' ? '生产' : '非生产'}领料单`,
    },
  );

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

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