import {RangeValue} from '@components';
import type {Dayjs} from 'dayjs';
import {useContextSection, useExportFile, usePage} from '@hooks';
import {context, pageContext} from '../context';
import {containerScrapLogExport} from '@apis';

export function useSearch(dates: RangeValue<Dayjs>) {
  const dispatch = useContextSection(context, state => state[1]);

  function onSearch() {
    const startTime = dates?.[0]?.format('YYYY-MM-DD') ?? '',
          endTime = dates?.[1]?.format('YYYY-MM-DD') ?? '';
    dispatch({type: 'SEARCH', payload: {startTime, endTime}});
  }

  return onSearch;
}

export function useExport() {
  const params = useContextSection(
    context,
    function([{id, startTime, endTime}]) {
      return {containerName: id, startTime, endTime};
    },
  );
  const [{page, pageSize}] = usePage(pageContext);
  const [isExporting, mutate] = useExportFile(containerScrapLogExport);

  function onExport() {
    mutate({
      page: String(page),
      limit: String(pageSize),
      ...params,
    });
  }

  return [isExporting, onExport] as const;
}
