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} from '../context';
import {
  HUGE_TABLE_WIDTH,
  LARGE_TABLE_WIDTH,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
} from '@utils';
import {exportStockList, getStockList} from '@apis';
import {
  useContextSection,
  useQueryTableList,
  useTableExportEvent,
} from '@hooks';

const columns: ColumnsType<StockListData> = [
  {title: '物料编号', dataIndex: 'code', width: LARGE_TABLE_WIDTH},
  {title: '物料名称', dataIndex: 'name', width: HUGE_TABLE_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: NORMAL_TABLE_WIDTH},
  {title: '物料类别', dataIndex: 'partType', width: NORMAL_TABLE_WIDTH},
  {title: '所属仓库', dataIndex: 'warehouseName', width: LARGE_TABLE_WIDTH},
  {title: '所属公司', dataIndex: 'companyName', width: LARGE_TABLE_WIDTH},
  {title: '公司编号', dataIndex: 'accountSleeve', width: SMALL_TABLE_WIDTH},
  {title: '供应商', dataIndex: 'supplierName', width: LARGE_TABLE_WIDTH},
  {title: 'WBS编号', dataIndex: 'wbs', width: NORMAL_TABLE_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, state => state[0]);

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

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

  return (
    <Card className='table-wrapper'>
      <TableTools
        onRefresh={refetch}
        isRefreshing={isFetching}
        isExporting={isExporting}
        onExport={onExport}
      />

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

export default TableList;
