import {
  useContextSection,
  useQueryTableList,
  useSupertube,
  useTableExportEvent,
} from '@hooks';
import {Card} from 'antd';
import {FC} from 'react';
import {context, pageContext, searchContext} from '../context';
import {
  exportProductionRequisitionList,
  exportUnproductionRequisitionList,
  getProductionRequisitionList,
  getUnproductionRequisitionList,
} from '@apis';

import {Table, TableTools} from '@components';
import {useColumns} from './hooks';
import {useBoolean} from 'ahooks';
import AddModal from './modal';
import EditModal from './edit-modal';

const TableList: FC = function() {
  const params = useContextSection(context, state => state[0]);
  const [{data, count}, {refetch}] = useQueryTableList({
    queryFn:
      params.type === '1'
        ? getProductionRequisitionList
        : getUnproductionRequisitionList,
    params,
    pageContext,
    searchContext,
  });
  const [
    {columns, editState, visible: editVisible},
    {onClose},
  ] = useColumns(refetch);
  const [visible, {setTrue, setFalse}] = useBoolean();
  const isSuper = useSupertube();
  const [isExporting, onExport] = useTableExportEvent({
    fn:
      params.type === '1'
        ? exportProductionRequisitionList
        : exportUnproductionRequisitionList,
    context: context as any,
    pageContext,
  });

  return (
    <>
      <Card className="table-wrapper">
        <TableTools
          title={params.type === '1' ? void 0 : '非生产领料明细'}
          onAdd={isSuper ? setTrue : void 0}
          pageContext={pageContext}
          searchContext={searchContext}
          isExporting={isExporting}
          onExport={onExport}
        />

        <Table
          columns={columns}
          data={data}
          count={count}
          pageContext={pageContext}
          searchContext={searchContext}
          data-testid="production_requisition_table"
        />
      </Card>

      {isSuper && (
        <AddModal visible={visible} onClose={setFalse} onFetch={refetch} />
      )}

      {isSuper && (
        <EditModal
          visible={editVisible}
          {...editState}
          onClose={onClose}
          onFetch={refetch}
        />
      )}
    </>
  );
};

export default TableList;
