import Vue from 'vue'
import VueRouter from 'vue-router'
import { store } from '@/components/vuex/store'
const Home = () => import('@/components/Home')
const ViewTask = () => import('@/components/Supervision/ViewTask')
const statPage = () => import('@/components/Statistic/statPage')
const Analysis = () => import('@/components/Analysis/analysisPage')
const DataManagement = () => import('@/components/DataManagement/DataManagement')
const xmlHome = () => import('@/components/TaskManagement/xml/home.vue')
const drawtool = () => import('@/components/TaskManagement/xml/drawtool.vue')
const position = () => import('@/components/TaskManagement/xml/position.vue')
const basemap = () => import('@/components/TaskManagement/xml/basemap.vue')
const creatTable = () => import('@/components/TaskManagement/xml/creatTable.vue')
const Login = () => import('@/components/login/login.vue')
const Register = () => import('@/components/login/register.vue')
const tableCon = () => import('@/components/TaskManagement/xml/tableCon.vue')
const main = () => import('@/components/TaskManagement/xml/main.vue')
const NotFound = () => import('@/components/404.vue')
const Manage = () => import('@/components/TaskManagement/manage/TPManage.vue')
const TaskManage = () => import('@/components/TaskManagement/manage/TaskManage.vue')
const DataManage = () => import('@/components/TaskManagement/manage/DataManage.vue')
const UserManage = () => import('@/components/TaskManagement/manage/UserManage.vue')
const ModifyPassword = () => import('@/components/login/ModifyPassword.vue')
const ForgetPassword = () => import('@/components/login/ForgetPassword.vue')
const Addinfo = () => import('@/components/login/Addinfo.vue')
const ManualAllocate = () => import('@/components/TaskManagement/manage/ManualAllocate.vue')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/view'
  },
  {
    path: '/view',
    rediret: '/view',
    type: 'view',
    name: '工作监管',
    component: Home,
    children: [
      {
        path: '/view',
        name: '轨迹查看',
        component: ViewTask
      }]
  }, {
    path: '/statistic',
    type: 'statistic',
    name: '汇总统计',
    component: Home,
    children: [{
      path: '/statistic',
      name: '统计',
      component: statPage
    }]
  },
  {
    path: '/analysis',
    type: 'analysis',
    name: '分析决策',
    component: Home,
    children: [{
      path: '/analysis',
      name: '分析',
      component: Analysis
    }]
  },
  {
    path: '/manage',
    type: 'Manage',
    name: '任务管理',
    component: Home,
    children: [{
      path: '/manage',
      component: Manage,
      children: [
        { path: '/taskmanage', component: TaskManage },
        { path: '/usermanage', component: UserManage },
        { path: '/datamanage', component: DataManage },
        { path: '/main', component: main },
        { path: '/manualallocate/:id/:name', component: ManualAllocate }
      ]
    },
    {
      path: '/home/:name/:key/:id',
      component: xmlHome,
      name: 'Meta',
      iconCls: 'el-icon-menu', // 图标样式class
      children: [
        { path: '/home/:name/:key/:id/drawtool', component: drawtool, name: 'Drawtool' },
        { path: '/home/:name/:key/:id/position', component: position, name: 'Position' },
        { path: '/home/:name/:key/:id/basemap', component: basemap, name: 'Basemap' },
        { path: '/home/:name/:key/:id/creattable', component: creatTable, name: 'creatTable' },
        { path: '/home/:name/:key/:id/:index/tablecon', component: tableCon }
      ]
    },
    {
      path: '/home/:name/:id',
      component: xmlHome
    }]
  },
  {
    path: '/data',
    type: 'data',
    name: '数据管理',
    component: Home,
    children: [{
      path: '/data',
      name: '数据',
      component: DataManagement
    }]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/addinfo',
    component: Addinfo
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/modifypassword',
    component: ModifyPassword
  },
  {
    path: '/forgetpassword',
    component: ForgetPassword
  },
  {
    path: '*',
    component: NotFound
  },
  {
    path: '/manage',
    component: Manage,
    children: [
      { path: '/taskmanage', component: TaskManage },
      { path: '/usermanage', component: UserManage },
      { path: '/manualallocate/:id/:name', component: ManualAllocate },
      { path: '/main', component: main }

    ]
  }
]
const router = new VueRouter({
  routes
})
router.beforeEach(async (to, from, next) => {
  // 如果目标路径与当前路径相同，直接放行，避免 NavigationDuplicated 错误
  if (to.path === from.path) {
    next()
    return
  }
  
  if (to.path.startsWith('/login')) {
    window.sessionStorage.removeItem('access-user')
    window.sessionStorage.removeItem('access-id')
    // 清除初始化状态
    store.commit('setTaskDataInitialized', false)
    store.commit('clearInitError')
    next()
  } else if (to.path.startsWith('/register') || to.path.startsWith('/modifypassword') || to.path.startsWith('/forgetpassword') || to.path.startsWith('/addinfo')) {
    window.sessionStorage.removeItem('access-user')
    window.sessionStorage.removeItem('access-id')
    // 清除初始化状态
    store.commit('setTaskDataInitialized', false)
    store.commit('clearInitError')
    next()
  } else {
    let user = window.sessionStorage.getItem('access-user') === '' ? false : window.sessionStorage.getItem('access-user')
    if (!user) {
      next({ path: '/login' })
    } else {
      // 检查数据是否已初始化
      const isInitialized = store.state.taskDataInitialized
      const isInitializing = store.state.taskDataInitializing
      
      // 如果数据未初始化且不在初始化中，则进行初始化
      if (!isInitialized && !isInitializing) {
        try {
          const result = await store.dispatch('initTaskData')
          if (result.success) {
            // 初始化成功，继续路由
            next()
          } else {
            // 初始化失败，显示错误提示并阻止路由
            store.commit('setInitError', result.error)
            // 阻止路由跳转，显示错误对话框
            next(false)
          }
        } catch (error) {
          // 初始化异常
          store.commit('setInitError', error.message || '初始化失败，请重试')
          next(false)
        }
      } else if (isInitializing) {
        // 正在初始化中，等待完成（最多等待5秒）
        let waited = 0
        const maxWait = 5000
        const checkInterval = setInterval(() => {
          waited += 100
          if (!store.state.taskDataInitializing || waited >= maxWait) {
            clearInterval(checkInterval)
            if (store.state.taskDataInitialized) {
              next()
            } else {
              if (waited >= maxWait) {
                store.commit('setTaskDataInitializing', false)
                store.commit('setInitError', '初始化超时，请重试')
              } else {
                store.commit('setInitError', '初始化失败，请重试')
              }
              next(false)
            }
          }
        }, 100)
      } else {
        // 已初始化，继续路由
        next()
      }
    }
  }
})
export default router
