import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import NotFound from '@/views/NotFound.vue'
import Login from '@/views/Login.vue'
import NoAuth from '@/views/NoAuth.vue'
import req from '@/request.js'
import qs from 'qs'
import portal from '@/api/portal.js'
import utilMd5 from './md5'
import uc from '@/api/uc.js'
import { Message } from 'element-ui'
import { Loading } from 'element-ui'
import flowformRouter from '@/components/flowURLForm/formRouter.js' // URL表单路由
//路由
import mainRouter from '@/module_router.js'
import Layout from '@/components/layout/Layout.vue'
// import { component } from 'vue/types/umd'

Vue.use(Router)

var router = new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/',
            redirect: {
                name: 'login'
            }
        },
        {
            path: '/login',
            name: 'login',
            component: Login,
            meta: {
                single: true,
                anonymous: true
            }
        },
        {
            path: '/auth',
            name: 'auth',
            component: () => import('@/views/Auth.vue'),
            meta: {
                single: true,
                anonymous: true
            }
        },
        {
            path: '/NoticeDetils',
            name: 'NoticeDetils',
            component: () => import('@/views/NoticeDetils.vue'),
            meta: {
                single: true,
                anonymous: true
            }
        },
        {
            path: '/NoAuth',
            name: 'NoAuth',
            component: NoAuth,
            meta: {
                single: true,
                anonymous: true
            }
        },
        {
            path: '/resetPwdView',
            name: 'resetPwdView',
            props: true,
            component: () => import('@/views/ResetPwdView.vue'),
            meta: {
                single: true,
                anonymous: true
            }
        },
        {
            path: '*',
            component: NotFound,
            meta: {
                single: true
            }
        },
        {
            path: '/platLayout',
            name: 'platLayout',
            component: Layout,
            meta: {
                single: true,
                anonymous: true
            },
            children: [
                {
                    path: 'PersonalInfo',
                    name: 'PersonalInfoInner',
                    props: true,
                    component: () => import('@/views/PersonalInfo.vue')
                },
                {
                    path: 'resetPwdView',
                    name: 'resetPwdViewInner',
                    props: true,
                    component: () => import('@/views/ResetPwdView.vue')
                },
                ...mainRouter
            ]
        },
        {
            path: '/balanceOverview',
            name: 'balanceOverview',
            component: () => import('@/views/BigScreen/balanceOverview.vue'),
        },
        {
            path: '/operationFees',
            name: 'operationFees',
            component: () => import('@/views/BigScreen/operationFees.vue'),
        },
        {
            path: '/videoMonitoring',
            name: 'videoMonitoring',
            component: () => import('@/views/BigScreen/videoMonitoring.vue'),
        },
        {
            path: '/itResources',
            name: 'itResources',
            component: () => import('@/views/BigScreen/itResources.vue'),
        },
        {
            path: '/homePage',
            name: 'homePage',
            component: () => import('@/views/BigScreen/homePage.vue'),
        },
        {
            path: '/normal',
            name: 'normal',
            component: () => import('@/views/Normal/normal.vue')
        }, 
        // 待办任务
    {
        path: '/task/:taskId/:leaderId',
        name: 'task',
        component: () =>
          import('@/components/flow/taskFlowComponents/flowTask.vue'),
        props: true
      },
      /* 跳转任务详情 */
      {
        path: '/inst/:instId/:type',
        name: 'inst',
        component: () => import('@/components/flow/task.vue'),
        props: true
      },
      /* 待阅列表跳转 */
      {
        path: '/inst/:instId/:type/:readId',
        name: 'instRead-read',
        component: () => import('@/components/flow/task.vue'),
        props: true
      },
      {
        path: '/start/:defId/:instId',
        name: 'instStart',
        component: () => import('@/components/flow/start.vue'),
        props: true
      },
      {
        path: 'v-done',
        name: 'done',
        component: () => import('@/components/flow/done.vue')
      },
      {
        path: 'v-done/:defKey',
        name: 'done-defKey',
        component: () => import('@/components/flow/done.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      {
        path: 'v-request',
        name: 'request',
        component: () => import('@/components/flow/myRequest.vue')
      },
      {
        path: 'v-request/:defKey',
        name: 'request-defKey',
        component: () => import('@/components/flow/myRequest.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      {
        path: 'v-flowList',
        name: 'flowList',
        component: () => import('@/components/flow/flowList.vue')
      },
      {
        path: 'v-todoRead',
        name: 'todoRead',
        component: () => import('@/components/flow/todoRead.vue')
      },
      {
        path: 'v-todoRead/:defKey',
        name: 'todoRead-defKey',
        component: () => import('@/components/flow/todoRead.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      {
        path: 'v-doneRead',
        name: 'doneRead',
        component: () => import('@/components/flow/doneRead.vue')
      },
      {
        path: 'v-doneRead/:defKey',
        name: 'doneRead-defKey',
        component: () => import('@/components/flow/doneRead.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      {
        path: 'v-myRead',
        name: 'myRead',
        component: () => import('@/components/flow/myRead.vue')
      },
      {
        path: 'v-myRead/:defKey',
        name: 'myRead-defKey',
        component: () => import('@/components/flow/myRead.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      {
        path: 'v-myDelegate',
        name: 'myDelegate',
        component: () => import('@/components/flow/myDelegate.vue')
      },
      {
        path: 'v-myDelegate/:defKey',
        name: 'myDelegate-defKey',
        component: () => import('@/components/flow/myDelegate.vue'),
        props: true,
        meta: {
          single: true
        }
      },
  
      {
        path: '/formManage/:instId/:type',
        name: 'formManage',
        component: () => import('@/components/flow/formManage.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      /* 跳转启动流程 */
      {
        path: '/agentStart/:defId/:leaderId',
        name: 'defStart',
        component: () => import('@/components/flow/start.vue'),
        props: true
      },
      /*复制流程启动 */
      {
        path: '/agentStart/:defId/:leaderId/:copyInstId',
        name: 'defCopyStart',
        component: () => import('@/components/flow/start.vue'),
        props: true
      },
      //根据流程定义key启动流程
      {
        path: '/agentStartByKey/:defKey',
        name: 'defKeyStart',
        component: () => import('@/components/flow/startByKey.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      {
        path: '/sysModulePreview/:id/:appName',
        name: 'sysModulePreview',
        component: () => import('@/components/generator/sysModulePreview.vue'),
        props: true,
        meta: {
          single: true
        }
      },
      {
        path: '/start/:defId/:instId',
        name: 'instStart',
        component: () => import('@/components/flow/start.vue'),
        props: true
      },
      /* 跳转任务详情 */
      {
        path: '/inst/:instId/:type',
        name: 'inst',
        component: () => import('@/components/flow/task.vue'),
        props: true
      },
  
      /* 待阅列表跳转 */
      {
        path: '/inst/:instId/:type/:readId',
        name: 'instRead-read',
        component: () => import('@/components/flow/task.vue'),
        props: true
      },
      /* 模块开发代办跳转 */
      {
        path: '/sysModuleInst/:taskId/:leaderId/:defKey/:noSingle',
        name: 'sysModuleInst',
        component: () => import('@/components/flow/task.vue'),
        props: true,
        meta: {
          single: true
        }
      },
        ...flowformRouter
    ]
})

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

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

//动态新增二级路由
router.addList = (path, list) => {
    let isAddPath = false
    let isChildren = false

    return isChildren
}

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 logoutAndCleanUp = (to, from, next) => {
    store.dispatch('login/logoutAndCleanUp').then(() => {
        if (window.ssoConfig.mode && window.ssoConfig.mode != 'jwt' && !ticket) {
            ssoRedirect()
        } else if (!window.ssoConfig.mode || window.ssoConfig.mode == 'jwt') {
            next({
                path: '/login'
                // query: {
                //     redirect: to.fullPath
                // }
            })
        } else {
            throw '登录失败'
        }
    })
}

// 移除url后面的指定参数
const removeUrlParams = param => {
    const query = window.location.search.substring(1)
    if (!query) {
        return
    }
    const vars = query.split('&')
    const newVars = []
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=')
        if (pair[0] != param) {
            newVars.push(vars[i])
        }
    }
    console.log(newVars)
    setTimeout(() => {
        const path = `${window.location.pathname}${newVars.length > 0 ? '?' : ''
            }${newVars.join('&')}`
        window.history.replaceState(null, null, path)
    }, 1000)
}

const tokenLogin = (userInfo, next, routerName, pathInfo) => {
    store.dispatch('login/loginAuthNoPassword', userInfo).then(loginStatus => {
      if (loginStatus && loginStatus == true) {
        store.dispatch('menu/actionFrontMenus').then(res => {
          if (routerName&&routerName!='task') {
            console.log(routerName, 'routerName')
            // delete pathInfo.query.routerName
            // delete pathInfo.query.tokenKey
            // let url = ''
            // for (let i in pathInfo.query) {
            //   url += i + '=' + pathInfo.query[i] + '&'
            // }
            // let path_ =
            //         pathInfo.fullPath.split('?')[0] +
            //         '?' +
            //  url.slice(0, url.length - 1)
            // let arr = path_.split(pathInfo.name)
            // console.log(arr,'arr');
            // let path = arr[0] + routerName + arr[1]
            // window.location.href = '/fvue'+path;
          } else {
            if(pathInfo.path =='/login'&&pathInfo.query.redirect == undefined){
              next({
                path: `/platLayout/${res[0].children[0].children[0].alias}`
              })
            }else if(pathInfo.name =='task'){
              next({
                path: pathInfo.path+'?close=0'
              })
            }else if(pathInfo.query.routerName =='task'){
              // next({
              //   path: pathInfo.query.redirect
              // })
              window.location.href = pathInfo.query.redirect+'?close=0'
            } else{
              next({
                path: `/platLayout/${res[0].children[0].children[0].alias}`
              })
            }
            removeUrlParams('tokenKey')
            // 获取字典
            portal.getSysDict().then(data => {
              if (data) {
                sessionStorage.setItem('dict_data', JSON.stringify(data))
              }
            })
            store.dispatch('menu/getCurrentUserMethodAuth')
          }
        })
      }
    })
  }

router.beforeEach(async (to, from, next) => {
    console.log(to, 'to,from')
    // if (to.query.routerName&&to.query.routerName!='task') {
    //     const account = to.query.acconut
    //     tokenLogin(
    //       {
    //         username: account,
    //         password: '',
    //         token: utilMd5.hexMD5(account + 'JDXT')
    //       },
    //       next,
    //       to.query.routerName,
    //       to
    //     )
    //   } 
    //   else
      if (to.query.tokenKey) {
        req.post('${portal}/api/valid/' + to.query.tokenKey).then(res => {
          console.log(res,';resss');
          if (res.data.state) {
            let value = res.data.value
            tokenLogin(
              {
                username: value.account,
                password: '',
                token: utilMd5.hexMD5(value.account + 'JDXT')
              },
              next,
              to.query.routerName,
              to
            )
            removeUrlParams('tokenKey')
          } 
        })
      }
    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._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
