import store from '@/store'
import menusList from '@/data/menus'
import session from "@/framework/utils/storage"
import lStorage from '@/utils/localStorage'
import { MessageBox, Message } from 'element-ui'
import Bus from '@/utils/bus.js'

function toLogin() {
  let ssoServer = process.env.SSO_SERVER
  let redirectUrl = window.location.protocol + '//' + window.location.host + '/adm/auth'
  window.location.href = `${ssoServer}?redirectUrl=${redirectUrl}`
}

function checkMenu(menu, ps) {
  let result = { name: menu.name, icon: menu.icon, path: menu.path }
  if (menu.children) {
    // 如果有下级菜单权限,则自动拥有上级菜单权限
    result.children = []
    menu.children.forEach(child => {
      let submenu = checkMenu(child, ps)
      if (submenu) {
        result.children.push(submenu)
      }
    })
    return result.children.length > 0 ? result : null
  } else if (menu.opts) {
    return menu.opts.some(opt => ps[opt.permission]) ? result : null
  } else {
    // 如果没有下级菜单且没有opts属性, 菜单可以直接访问,不需要权限
    return result
  }
}

export default {
  /**
   *  路由守卫, 每次路由跳转时验证登录
   * @param {*} to
   * @param {*} from
   * @param {*} next
   */
  routerBeforeEach: async function (to, from, next) {
    store.commit('clearAxiosArr')
    const projects = store.getters['layout/projects']
    const menus = store.getters['layout/menus']
    if (to.path == '/auth' || to.path == '/nouser'||to.path=='/login') {
      next()
    } else {
      if (process.env.NO_LOGIN !== 'true') {// 登录
         let ssoToken = store.getters['ssoToken'] ? store.getters['ssoToken'] : lStorage.get("ssoToken");
         store.commit('setSsoToken', ssoToken)
         if (!ssoToken) {
           // 本地是未登录状态, 保存目标页面地址, 去登录
           let lastRoute = { path: to.path, params: to.params, query: to.query }
           store.commit('setLastRoute', lastRoute)
          //  toLogin()
          /** 
           * 调用toLogin方法修改为使用自己的登录页面，调用运维平台的登录接口
           * nh 2021.10.21
          */
          next({path: "/login"})
         } else {
           if (projects.length && menus.length) {// 存在项目列表和系统菜单
             handleRoute()
           } else {// 不存在项目列表和系统菜单
             store.dispatch('layout/loadUserInfo').then(resp => {
               console.log('store dispatch result ', resp)
              //  if (resp.code  == 'Success') {
                if (resp.result  == 'success') {
                 handleRoute();
               } else {
                 Message.error(`${resp.message}，请重新登录！`)
                //  toLogin()
                next({path: "/login"})
               }
             })
           }
         }
      } else {// 免登陆
        if (projects.length && menus.length) {// 存在项目列表和系统菜单
          handleRoute()
        } else {// 不存在项目列表和系统菜单
          // 设置默认用户
          store.commit('layout/setUserInfo', { userName: 'admin', userId: '06328a53c69a41bb8f5bb1a552c6e8d6' })
          store.commit('layout/setUserId', '06328a53c69a41bb8f5bb1a552c6e8d6')
          // 获取环境全部项目
          store.dispatch('layout/getAllProject').then(res => {
            Bus.$emit('initProjectId');
            console.log("获取项目列表成功！");
          }).catch(() => {
              console.error("获取项目列表失败！");
          });
          // 初始化项目列表
        //   store.commit('layout/setProjects', window.__systemConf.projects || [])
          // 设置默认项目id为项目列表的第一个项目
        //   let pro = store.getters['layout/projects']
        //   if (pro[0] && pro[0].id) store.commit('layout/setprojectId', pro[0].id)

          // 获取本地系统菜单
          store.commit('layout/setMenus', menusList)
          handleRoute()
        }
      }
      return true
    }
    /**
     * 路由跳转处理
     */
     function handleRoute() {
      if (
        (from.path == "/ledger/rentadd" && session.get("rentAddData") && session.get("rentAddData").length) ||
        (from.path == "/ledger/cenoteadd" && session.get("cenoteAddData") && session.get("cenoteAddData").length) ||
        (from.path == "/ledger/deviceadd" && session.get("deviceAddData") && session.get("deviceAddData").length) ||
        (from.path == "/ledger/spaceadd" && session.get("spaceAddData") && session.get("spaceAddData").length) ||
        (from.path == "/ledger/propertyadd" && session.get("propertyAddData") && session.get("propertyAddData").length) ||
        (from.path == "/ledger/partsadd" && session.get("partsAddData") && session.get("partsAddData").length) ||
        (from.path == "/ledger/systemadd" && session.get("systemAddData") && session.get("systemAddData").length)
      ) { //判断新增信息是否保存
        MessageBox.confirm("新增信息未保存，离开将丢失新增信息，是否继续？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(() => {
          let arr = from.path.split("/")
          let srt = arr[arr.length - 1].slice(0, -3)
          session.remove(`${srt}AddData`)
          next()
        }).catch(() => {
          next(false)
        })
      } else {
        if (to.meta.breadcrumbs) {
          store.dispatch('setBreadcrumb', to.meta.breadcrumbs)
        }
        next()
      }
    }
  },
  toNoUser() {
    console.log(this)
    this.$router.replace('/nouser')
  },

  toLogout() {
    // TODO	调用登出接口（未添加）
    store.commit('setSsoToken', null)
    lStorage.remove('ssoToken')
    let ssoServer = process.env.SSO_SERVER
    let redirectUrl = window.location.protocol + '//' + window.location.host + '/adm/auth'
    window.location.href = `${ssoServer}?redirectUrl=${redirectUrl}`
  },

  toLoginPage: toLogin
}
