import httputils from '@/utils/httputils'
import store from '@/store'
import menus from '@/data/menus'
import session from "@/framework/utils/storage"
import { MessageBox } from 'element-ui'

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

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) {
    console.log('router before ', to)
    if (to.path == '/auth' || to.path == '/nouser') {
      next()
    } else {
      let userInfo = store.getters['layout/userInfo']
      if (to.meta.breadcrumbs) {
        store.dispatch('setBreadcrumb', to.meta.breadcrumbs)
      }
      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 {
        next()
      }
      console.log("==================== user info ================", 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)
      //   }
      //   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 {
      //     next()
      //   }
      // }
      return true
    }
  },
  toNoUser() {
    console.log(this)
    this.$router.replace('/nouser')
  },

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

  toLogout() {
    // TODO
    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
}
