const utils = {
  // get and set sotorage
  storage: function(key, val=false) {
    if(!val) {
      const data = window.sessionStorage.getItem(key);
      return JSON.parse(data);
    }
    window.sessionStorage.setItem(key, JSON.stringify(val));
  },
  removeStorage: function(key) {
    window.sessionStorage.removeItem(key);
  },
  // 清除所有sessionStorage取值
  removeSessionData () {
    window.sessionStorage.clear()
  },
  toRouter: function(id = 0){
    if(!id) {
      return { currRouterName: '/mainPage', leftMenus: [] };
    }
    const { menus } = this.storage('sw_user');
    let leftMenus = menus[0].childMenus;
    if(id) {
      const menu = menus.find(item => item.menuId === id);
      if (menu && menu.childMenus) {
        leftMenus = menu.childMenus;
      } else {
        leftMenus = []
      }
    }
    // TODO , Will handle the more sub menu
    const noSubMenu = leftMenus.filter(item => {
      if (item.childMenus) {
        return item.childMenus
      } else {
        return !item.childMenus
      }
    })
    let currRouterName = noSubMenu[0].linkUrl;
    let currMenuId = noSubMenu[0].menuId;
    return { currRouterName, leftMenus,currMenuId};
  },
  removeSpace (str) { // 去掉字符串中間多余空白（保留一個空白）
    let repStr = ''
    for (let i = 0; i < str.length; i++) {
      if (str.substring(i, i + 1) !== ' ') {
        repStr = repStr + str.substring(i, i + 1)
      } else {
        if (repStr.substring(repStr.length - 1, repStr.length) !== ' ') {
          repStr = repStr + ' '
        }
      }
    }
    return repStr
  }
}

export default utils;

