import {FilterSelectorModal, FilterTool} from '@components';
import {
  useContextSection,
  useFilterDB,
  useFilterField,
  usePage,
  useRangeDate,
  useTableSearchToolEvents,
} from '@hooks';
import {FC} from 'react';
import {context, pageContext, searchContext} from '../context';
import {fixedMap, sourceMap} from './state';

const Filter: FC = function () {
  const [{dates, start, end}, onDatesChange] = useRangeDate();
  const [fields, {onChange, resetState}] = useFilterField(
    {
      orderCode: '',
      type: '1' as '1' | '2',
      materialName: '',
      supplierId: '',
      wllbCode: '',
    },
    true,
  );

  const [, {onCurrentPageChange}] = usePage(pageContext);
  const [visible, {onSearch, onReset, onShowModal, onCloseModal}] =
    useTableSearchToolEvents(
      context,
      {...fields, startTime: start, endTime: end},
      {
        searchCallback() {
          // 在useQuerySearch的参数变化该页面前触发
          // 因为这里可能需要变更查询函数
          onCurrentPageChange(1);
        },
        resetCallback() {
          resetState();
          onDatesChange([null, null]);
        },
      },
    );
  const [filterList, {set}] = useFilterDB();
  const {isSearching} = useContextSection(searchContext, state => state[0]);

  return (
    <>
      <FilterTool
        onSearch={onSearch}
        onChange={onChange}
        fields={{...fields, startTime: start, endTime: end}}
        dates={dates}
        onDatesChange={onDatesChange}
        fixedMap={fixedMap}
        sourceMap={sourceMap}
        onReset={onReset}
        isSearching={isSearching}
        filterData={filterList}
        onFilter={onShowModal}
        testId='purchase_filter'
      />

      <FilterSelectorModal
        source={filterList}
        visible={visible}
        onClose={onCloseModal}
        filtermap={sourceMap}
        onConfirm={set}
      />
    </>
  );
};

export default Filter;
