import store from '@/store'
import demoMenus from '@/demo/demo-menus'
import menus from '@/data/menus'
import router from '@/router'
import httputils from '@/utils/httputils'
// const userInfo = { username: 'admin', permissions: ['demo'] }

const userInfo = null

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

function checkMenu(menu, ps) {
  let result = { name: menu.name, icon: menu.icon, path: menu.path, disabled: menu.disabled }
  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) {
    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 new Promise((resolve, reject) => resolve({ result: 'success', ...userInfo }))
    return httputils.getJson(`/admin/ibms/user/userInfo`)
  },

  toLogout() {
    // TODO
    router.push('/auth')
    store.commit('setSsoToken', null)
    let ssoServer = process.env.SSO_SERVER
    let redirectUrl = window.location.protocol + '//' + window.location.host + '/'
    window.location.href = `${ssoServer}/logout?redirectUrl=${redirectUrl}`
  },

  toLoginPage: toLogin
}
