import store from '@/store'
import storage from "@/framework/utils/storage"
import lStorage from '@/utils/localStorage'
import menus from '@/data/menus'
import router from '@/router'
import httputils from '@/api/httputils'
import { logout } from "@/api/system/persagy-sso-server";
import { Message } from 'element-ui'
// const userInfo = { username: 'admin', permissions: ['demo'] }

const userInfo = null

function toLogin() {
  router.push('/login')
}

function checkMenu(menu, ps) {
  let result = { ...menu }
  if (menu.childrens) {
    // 如果有下级菜单权限,则自动拥有上级菜单权限
    result.childrens = []
    menu.childrens.forEach(child => {
      let submenu = checkMenu(child, ps)
      if (submenu) {
        result.childrens.push(submenu)
      }
    })
    return result.childrens.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) {
    console.log('router before ', to)
    if (to.path == '/auth' || to.path == '/login') {
      next()
    } else {
      if (to.meta.breadcrumbs) {
        store.dispatch('setBreadcrumb', to.meta.breadcrumbs)
      } else {
        store.dispatch('setBreadcrumb', [])
      }
      // next()
      let userInfo = store.getters['layout/userInfo']
      if (!userInfo) {
        // 本地是未登录状态, 保存目标页面地址, 去登录
        let lastRoute = { path: to.path, params: to.params, query: to.query }
        store.commit('setLastRoute', lastRoute)
        toLogin()
      } else {
        if (to.meta.breadcrumbs) {
          store.dispatch('setBreadcrumb', to.meta.breadcrumbs)
        }
        next()
      }
      return true
    }
  },

  getMenus(permissions) {
    let result = []
    let allMenus = []
    // 开发环境下展示demo页面
    // if (process.env.NODE_ENV === 'development') {
    //     allMenus = demoMenus
    // }
    allMenus = allMenus.concat(menus)
    let ps = !permissions ? {} : permissions
    console.log(ps)
    allMenus.forEach(item => {
      let menu = checkMenu(item, ps)
      if (menu) {
        result.push(menu)
      }
    })
    return result
  },

  login(username, password) {
    return new Promise((resolve, reject) => {
      if (username == 'admin') {
        resolve({ result: 'success', ssoToken: 'admin-token' })
      } else {
        resolve({ result: 'fail', message: 'username or password error' })
      }
    })
  },

  loadUserInfo() {
    return httputils.getJson(`/admin/ibms/user/userInfo`)
  },

  /**
   * 退出账户登录
   */
  async toLogout() {
    // TODO 调用登出接口（未添加）
    let ssoServer = process.env.SSO_SERVER
    let redirectUrl = window.location.protocol + '//' + window.location.host + '/adm/auth'
    const res = await logout({});
    if (res.code === 'Success') {
        store.commit('setSsoToken', null)
        lStorage.remove('');
        lStorage.remove('ssoToken')
        store.commit('layout/setUserInfo', null)
        store.commit('layout/setUserId', "")
        window.location.href = `${ssoServer}?redirectUrl=${redirectUrl}`
    } else {
        Message.error(`登出失败，失败原因：${res.message}`);
    }
  },

  toLoginPage: toLogin
}
