import { history } from '@umijs/max';
import CryptoJS from 'crypto-js';
import { Base64 } from 'js-base64';
import { CLIENT_ID, CLIENT_SECRET, INDEX_ROUTE, LOGIN_SERVE } from './config';
import { clearSession, getSession } from './session';

type ViewType = 'default' | 'iframe' | 'urlVerify'; //模式（详细请看README）
// 获取登录信息-access_token
export const getOauthTokenInfo = (
  viewType: ViewType = 'urlVerify',
  userName?: string,
  pwd?: string,
) => {
  const token = getSession('access_token');
  if (token && token !== 'undefined') {
    history.push('/home');
    return;
  } else {
    let redirect_uri = Base64.encode(window.location.origin + INDEX_ROUTE);
    let client_id = Base64.encode(CLIENT_ID); //户端 ID
    let client_secret = Base64.encode(CLIENT_SECRET); //客户端密钥
    let username; //账号
    let password; //密码
    if (viewType === 'urlVerify') {
      username = Base64.encode(userName || '');
      password = Base64.encode(pwd || '');
    }

    let authUrl = `${LOGIN_SERVE}?viewType=${viewType}&redirect_uri=${redirect_uri}&client_id=${client_id}
      &client_secret=${client_secret}&username=${username}&password=${password}`;
    window.location.replace(authUrl);
  }
};

// 获取URL中的参数
export const getUrlParams = () => {
  var url = location.search; //获取url中"?"符后的字串
  var theRequest: any = new Object();
  if (url.indexOf('?') != -1) {
    var str = url.substr(1);
    let strs = str.split('&');
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
    }
  }
  return theRequest;
};

//退出登录
export const loinOut = () => {
  clearSession();
  getOauthTokenInfo('default');
};

// base64转字符串
export const base64ToStr = (str: string) => {
  return CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(str));
};

/**
 *将后端菜单平级处理为树结构
 systemRoots:系统的根标识，一般一个系统就一个唯一的，取systemRoots
 */
export function buildTreeSimplified(items: any[], systemRoots: string) {
  // 构建树
  const buildTree = (items: any, parentId: string) => {
    const childItems: any[] = [];
    items.forEach((item: any) => {
      const currentId = item[options.id];
      if (item[options.parentId] === parentId) {
        const child = buildTree(items, currentId);
        child.length && (item.children = child);
        childItems.push(item);
      }
    });
    return childItems;
  };

  const options = {
    parentId: 'pId', //匹配的父节点字段
    id: 'id', //匹配的id
  };
  const tree = buildTree(items, systemRoots);
  return tree;
}
