import { Dialog, Modal } from 'antd-mobile';
import {
  getRoutesConfig,
  V4_Login,
  V3_Login
} from '../../services/login/LoginController';
import { preloadFunctionImage } from '../../utils/util';
import { startLoading } from '../Loading';
import { getDictionaryValue } from '../../services/common/CommonController';
import { useModel, history } from '../../utils/umiExport';
import { setV4AccessToken, saveUserData } from '../../utils/loginUtil';
import EncryptUtil from '../../utils/EncryptUtil';
interface userProps {
  username: string;
  password: string;
}
export const useLogin = () => {
  const { initialState, setInitialState }: any = useModel("@@initialState")
  const { version, modules } = initialState.settings
  const sortFunctions = (val: Array<any>) => {
    const arr: Array<any> = Object.assign([], val);
    if (arr && arr.length > 0) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = 0; j < arr.length - 1 - i; j++) {
          if (arr[j].position > arr[j + 1].position) {
            let temp = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = temp;
          }
        }
      }
      if (arr.length > 4) {
        return arr.slice(0, 4);
      }
      return arr;
    }
    return val;
  };
  const onFinish = async (value: userProps) => {
    const { username, password } = value;
    if (!username) {
      Modal.alert({
        content: '账号不能为空',
      });
      return;
    }
    if (!password) {
      Modal.alert({
        content: '密码不能为空',
      });
      return;
    }
    if (username && password) {
      const loading = startLoading();
      try {
        if (version === 'V4') {
          const loginData = await V4_Login(username, password);
          if (loginData && loginData.access_token) {
            setV4AccessToken(loginData);
            // RSA 加密 { username, password } 整体，用于 getRoutesConfig 鉴权
            const data = EncryptUtil.RSAEncrypt(JSON.stringify({ username, password }));
            const userData = await getRoutesConfig(data, modules!);
            const { functions } = userData;
            const sortFunction = await preloadFunctionImage(sortFunctions(functions));
            const dictionary = await getDictionaryValue();
            saveUserData(userData, sortFunction, dictionary);
            setInitialState({ ...initialState,
              func: sortFunction, currentUser: userData, dictionary,
              token: loginData.access_token });
            history.push('/main');
          } else {
            Dialog.alert({ content: loginData.msg });
          }
        } else if (version === 'V3') {
          const loginData = await V3_Login(username, password);
          if (loginData.states && loginData.states === '登录成功') {
            const data = EncryptUtil.RSAEncrypt(JSON.stringify({ username, password }));
            const userData = await getRoutesConfig(data, modules!);
            const { functions } = userData;
            const sortFunction = await preloadFunctionImage(sortFunctions(functions));
            const dictionary = await getDictionaryValue();
            saveUserData(userData, sortFunction, dictionary);
            setInitialState({ ...initialState, func: sortFunction, currentUser: userData, dictionary });
            history.push('/main');
          } else {
            Dialog.alert({ content: `系统登录失败` });
          }
        }
      } catch (error) {
        Dialog.alert({ content: '登录失败' });
      } finally {
        loading.close();
      }
    }
  };
  return {
    onFinish,
  };
};
