import {Card} from 'antd';
import {FC} from 'react';
import {ColumnsType} from 'antd/es/table';
import {StockListData} from '@models';
import {Table, TableTools} from '@components';
import {context, pageContext, searchContext, transformState} from '../context';
import {
  COMPANY_COL_WIDTH,
  LARGE_TABLE_WIDTH,
  MATERIAL_CODE_COL_WIDTH,
  MATERIAL_NAME_COL_WIDTH,
  MATERIAL_TYPE_COL_WIDTH,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
  SUPPLIER_COL_WIDTH,
  WBS_COL_WIDTH,
} from '@utils';
import {exportStockList, getStockList} from '@apis';
import {
  useContextSection,
  useQueryTableList,
  useTableExportEvent,
} from '@hooks';

const columns: ColumnsType<StockListData> = [
  {title: '物料编号', dataIndex: 'code', width: MATERIAL_CODE_COL_WIDTH},
  {title: '物料名称', dataIndex: 'name', width: MATERIAL_NAME_COL_WIDTH},
  {
    title: '库位名称',
    dataIndex: 'storageLocationName',
    width: NORMAL_TABLE_WIDTH,
  },
  {title: '数量', dataIndex: 'sum', width: SMALL_TABLE_WIDTH, align: 'right'},
  {title: '计量单位', dataIndex: 'unitOfMeasurement', width: SMALL_TABLE_WIDTH},
  {title: '物料类型', dataIndex: 'wllbClass', width: MATERIAL_TYPE_COL_WIDTH},
  {title: '物料类别', dataIndex: 'partType', width: NORMAL_TABLE_WIDTH},
  {title: '所属仓库', dataIndex: 'warehouseName', width: LARGE_TABLE_WIDTH},
  {title: '所属公司', dataIndex: 'companyName', width: COMPANY_COL_WIDTH},
  {title: '公司编号', dataIndex: 'accountSleeve', width: SMALL_TABLE_WIDTH},
  {title: '供应商', dataIndex: 'supplierName', width: SUPPLIER_COL_WIDTH},
  {title: 'WBS编号', dataIndex: 'wbs', width: WBS_COL_WIDTH},
  {
    title: '安全库存',
    dataIndex: 'maxNum',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
  {
    title: '库龄(天)',
    dataIndex: 'day',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
  },
];

const TableList: FC = function () {
  const params = useContextSection(context, function ([state]) {
    return transformState(state);
  });

  const [{data, count}] = useQueryTableList({
    queryFn: getStockList,
    params,
    pageContext,
    searchContext,
  });

  const [isExporting, onExport] = useTableExportEvent({
    pageContext,
    context,
    fn: exportStockList,
    parseParams: transformState,
  });

  return (
    <Card className='table-wrapper'>
      <TableTools
        pageContext={pageContext}
        searchContext={searchContext}
        isExporting={isExporting}
        onExport={onExport}
      />

      <Table
        data-testid='stock_table'
        data={data}
        count={count}
        pageContext={pageContext}
        searchContext={searchContext}
        columns={columns}
      />
    </Card>
  );
};

export default TableList;
