import {useContextSection, useExportFile, usePage} from '@hooks';
import {useState} from 'react';
import {context, pageContext} from '../context';
import {goodsExport} from '@apis';

export function useSearch() {
  const [value, setValue] = useState('');
  const dispatch = useContextSection(context, ([, dispatch]) => dispatch);
  const [, {onCurrentPageChange}] = usePage(pageContext);

  function onSearch() {
    onCurrentPageChange(1);
    dispatch({type: 'SEARCH', payload: {number: value}});
  }

  return [{value}, {onSearch, onChange: setValue}] as const;
}

export function useExport() {
  const [{page, pageSize}] = usePage(pageContext);
  const [isExporting, mutate] = useExportFile(goodsExport);
  const code = useContextSection(context, ([{number}]) => number);

  function onExport() {
    mutate({
      itemNumber: code,
      page: String(page),
      limit: String(pageSize),
    });
  }

  return [isExporting, onExport] as const;
}
