import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import NotFound from '@/views/NotFound.vue'
import Login from '@/views/Login/index.vue'
import req from '@/request'
import uc from '@/api/uc.js'
import portal from '@/api/portal.js'
//路由
import mainRouter from '@/router/module-router'
import customSystemRouter from '@/router/custom-system-router'
import bigScreenRouter from '@/router/bigScreenRouter'
import Layout from '@/components/layout/Layout.vue'
// 消息组件
import { Message } from 'element-ui'

import SparkMD5 from 'spark-md5'


Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    // 重定向到login
    {
      path: '/',
      redirect: {
        name: 'NotFound'
      }
    },
    {
      path: '/notFound',
      name: 'NotFound',
      component: NotFound,
      meta: {
        anonymous: true
      }
    },
    // 登录页面
    // {
    //   path: '/login',
    //   name: 'login',
    //   component: Login,
    //   meta: {
    //     single: true,
    //     anonymous: true
    //   }
    // },
    // 重置密码
    {
      path: '/resetPwdView',
      name: 'resetPwdViewInner',
      props: true,
      component: () => import('@/views/ResetPwdView.vue')
    },
    // 跳转鉴权等待页面
    {
      path: '/safety',
      name: 'safety',
      component: () => import('@/views/Loading.vue'),
      meta: {
        single: true,
        anonymous: true
      }
    },
    {
      path: '/patrol',
      name: 'patrol',
      component: () => import('@/views/Loading.vue'),
      meta: {
        single: true,
        anonymous: true
      }
    },
    {
      path: '/websocketCheck',
      name: 'websocketCheck',
      component: () => import('@/views/WebsocketCheck.vue'),
      meta: {
        single: true,
        anonymous: true
      }
    },
    {
      path: '/eventRegistration',
      name: 'eventRegistrationSingle',
      component: () => import('@/views/patrolAndRescue/commandDispatch/EventRegistration')
    },
    {
      path: '/informatiOnForAttention',
      name: 'informatiOnForAttentionSingle',
      component: () => import('@/views/patrolAndRescue/operationalMonitoring/informatiOnForAttention')
    },
    {
      path: '/specialWarningInformation',
      name: 'specialWarningInformationSingle',
      component: () => import('@/views/patrolAndRescue/operationalMonitoring/specialWarningInformation')
    },
    {
      path: '/informatiOnForAttentionPublish',
      name: 'informatiOnForAttentionPublishSingle',
      component: () => import('@/views/patrolAndRescue/operationalMonitoring/informatiOnForAttention/publish.vue')
    },
    {
      path: '/specialWarningInformationPublish',
      name: 'specialWarningInformationPublishSingle',
      component: () => import('@/views/patrolAndRescue/operationalMonitoring/specialWarningInformation/publish.vue')
    },
    // 大屏页面安全生产
    ...bigScreenRouter,


    // 后台页面
    {
      path: '/platLayout',
      name: 'platLayout',
      component: Layout,
      meta: {
        single: true,
        anonymous: true
      },
      children: [
        // 自定义前台路由
        ...customSystemRouter,
        // 需要在系统菜单中配置的路由
        ...mainRouter,
        // 404页面
        {
          path: '/:catchAll(.*)',
          component: NotFound,
          meta: {
            // single: true
          }
        }
      ]
    },

    // 404页面
    {
      path: '/:catchAll(.*)',
      component: NotFound,
      meta: {
        // single: true
      }
    }
  ]
})


const createRouter = () =>
  new Router({
    mode: 'history',
    routes: []
  })

//重写动态添加路由方法
router.$addRoutes = params => {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher //重置路由规则
  router.addRoutes(params) // 添加路由
}

//动态新增二级路由
router.addList = () => false


let registerRouteFresh = true

const ssoRedirect = () => {
  if (window.ssoConfig.mode === 'cas') {
    let service = window.location.href
    localStorage.setItem('service', service)
    window.location.href = window.ssoConfig.url + '?service=' + service
  } else if (window.ssoConfig.mode === 'oauth') {
    if (!window.ssoConfig.clientId) {
      throw 'oauth模式下必须提供clientId'
    }
    const service = window.location.href
    localStorage.setItem('service', service)
    window.location.href = `${window.ssoConfig.url}?response_type=code&client_id=${window.ssoConfig.clientId}&redirect_uri=${service}`
  }
}

const handelShortUrl = (to, from, next) => {
  req
    .get(
      '${portal}/portal/shorturlManage/v1/getLongUrlByShortUrl?shortUrl=' +
      to.fullPath.substr(1),
      '',
      false
    )
    .then(resp => {
      if (resp && resp.data && resp.data.state) {
        store
          .dispatch(
            'login/validAndCompletedCurrent',
            resp.data.value.guestToken
          )
          .then(() => {
            next({
              path: resp.data.value.url
            })
          })
          .catch(() => {
            logoutAndCleanUp(to, from, next)
          })
      } else {
        next({
          path: '/messageFillPage/' + resp.data.message
        })
      }
    })
    .catch(() => {
      logoutAndCleanUp(to, from, next)
    })
}
const getAllDict = () => {
  portal
    .getSysDict()
    .then((data) => {
      if (data) {
        sessionStorage.setItem(
          'dict_data',
          JSON.stringify(data)
        )
      }
    })
    .catch((err) => {
      console.log(err, '字典err')
    })
}

const logoutAndCleanUp = (to, from, next) => {
  store.dispatch('login/logoutAndCleanUp').then(() => {
    if (window.ssoConfig.mode && window.ssoConfig.mode !== 'jwt') {
      ssoRedirect()
    } else if (!window.ssoConfig.mode || window.ssoConfig.mode === 'jwt') {
      window.location.replace(window.context.defaultLoginUrl)
    } else {
      throw '登录失败'
    }
  })
}

const removeUrlParams = (param) => {
  const url = new URL(window.location)
  url.searchParams.delete(param)
  window.history.replaceState({}, '', url)
}

const decodeToken = (key) => {
  let sparkStr = ''
  let spark = new SparkMD5()
  spark.append(key)
  sparkStr = spark.end()

  console.log('sparkStr', sparkStr)

  let Base64 = require('js-base64').Base64
  let token = Base64.encode(sparkStr)

  return token
}


// 通过账号登录
const accountLogin = (userInfo, next, name, publishId = '') => {
  store.dispatch('login/loginByPrincipal', userInfo).then((loginStatus) => {
    if (loginStatus && loginStatus == true) {
      getAllDict()
      // 获取当前用户的按钮、方法权限
      store.dispatch(
        'menu/getCurrentUserMethodAuth'
      )
      //获取前台页面所有菜单
      store
        .dispatch('menu/actionFrontMenus')
        .then((res) => {
          if (res.length) {
            store
              .dispatch(
                'login/checkUserInfoState'
              )
              .then((isFinishUserInfo) => {
                if (!isFinishUserInfo) {
                  next({
                    path: '/platLayout/personalInfo'
                  })
                } else {
                  // 事件登记
                  if (name === 'eventRegistrationSingle') {
                    next({
                      path: '/eventRegistration'
                    })
                  } else if (name === 'informatiOnForAttentionSingle') {
                    next({
                      path: '/informatiOnForAttention'
                    })
                  } else if (name === 'specialWarningInformationSingle') {
                    next({
                      path: '/specialWarningInformation'
                    })
                  } else if (name === 'informatiOnForAttentionPublishSingle') {
                    next({
                      path: '/informatiOnForAttentionPublish',
                      query: {
                        publishId
                      }
                    })
                  } else if (name === 'specialWarningInformationPublishSingle') {
                    next({
                      path: '/specialWarningInformationPublish',
                      query: {
                        publishId
                      }
                    })
                  } else {
                    // 跳转到权限页面
                    let { children } = res && res.find((i) => i.alias === 'normal')
                    const getPath = (treeData, path = '') => path + `/${treeData[0].alias}`
                    next({
                      path: getPath(children, '/platLayout')
                    })
                  }
                }
              })
          } else {
            Message.error('抱歉！您尚无可访问页面，请联系管理员添加！')
          }
        })
    }
  })
}

const mvueLogin = (ticket, next, name) => {
  // 3.携带ticket做用户鉴权；
  store.dispatch('login/validAndCompletedCurrent', ticket)
    .then(() => {
        getAllDict()
        store.dispatch('menu/getCurrentUserMethodAuth')
        // 初始化菜单
        store
        .dispatch('menu/actionFrontMenus', true)
        .then((res) => {
          if (res.length) {
            store
              .dispatch(
                'login/checkUserInfoState'
              )
              .then((isFinishUserInfo) => {
                if (!isFinishUserInfo) {
                  next({
                    path: '/platLayout/personalInfo'
                  })
                } else {
                    // 跳转到权限页面
                    let { children } = res && res.find((i) => i.alias === 'normal')
                    const getPath = (treeData, path = '') => path + `/${treeData[0].alias}`
                    next({
                      path: getPath(children, '/platLayout')
                    })
                    removeUrlParams('token')
                  }
              })
          } else {
            Message.error('抱歉！您尚无可访问页面，请联系管理员添加！')
          }
        })
    })
}

router.beforeEach(async (to, from, next) => {
  // 后台跳转前台
  if (to.query.token) {
      let ticket = to.query.token
      mvueLogin(ticket, next)
  }

  // 驾驶舱登录到事件登记或者工作台携带tokenKey
  if ((to.name === 'eventRegistrationSingle' || to.name === 'informatiOnForAttentionSingle' || to.name === 'specialWarningInformationSingle' || to.name === 'informatiOnForAttentionPublishSingle' || to.name === 'specialWarningInformationPublishSingle' || to.name === 'patrol') && to.query.tokenKey) {
    decodeToken('admin' + 'Artfess@024')
    let data = {
      key: to.query.tokenKey
    }
    let token = {
      token: '',
      tokenKey: to.query.tokenKey
    }
    uc.authFormUserTokenKey(data)
      .then((res) => {
        if (res.success) {
          token.token = res.data
          uc.authUserInfo(token).then((res) => {
            if (res.success) {
              //同步后获取用户名密码登录
              let key = 'Artfess@024'
              const decodeTokenStr = decodeToken(res.data.userCode + key)
              const publishId = to.query.publishId || ''
              accountLogin(
                {
                  account: res.data.userCode,
                  token: decodeTokenStr,
                  password: ''
                },
                next,
                to.name,
                publishId
              )
            } else {
              Message.error(res.msg)
              next({ path: '/login' })
            }
          })
        } else {
          Message.error(res.msg)
          window.location.replace(window.context.defaultLoginUrl)
        }
      })
      .catch((err) => {
        Message.error(err)
        window.location.replace(window.context.defaultLoginUrl)
      })
  }

  // 统一门户到携带ptk登录
  if ((to.name === 'safety' || to.name === 'patrol') && to.query.ptk) {
    const ptk = to.query.ptk
    uc.validateKeyAndGetUser(ptk)
      .then((res) => {
        if (res.state) {
          console.log(res)
          const account = res.value.account || ''
          let key = 'Artfess@024'
          const decodeTokenStr = decodeToken(account + key)
          accountLogin(
            {
              account: account,
              token: decodeTokenStr,
              password: ''
            },
            next,
            to.name
          )
        } else {
          Message.error('验证失败')
          window.location.replace(window.context.defaultLoginUrl)
        }
      })
      .catch((err) => {
        Message.error(err || '验证失败')
        window.location.replace(window.context.defaultLoginUrl)
      })
  }


  store.dispatch('menu/getAllmenus', {}).then(menus => {
    //href菜单不进这段代码
    if (to.fullPath.indexOf('href') === -1) {
      let alias = to.fullPath.split('/')[1]
      for (let i = 0; i < menus.length; i++) {
        if (menus[i].alias === alias) {
          store.dispatch('menu/getCurrentMenu', {
            alias: menus[i].alias,
            name: menus[i].name
          })
          break
        }
      }
    }
  })
  if (to.fullPath.startsWith('/surl/')) {
    handelShortUrl(to, from, next)
    return
  }

  // 1.当前为单点登录模式，且要路由到login页面，则做单点登录重定向；
  if (
    to.name === 'login' &&
    window.ssoConfig.mode &&
    window.ssoConfig.mode !== 'jwt'
  ) {
    // 单点登录时如果已经携带了code或者ticket时，如果是/login路径需要跳转到默认页面（解决反复跳转的问题）
    if (
      (window.ssoConfig.mode === 'cas' || window.ssoConfig.mode === 'oauth') &&
      (to.query.code || to.query.ticket)
    ) {
      window.location.href = window.location.href.replace('/login', '')
      return
    } else {
      ssoRedirect()
    }
  }

  if (from.name !== 'defStart' || to.name !== 'instStart') {
    sessionStorage.removeItem('formImportTempRefId')
    sessionStorage.removeItem('formImportTempJson')
  }

  if (
    sessionStorage.menu_alias &&
    to.fullPath &&
    to.fullPath.split('/')[1] === 'home'
  ) {
    sessionStorage.menu_alias = ''
  }
  if (to.matched.some(record => !record.meta.anonymous)) {
    let ticket = to.query.token
    // 2.当前已经从单点页面重定向回来了，且在url地址中携带了ticket或code；
    if (window.ssoConfig.mode === 'cas') {
      ticket = to.query.ticket
    } else if (window.ssoConfig.mode === 'oauth') {
      ticket = to.query.code
    }

    store
      // 3.携带ticket做用户鉴权；
      .dispatch('login/validAndCompletedCurrent', ticket)
      .then(() => {
        store.dispatch('menu/actionFrontMenus')
        store._vm.$root.$emit('login-completed')

        if (registerRouteFresh) {
          if (sessionStorage.menu_alias) {
            let path = '/' + sessionStorage.menu_alias
            let isChildren = router.addList(path, router.options.routes) //动态新增二级路由
            //当前点击菜单的路由别名不存在 router.js 里面
            // if (!isChildren) {
            //   let alias_new = {
            //     path: path,
            //     name: 'alias_new',
            //     component: resolve =>
            //       require(['@/views/menuContent.vue'], resolve),
            //     children: []
            //   }
            //   router.options.routes.push(alias_new)
            //   router.addList(path, router.options.routes) //动态新增二级路由
            // }
            router.replace({
              path: to.path,
              query: to.query
            })
          }
          registerRouteFresh = false
        }
        next()
        // url地址带token的方式认证成功后删除url中的token
        // removeUrlParams('tokenKey')
      })
      .catch(() => {
        // 4.鉴权失败时根据当前模式重定向到对应页面。
        logoutAndCleanUp(to, from, next)
      })
  } else {
    next()
  }
})

export default router
