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

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(code: string) {
  const [{page, pageSize}] = usePage(pageContext);

  function onExport() {
    goodsExport({
      itemNumber: code,
      page: String(page),
      limit: String(pageSize),
    }).then((res: Blob) => exportFile(res));
  }

  return onExport;
}
