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

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

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

  return [state, onChange] as const;
}

export function useHandle(name: string, code: string) {
  const dispatch = useContextSection(context, state => state[1]);
  const [{page, pageSize}, {onCurrentPageChange}] = usePage(pageContext);

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

  function onExport() {
    exportDepartment({
      page: page.toString(),
      limit: pageSize.toString(),
      code,
      departmentName: name,
    })
      .then(function(res: Blob) {
        exportFile(res);
      })
      .catch(function() {
        message.error(EXPORT_ERROR_TIPS);
      });
  }

  return {onSearch, onExport};
}
