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

export function useField() {
  const [state, setState] = useState({name: '', code: ''});

  function onChnge(key: 'name' | 'code') {
    return function(value: string) {
      setState(prev => ({...prev, [key]: value}));
    };
  }

  return [state, onChnge] as const;
}

export function useSearch(name: string, code: string) {
  const dispatch = useContextSection(context, ([,dispatch]) => dispatch);
  const [, {onCurrentPageChange}] = usePage(pageContext);

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

  return onSearch;
}

export function useExport(name: string, code: string) {
  const [{page, pageSize}] = usePage(pageContext);

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

  return onExport;
}
