import Vue from 'vue'
import Router from 'vue-router'
// biz模块分文件管理
// import workOrderRouter from '@/biz/workOrderManage/router.js' // 工单管理
// import bizRouter from '@/biz/router.js'
import store from '@/store'
const HtTabsComponent = () => import('@/components/common/HtTabsComponent.vue')
const TemplateComponent = () =>
  import('@/components/common/TemplateComponent.vue')
import Statement from '@/components/bizComponents/common/Statement.vue'
Vue.use(Router)

var router = new Router({
  base: process.env.BASE_URL,
  mode: 'history',
  routes: [{
      path: '/login/:tenant',
      name: 'tenantLogin',
      props: true,
      component: () => import('@/views/Login.vue'),
      meta: {
        single: true,
        anonymous: true
      }
    },
    {
      path: '/login',
      name: 'login',
      props: true,
      component: () => import('@/views/Login.vue'),
      meta: {
        single: true,
        anonymous: true
      }
    },
    {
      path: '/resetPwdView',
      name: 'resetPwdView',
      props: true,
      component: () => import('@/views/ResetPwdView.vue'),
      meta: {
        single: true,
        anonymous: true
      }
    },

    {
      path: '/',
      redirect: {
        name: 'login'
      }
    },

    {
      path: '/sysplat',
      name: 'sysplat',
      component: () => import('@/components/layout/layout.vue'),
    //   redirect: {
    //     name: 'noPage'
    //   },
      children: [{
          path: '404',
          name: 'noPage',
          component: () => import('@/components/common/HtTabsComponent.vue'),
          meta: {
            isHome: true
          }
        },
        //地图
        {
          path: 'maptest',
          name: 'maptest',
          component: HtTabsComponent
        },
        // url菜单
        {
          path: 'href/template/:alias',
          name: 'href',
          component: () => import('@/components/common/HtTabsComponentHref.vue')
        },
        // {
        //   //系统配置-系统首页
        //   path: 'sysIndex',
        //   name: 'sysIndex',
        //   // component: HtTabsComponent,
        //   component: () => import('@/views/common/SysIndex.vue'),
        //   meta: {
        //     isHome: true
        //   }
        // },
        { // 消息中心
          path: "messageCenter",
          name: "messageCenter",
          component: HtTabsComponent,
          meta: {
            menuLabel: "消息中心"
          }
        },
        {
          path: 'form',
          name: 'form',
          component: HtTabsComponent
        },
        {
          path: 'report',
          name: 'report',
          component: HtTabsComponent
        },
        {
          path: 'meta',
          name: 'meta',
          component: HtTabsComponent
        },
        {
          path: 'i18n',
          name: 'i18n',
          component: HtTabsComponent,
          meta: {
            isReloadPage: true
          }
        },

        {
          path: 'tenantType',
          name: 'tenantType',
          component: HtTabsComponent,
          meta: {
            isReloadPage: true
          }
        },
        {
          path: 'tenantMailServer',
          name: 'tenantMailServer',
          component: HtTabsComponent,
          meta: {
            isReloadPage: true
          }
        },
        {
          path: 'tenantManager',
          name: 'tenantManager',
          component: HtTabsComponent
        },
        {
          path: 'tenantInfoManager',
          name: 'tenantInfoManager',
          component: HtTabsComponent
        },
        {
          path: 'instance',
          name: 'instance',
          component: HtTabsComponent
        },
        {
          path: 'customDialogList',
          name: 'customDialogList',
          component: HtTabsComponent
        },
        {
          path: 'customQueryList',
          name: 'customQueryList',
          component: HtTabsComponent
        },
        {
          path: 'fileList',
          name: 'fileList',
          component: HtTabsComponent
        },
        {
          path: 'flowDesign',
          name: 'flowDesign',
          component: HtTabsComponent
        },
        {
          path: 'businessObj',
          name: 'businessObj',
          component: HtTabsComponent
        },
        {
          path: 'FlowUploadProperties',
          name: 'FlowUploadProperties',
          component: HtTabsComponent
        },
        {
          path: 'customChartManager',
          name: 'customChartManager',
          component: HtTabsComponent
        },
        {
          path: 'reportManager',
          name: 'reportManager',
          component: HtTabsComponent
        },
        {
          path: 'heiOrganization',
          name: 'heiOrganization',
          component: HtTabsComponent
        },
        {
          path: 'reportManager/viewList',
          name: 'viewList',
          component: () => import('@/components/form/customView/ViewList.vue'),
          meta: {
            isHome: true
          }
        },
        {
          path: 'reportManager/flowChartEdit',
          name: 'flowChartEdit',
          component: () => import('@/components/form/chart/FlowChartEdit.vue'),
          meta: {
            isHome: true
          }
        },
        {
          path: 'agent',
          name: 'agent',
          component: HtTabsComponent
        },
        {
          path: 'demo',
          name: 'demo',
          component: HtTabsComponent,
          meta: {
            anonymous: true
          }
        },
        {
          path: 'formTemplateList',
          name: 'formTemplateList',
          component: HtTabsComponent
        },
        {
          path: 'dataTemplateList',
          name: 'dataTemplateList',
          component: HtTabsComponent
        },
        {
          path: 'executeJobList/:jobName',
          name: 'executeJobList',
          component: HtTabsComponent,
          meta: {
            keepAlive: true //页面跳转重新渲染 默认不渲染
          }
        },
        {
          path: 'schedulerTriggerList/:jobName',
          name: 'schedulerTriggerList',
          component: HtTabsComponent,
          meta: {
            keepAlive: true
          }
        },
        {
          path: 'portal',
          name: 'portal',
          component: HtTabsComponent
        },
        {
          path: 'dataSourceManager',
          name: 'dataSourceManager',
          component: HtTabsComponent
        },
        // 新闻公告
        {
          path: 'portalNewsNoticeManager',
          name: 'portalNewsNoticeManager',
          component: HtTabsComponent
        },
        {
          path: 'applicationModule',
          name: 'applicationModule',
          component: HtTabsComponent
        },
        {
          path: 'sysExternalUniteList',
          name: 'sysExternalUniteList',
          component: HtTabsComponent
        },
        {
          path: 'dataManager',
          name: 'dataManager',
          component: HtTabsComponent
        },
        {
          path: 'fileManager',
          name: 'fileManager',
          component: HtTabsComponent
        },
        {
          path: 'sysSetting',
          name: 'sysSetting',
          component: HtTabsComponent
        },
        {
          path: 'mobileUnite',
          name: 'mobileUnite',
          component: HtTabsComponent
        },
        {
          path: 'sysModuleList',
          name: 'sysModuleList',
          component: HtTabsComponent
          // component: () => import("@/views/system/generator/sysModuleList.vue")
        },

        {
          path: 'help',
          name: 'help',
          component: HtTabsComponent
        },
        {
          path: 'templateMenu/:alias',
          name: 'templateMenu',
          component: TemplateComponent,
          meta: {
            keepAlive: true //页面跳转重新渲染 默认不渲染
          }
        },

        {
          path: 'codeGenerator',
          name: 'codeGenerator',
          component: HtTabsComponent
        },
        {
          path: 'roleMatrixManager',
          name: 'roleMatrixManager',
          component: HtTabsComponent
        },
        {
          path: 'matrixManager',
          name: 'matrixManager',
          component: HtTabsComponent
        },
        {
          path: 'matrixData/:matrixId',
          name: 'matrixData',
          component: () => import('@/views/uc/MatrixData.vue')
        },
        {
          path: 'portalDataSensitiveManager',
          name: 'portalDataSensitiveManager',
          component: HtTabsComponent
        },
        {
          path: 'scheduling',
          name: 'scheduling',
          component: HtTabsComponent
        },
        {
          path: 'taskSchedule',
          name: 'taskSchedule',
          component: HtTabsComponent
        },
        /*即时通讯*/
        {
          path: 'groupMange',
          name: 'groupMange',
          component: HtTabsComponent
        },
        {
          path: 'massesGroupMange',
          name: 'massesGroupMange',
          component: HtTabsComponent
        },

        /** ------系统配置----- **/
        {
          // 系统配置-枚举字典
          path: 'sysDict',
          name: 'sysDict',
          component: HtTabsComponent
        },
        {
          //系统配置-系统信息
          path: 'sysMsg',
          name: 'sysMsg',
          component: HtTabsComponent
        },
        {
          //系统配置-菜单管理
          path: 'menuManagerRouter',
          name: 'menuManagerRouter',
          component: HtTabsComponent
        },
        {
          //系统配置-菜单管理
          path: 'enclosure',
          name: 'enclosure',
          component: HtTabsComponent
        },
        {
          //系统配置-公共树管理
          path: 'sysTypeManager',
          name: 'sysTypeManager',
          component: HtTabsComponent,
          meta: {
            isReloadPage: true
          }
        },
        {
          //系统配置-行政区划
          path: 'sysAdstration',
          name: 'sysAdstration',
          component: HtTabsComponent
        },
        {
          //系统配置-系统参数
          path: 'sysPropertiesManager',
          name: 'sysPropertiesManager',
          component: HtTabsComponent
        },
        //系统配置-分类字典
        {
          path: 'ClassificationDictionary',
          name: 'ClassificationDictionary',
          component: HtTabsComponent
        },
        {
          //系统配置-单据号规则
          path: 'DocumentNumber',
          name: 'DocumentNumber',
          component: HtTabsComponent
        },
        {
          //系统配置-附件配置
          path: 'attachmentConfig',
          name: 'attachmentConfig',
          component: HtTabsComponent
        },
        {
          //系统配置-邮件配置
          path: 'MailConfiguration',
          name: 'MailConfiguration',
          component: HtTabsComponent
        },
        {
          //系统配置-常用语管理
          path: 'CommonWords',
          name: 'CommonWords',
          component: HtTabsComponent
        },
        // 系统配置-数据备份
        {
          path: 'BackupManager',
          name: 'BackupManager',
          component: HtTabsComponent
        },
        //系统配置-系统监控
        {
          path: 'SystemMonitoring',
          name: 'SystemMonitoring',
          component: HtTabsComponent
        },
        {
          path: 'OnlineUser',
          name: 'OnlineUser',
          component: HtTabsComponent
        },


        /** --------组织权限--------- **/

        {
          //组织权限-租户管理
          path: 'tenant',
          name: 'tenant',
          component: HtTabsComponent,
          meta: {
            isReloadPage: true
          }
        },
        {
          //组织权限-组织管理
          path: 'organization',
          name: 'organization',
          component: HtTabsComponent,
          meta: {
            isReloadPage: true
          }
        },
        {
          //组织权限-职务岗位
          path: 'Position',
          name: 'Position',
          component: HtTabsComponent
        },
        {
          //组织权限-用户管理
          path: 'ucManager',
          name: 'ucManager',
          component: HtTabsComponent,
          meta: {
            isReloadPage: true
          }
        },
        {
          //组织权限-汇报线管理
          path: 'reportLine',
          name: 'reportLine',
          component: HtTabsComponent
        },
        {
          //组织权限-数据权限
          path: 'dataAuth',
          name: 'dataAuth',
          component: HtTabsComponent
        },
        {
          //组织权限-角色管理
          path: 'roleManager',
          name: 'roleManager',
          component: HtTabsComponent
        },
        {
          //组织权限-群组管理
          path: 'groupManage',
          name: 'groupManage',
          component: HtTabsComponent
        },

        /** --------日志中心---------- **/
        {
          path: 'BusinessLog',
          name: 'BusinessLog',
          component: HtTabsComponent,
        },
        {
          path: 'LoginLogList',
          name: 'LoginLogList',
          component: HtTabsComponent,
        },
        {
          path: 'systemLog',
          name: 'systemLog',
          component: HtTabsComponent,
        },
        {
          // 日志中心-日志配置
          path: 'LogConfiguration',
          name: 'LogConfiguration',
          //component: () => import('@/views/log/LogConfiguration.vue'),
          component: HtTabsComponent,
          meta: {
            keepAlive: true
          }
        },
        {
          // 日志中心-平台操作日志
          path: 'operationLog',
          name: 'operationLog',
          component: HtTabsComponent,
          meta: {
            keepAlive: true //页面跳转重新渲染 默认不渲染
          }
        },
        // 日志中心-消息日志
        {
          path: 'messageSendLog',
          name: 'messageSendLog',
          component: HtTabsComponent,
          meta: {
            keepAlive: true
          }
        },
        {
          // 日志中心-系统管理日志
          path: 'OperationLogList',
          name: 'OperationLogList',
          component: HtTabsComponent
        },
        {
          // 日志中心-业务运行日志
          path: 'BusinesWorkingLog',
          name: 'BusinesWorkingLog',
          component: HtTabsComponent
        },
        {
          // 日志中心-异常日志
          path: 'ExceptionLog',
          name: 'ExceptionLog',
          component: HtTabsComponent
        },
        // 日志中心-登录统计
        {
          path: 'LoginStatistics',
          name: 'LoginStatistics',
          // component: () => import('@/views/log/LoginStatistics.vue'),
          component: HtTabsComponent,
          meta: {
            keepAlive: true
          }
        },
        {
          // 日志中心-接口事件日志
          path: 'InterfaceEventLog',
          name: 'InterfaceEventLog',
          // component: () => import('@/views/log/InterfaceEventLog.vue'),
          component: HtTabsComponent,
          meta: {
            keepAlive: true
          }
        },
        {
          // 日志中心-登录日志
          path: 'loginLog',
          name: 'loginLog',
          component: HtTabsComponent
        },
        // 日志中心-三员日志
        {
          path: "memberLogs",
          name: "memberLogs",
          component: HtTabsComponent
        },




        /** --------安全中心---------- **/

        { // 安全中心-密码策略
          path: 'pwdStrategy',
          name: 'pwdStrategy',
          component: HtTabsComponent
        },
        { // 安全中心-账号锁定
          path: "accountLock",
          name: "accountLock",
          component: HtTabsComponent
        },
        { // 安全中心-设备管理
          path: "deviceManager",
          name: "deviceManager",
          component: HtTabsComponent
        },
        { // 安全中心-版权授权
          path: "secManage",
          name: "secManage",
          component: HtTabsComponent
        },

        //demo--地图测试
        {
          path: "mapDemo",
          name: 'mapDemo',
          component: () => import("@/views/Map/mapDemo")
        },
        {
          path: 'TableDesign',
          name: 'TableDesign',
          component: HtTabsComponent
        },

        /** --------应用中心---------- **/
        {
          // 消息配置
          path: 'messageConfig',
          name: 'messageConfig',
          component: HtTabsComponent
        },
        {
          // 消息配置
          path: 'messageManage',
          name: 'messageManage',
          component: HtTabsComponent
        },
        // 消息配置-消息分类
        {
          path: 'messageClassification',
          name: 'messageClassification',
          component: HtTabsComponent
        },

        //消息配置-消息模板
        {
          path: 'msgTemplate',
          name: 'msgTemplate',
          component: HtTabsComponent
        },
        //消息配置-消息配置
        {
          path: 'msgConfig',
          name: 'msgConfig',
          component: HtTabsComponent
        },
        //调度管理
        {
          path: 'schedulerManager',
          name: 'schedulerManager',
          component: HtTabsComponent
        },


        /**----------报表管理---------**/

        { //数据报表
          path: 'reportData',
          name: 'reportData',
          component: HtTabsComponent
        },
        { //图形报表
          path: 'reportGraphic',
          name: 'reportGraphic',
          component: HtTabsComponent
        },
        { //打印设计
          path: 'reportPrint',
          name: 'reportPrint',
          component: HtTabsComponent
        },
        { //大屏设计
          path: 'reportBigScreen',
          name: 'reportBigScreen',
          component: HtTabsComponent
        },
      ]
    },
    //新建大屏
    {
      path: '/build/:id',
      name: 'build',
      component: () => import('@/tripartite/buildBigScreen/src/page/build.vue')
    },
    //预览大屏
    {
      path: '/view/:id',
      name: 'view',
      component: () => import('@/tripartite/buildBigScreen/src/page/view.vue')
    },
    // 表单中心 表单预览渲染页面
    {
      path: '/previewForm/:formId',
      name: 'previewForm',
      component: () =>
        import('@/components/bizComponents/common/previewForm.vue'),
      props: true,
      meta: {
        single: true
      }
    },
    {
      path: '/previewForm/:formId/:single',
      name: 'previewForm-single',
      component: () =>
        import('@/components/bizComponents/common/previewForm.vue'),
      props: true,
      meta: {
        single: true
      }
    },
    {
      path: '/column/preview/:previewAlias',
      name: 'columnpreview',
      component: () => import('@/components/bizComponents/common/ColumnPreview.vue'),
      props: true,
      meta: {
        single: true
      }
    },
    { // 表单中心 数据列表渲染
      path: '/statement',
      component: Statement,
      children: [{
          path: 'querySql/queryView/:sqlAlias/:alias',
          name: 'querySqlContent',
          component: () =>
            import('@/components/bizComponents/querySql/querySqlContent.vue'),
          props: true
        },
        {
          path: 'querySql/queryView/:sqlAlias/:alias/:single',
          name: 'querySql-single',
          component: () =>
            import('@/components/bizComponents/querySql/querySqlContent.vue'),
          props: true,
          meta: {
            single: true
          }
        },
        {
          path: 'template/preview/:templateKey/:single',
          name: 'templatePreview-single',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templatePreview.vue'),
          props: true,
          meta: {
            single: true
          }
        },
        {
          path: 'template/preview/:templateKey',
          name: 'templatePreview',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templatePreview.vue'),
          props: true
        },
        {
          path: 'template/preview/:templateKey/:single/:parameterqQuerys',
          name: 'templatePreview-singleQuerys',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templatePreview.vue'),
          props: true,
          meta: {
            single: true
          }
        },
        {
          path: 'template/preview/:templateKey/:taskType/:defKey/:isJoinFlow',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templatePreview.vue'),
          props: true,
          meta: {
            single: true
          }
        },
        {
          path: '/',
          name: 'template-default',
          redirect: '/statement/draftList'
        },
        {
          path: 'draftList/:tempAlias/:dataViewFlag',
          name: 'templateDraftList',
          component: () =>
            import('@/components/bizComponents/dataTemplate/TemplateDraft.vue'),
          props: true,
          meta: {
            single: true
          }
        },
        {
          path: '/href/template/:alias',
          name: 'templateHref',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templateHref.vue'),
          props: true
        },
  
        {
          path: 'template/form/:templateKey/:action',
          name: 'templateForm',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templateForm.vue'),
          props: true
        },
        {
          path: 'template/form/:templateKey/:action/:single',
          name: 'templateFormSingle',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templateForm.vue'),
          props: true,
          meta: {
            single: true
          }
        },
        {
          path: 'template/form/:templateKey/:action/:single/:openType',
          name: 'templateFormSingleOpenType',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templateForm.vue'),
          props: true,
          meta: {
            single: true
          }
        },
        {
          path: 'template/form/:templateKey/:action/:single/:isShare',
          name: 'templateShare',
          component: () =>
            import('@/components/bizComponents/dataTemplate/templateForm.vue'),
          props: true,
          meta: {
            single: true
          }
        }
      ]
    },
    // ...bizRouter,
  ]
})

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}`
  }
}

// 移除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])
    }
  }
  setTimeout(() => {
    window.history.replaceState(
      null,
      null,
      `${window.location.pathname}${newVars.length > 0 ? '?' : ''
      }${newVars.join('&')}`
    )
  }, 100)
}

router.beforeEach((to, from, next) => {
  // 1.当前为单点登录模式，且要路由到login页面，则做单点登录重定向；s
  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 (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/actionMenus').then(() => {})
        store.dispatch('menu/actionFrontMenus').then(() => {})
        if (ticket) {
          store._vm.$root.$emit('getAuth');
        }
        next()
        removeUrlParams("token")
      })
      .catch(() => {
        // 4.鉴权失败时根据当前模式重定向到对应页面。
        store.dispatch('login/logoutAndCleanUp').then(() => {
          if (
            window.ssoConfig.mode &&
            window.ssoConfig.mode != 'jwt' &&
            !ticket
          ) {
            ssoRedirect()
          } else if (!window.ssoConfig.mode || window.ssoConfig.mode == 'jwt') {
            let account = ''
            if (store.state.login.currentUser) {
              account = store.state.login.currentUser.account
            }
            next({
              path: localStorage.getItem(account + 'loginRoutePath') || '/login',
              query: {
                redirect: to.fullPath
              }
            })
          } else {
            throw '登录失败'
          }
        })
      })
  } else {
    next()
  }
  // 404页面跳转
  if (to.name !== 'login' && to.matched.length === 0) {
    if (to.path.indexOf('sysplat') !== -1 || from.path.indexOf('sysplat') !== -1) {
      next({
        name: 'noPage'
      })
    } else {
      next({
        name: 'frontNoPage'
      })
    }
  } else {
    next();
  }
})

export default router