import {FC} from 'react';
import {useDicionaryType} from '../hooks';
import {Card} from 'antd';
import {Table, TableTools} from '@components';
import {context, pageContext, searchContext} from '../context';
import PutModal from './modal';
import {getDictionaryList} from '@apis';
import {useContextSection, useQueryTableList, useSupertube} from '@hooks';
import {OriginalListParams, GetDictionaryListParams} from '@models';
import StorageModal from './type-modal';
import {useHandle} from './hooks';

const TableList: FC = function () {
  const type = useDicionaryType();
  const params = useContextSection(
    context,
    function ([{name, code, warehouseType}]) {
      return {
        name,
        code,
        type,
        warehouseType,
      } as OriginalListParams<GetDictionaryListParams>;
    },
  );
  const [{data, count}, {refetch}] = useQueryTableList({
    queryFn: getDictionaryList,
    params,
    pageContext,
    searchContext,
  });
  const [
    {columns, visible, editId, editStoreVisible, storeId},
    {onAdd, onClose, onEditStoreClose},
  ] = useHandle(refetch);
  const isSuper = useSupertube();
  return (
    <>
      <Card className='table-wrapper'>
        <TableTools
          title={type.replace('字典', '') + '管理'}
          onAdd={isSuper ? onAdd : void 0}
          pageContext={pageContext}
          searchContext={searchContext}
        />

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

      {isSuper && (
        <PutModal
          id={editId.id}
          tldId={editId.tldId}
          onClose={onClose}
          onFetch={refetch}
          visible={visible}
        />
      )}

      {type === '仓库' && (
        <StorageModal
          visible={editStoreVisible}
          {...storeId}
          onClose={onEditStoreClose}
          onFetch={refetch}
        />
      )}
    </>
  );
};

export default TableList;
