import {Table, TableTools} from '@components';
import {
  useContextSection,
  useQueryTableList,
  useTableExportEvent,
} from '@hooks';
import {Card} from 'antd';
import {FC} from 'react';
import {context, pageContext, searchContext} from '../context';
import {exportInventory, getInventoryChildList} from '@apis';
import {ColumnsType} from 'antd/es/table';
import {InventoryChildListData} from '@models';
import {
  HUGE_TABLE_WIDTH,
  MIDDLE_TABLE_WIDTH,
  MODAL_PAGE_SIZE_LIST,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
} from '@utils';

const columns: ColumnsType<InventoryChildListData> = [
  {title: '物料编号', dataIndex: 'wllbCode', width: MIDDLE_TABLE_WIDTH},
  {title: '物料名称', dataIndex: 'name', width: HUGE_TABLE_WIDTH},
  {
    title: '物料数量',
    dataIndex: 'amount',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
    render(_, {amount}) {
      return amount ? parseInt(amount) : '0';
    },
  },
  {
    title: 'GS物料数量',
    dataIndex: 'gsAmount',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
    render(_, {gsAmount}) {
      return gsAmount ? parseInt(gsAmount) : '0';
    },
  },
  {
    title: '盘点数量',
    dataIndex: 'plateAmount',
    width: SMALL_TABLE_WIDTH,
    align: 'right',
    render(_, {plateAmount}) {
      return plateAmount ? parseInt(plateAmount) : '0';
    },
  },
  {title: '所属公司', dataIndex: 'accountName', width: NORMAL_TABLE_WIDTH},
];

const TableList: FC = function () {
  const params = useContextSection(context, state => state[0]);
  const [{isFetching, data, count}, {refetch}] = useQueryTableList({
    queryFn: getInventoryChildList,
    pageContext,
    searchContext,
    params,
  });
  const [isExporting, onExport] = useTableExportEvent({
    fn: exportInventory,
    pageContext,
    context,
  });

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

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

export default TableList;
