import Vue from "vue"
import VueRouter from "vue-router"
import cookies from 'vue-cookies'
import { userStore } from '@/store/userInfo'
import { Message } from 'element-ui'

Vue.use(VueRouter)

// 重写push||replace方法
// 先将原始push方法复制
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
// 重写
VueRouter.prototype.push = function (location, res, rej) {
  // 如果传了成功,失败的回调
  if (res && rej) {
    originPush.call(this, location, res, rej)
  } else {
    originPush.call(this, location, () => { }, () => { })
  }
}
VueRouter.prototype.replace = function (location, res, rej) {
  if (res && rej) {
    originReplace.call(this, location, res, rej)
  } else {
    originReplace.call(this, location, () => { }, () => { })
  }
}

const router = new VueRouter({
  mode: "history",
  base: import.meta.env.BASE_URL,
  routes: [
    {
      path: "/",
      redirect: '/dashboard'
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/Login.vue"),
      meta: {
        title: 'Log In Admin Console'
      }
    },
    {
      path: "/non-admin-user",
      name: "noadmin",
      component: () => import("../views/Noadmin.vue"),
      meta: {
        title: 'Non-admin User'
      }
    },
    {
      path: "/sign-up",
      name: "Create",
      component: () => import("../views/Create.vue"),
      meta: {
        title: 'Sign Up Admin Console'
      }
    },
    {
      path: "/free-trial-admin-console-signup",
      name: "FreeTrial",
      component: () => import("../views/FreeSign.vue"),
      meta: {
        title: 'Sign up | Free Trial Admin Console'
      }
    },
    {
      path: "/forget-password",
      name: "forgotpassword",
      component: () => import("../views/forgotpassword.vue"),
      meta: {
        title: 'Forget Password | Admin Account'
      }
    },
    {
      path: "/product/custom",
      name: "productCustom",
      component: () => import("../views/Product/Custom.vue"),
      meta: {
        title: 'Product | Admin Console'
      }
    },
    {
      path: "/product/pay",
      name: "productPay",
      component: () => import("../views/Product/Pay.vue"),
      meta: {
        title: 'Product | Admin Console'
      }
    },
    {
      path: "/product/:id",
      name: "productCode",
      component: () => import("../views/Product/ID.vue"),
      meta: {
        title: 'Product | Admin Console'
      }
    },
    {
      path: '',
      name: 'container',
      component: () => import("../views/Container.vue"),
      children: [
        {
          path: "/dashboard",
          name: "dashboard",
          component: () => import("../views/Dashboard.vue"),
          meta: {
            title: 'Home | Admin Console'
          }
        },
        {
          path: "/product",
          name: "product",
          component: () => import("../views/Product/Index.vue"),
          meta: {
            title: 'Product | Admin Console'
          }
        },
        {
          path: "/order",
          name: "productManagement",
          component: () => import("../views/ProductManagement.vue"),
          meta: {
            title: 'Order | Admin Console'
          }
        },
        {
          path: "/manage-team",
          name: "ManageTeam",
          component: () => import("../views/TeamManagement/ManageTeam.vue"),
          meta: {
            title: 'Manage Team | Admin Console'
          }
        },
        {
          path: "/manage-team/edit-team",
          name: "EditManageTeam",
          component: () => import("../views/TeamManagement/ManageTeamOperate.vue"),
          meta: {
            title: 'Manage Team | Admin Console'
          }
        },
        {
          path: "/manage-team/create-team",
          name: "CreateManageTeam",
          component: () => import("../views/TeamManagement/ManageTeamOperate.vue"),
          meta: {
            title: 'Manage Team | Admin Console'
          }
        },
        {
          path: "/manage-member",
          name: "ManageMember",
          component: () => import("../views/TeamManagement/ManageMember.vue"),
          meta: {
            title: 'Manage Member | Admin Console'
          }
        },
        {
          path: "/manage-member/edit-member",
          name: "EditManageMember",
          component: () => import("../views/TeamManagement/ManageMember/EditManageMember.vue"),
          meta: {
            title: 'Manage Member | Admin Console'
          }
        },
        {
          path: "/manage-member/add-member",
          name: "AddManageMember",
          component: () => import("../views/TeamManagement/ManageMember/AddManageMember.vue"),
          meta: {
            title: 'Manage Member | Admin Console'
          }
        },
        {
          path: "/manage-admin",
          name: "manageAdmin",
          component: () => import("../views/manageAdmin.vue"),
          meta: {
            title: 'Manage Admin | Admin Console'
          }
        },
        {
          path: "/manage-admin/edit-admin",
          name: "editAdmin",
          component: () => import("../views/MenageAdmin/editAdmin.vue"),
          meta: {
            title: 'Manage Admin | Admin Console'
          }
        },
        {
          path: "/manage-admin/add-admin",
          name: "addAdmin",
          component: () => import("../views/MenageAdmin/addAdmin.vue"),
          meta: {
            title: 'Manage Admin | Admin Console'
          }
        },
        {
          path: "/license-management",
          name: "licenseManage",
          component: () => import("../views/LicenseManage.vue"),
          meta: {
            title: 'Manage License | Admin Console'
          }
        },
        {
          path: "/assign-license",
          name: "assignlicense",
          component: () => import("../views/Assignlicense.vue"),
          meta: {
            title: 'Manage License | Admin Console'
          }
        },
        {
          path: "/batch-cancel-license",
          name: "volumecancel",
          component: () => import("../views/VolumeCancel.vue"),
          meta: {
            title: 'Manage License | Admin Console'
          }
        },
        {
          path: "/manage-device",
          name: "device",
          component: () => import("../views/Device.vue"),
          meta: {
            title: 'Manage Device | Admin Console'
          }
        },
        {
          path: "/download",
          name: "download",
          component: () => import("../views/Download.vue"),
          meta: {
            title: 'Admin Console'
          }
        },
        {
          path: "/samlsetting",
          name: "samlsetting",
          component: () => import("../views/SamlSetting.vue"),
          meta: {
            title: 'Console Settings | Admin Console'
          }
        },
        {
          path: "/settings",
          name: "settings",
          component: () => import("../views/Settings.vue"),
          meta: {
            title: 'Console Settings | Admin Console'
          }
        },
        {
          path: "/support",
          name: "support",
          component: () => import("../views/Support.vue"),
          meta: {
            title: 'Support | Admin Console'
          }
        },
        {
          path: "/reseller-manage-product",
          name: "ResellerProduct",
          component: () => import("../views/Reseller/Product.vue"),
          meta: {
            title: 'Manage Product | Admin Console for Reseller'
          }
        },
        {
          path: "/reseller-manage-license",
          name: "ResellerLicense",
          component: () => import("../views/Reseller/License.vue"),
          meta: {
            title: 'Manage License | Admin Console for Reseller'
          }
        },
      ]
    },
    { // 当没有匹配到正确路由的时候，匹配404组件
      path: '*',
      name: "404",
      component: () => import("../views/notFind.vue"),
    }
  ],
})
router.beforeEach((to, from, next) => {
  const whiteList = '/login'
  const token = cookies.get('accessToken')
  //如果没有token，并且去首页
  if (!token && to.path === '/dashboard') {
    next('/login')
  }
  //路由守卫，进行权限判断
  if (token === 'expired') {
    cookies.remove('accessToken')
    // 判断是否登录
    Message({
      duration: 5000,
      message: 'Your session has expired. Please log in again.',
      type: "error",
    })
    next('/login')
  } else if (token && to.path !== whiteList && to.path !== '/sign-up' && to.path !== '/non-admin-user' && to.path !== '/forget-password' && to.path !== '/free-trial-admin-console-signup') {
    // 判断权限
    if (userStore().user.role?.indexOf("2") !== -1 || userStore().user.role?.indexOf("1") !== -1 || userStore().user.role?.indexOf("4") !== -1) {
      // 目录设置非超级管理员不可进入
      if (to.path === '/samlsetting' && userStore().user.role?.indexOf("1") === -1) {
        next('/non-admin-user')
      } else {
        next()
      }
    } else {
      next('/non-admin-user')
      // next('/product?type=isNoAdmin')
    }
  } else {
    next()
  }
})

// 设置title
router.beforeEach((to, from, next) => {
  if (to && to.meta && to.meta.title) {
    document.title = to.meta.title
  }
  let head = document.getElementsByTagName('head')
  let meta = document.createElement('meta')
  document.querySelector('meta[name="keywords"]').setAttribute('content', 'Admin Console allows you to manage products, teams, licenses, and devices. Join Volume License Program to access the Admin Console now!')
  document.querySelector('meta[name="description"]').setAttribute('content', 'Admin Console, manage licenses, assign licenses, cancel licenses, volume licenses')
  meta.content = to.meta.content
  head[0].appendChild(meta)

  next()
})

export default router
