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

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

  function onChange(val: string) {
    setState(val);
  }

  return [state, onChange] as const;
}

export function useHandle(value: string) {
  const [{name}, dispatch] = useContext(context);
  const [{page, pageSize}, {onCurrentPageChange}] = usePage(pageContext);

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

  function onExport() {
    exportRole({
      page: String(page),
      limit: String(pageSize),
      roleName: name,
    }).then(function(res: Blob) {
      exportFile(res);
    });
  }

  return {onSearch, onExport};
}
