import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import api from '@/utils/api'

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/mainpage',
    meta: {
      title: '首页'
    }
  },
  {
    path: '/mylogin',
    name: 'MyLogin',
    component: () => import('@/views/MyLogin.vue'),
    meta: {
      title: '登录',
      hideForAuth: true
    }
  },
  {
    path: '/mainpage',
    name: 'MainPage',
    component: () => import('@/views/MainPage.vue'),
    meta: {
      title: '主页'
    }
  },
  {
    path: '/myshop',
    name: 'MyShop',
    component: () => import('@/views/MyShop.vue'),
    meta: {
      title: '积分商城'
    }
  },
  {
    path: '/myprofile',
    name: 'MyProfile',
    component: () => import('@/views/MyProfile.vue'),
    meta: {
      title: '个人中心'
    }
  },
  {
    path: '/distribution',
    name: 'Distribution',
    component: () => import('@/views/Distribution.vue'),
    meta: {
      title: '分销'
    }
  },
  {
    path: '/loading',
    name: 'Loading',
    component: () => import('@/views/Loading.vue'),
    meta: {
      title: '维护中'
    }
  },
  {
    path: '/mypoints-history',
    name: 'MyPointsHistory',
    component: () => import('@/views/MyPointsHistory.vue'),
    meta: {
      title: '积分记录',
      requiresAuth: true
    }
  },
  {
    path: '/editdetailspage',
    name: 'EditDetailsPage',
    component: () => import('@/views/EditDetailsPage.vue'),
    meta: {
      title: '编辑信息',
      requiresAuth: true
    }
  },
  {
    path: '/editpasswordpage',
    name: 'EditPasswordPage',
    component: () => import('@/views/EditPasswordPage.vue'),
    meta: {
      title: '编辑密码',
      requiresAuth: true
    }
  },
  {
    path: '/shop',
    name: 'Shop',
    component: () => import('@/views/Shop.vue'),
    meta: {
      title: '积分商城'
    }
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('@/views/ProductDetail.vue'),
    meta: {
      title: '商品详情'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: {
      title: '注册',
      hideForAuth: true
    }
  },
  {
    path: '/payment',
    name: 'Payment',
    component: () => import('@/views/Payment.vue'),
    meta: {
      title: '支付激活',
       requiresAuth: true
    }
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('@/views/Orders.vue'),
    meta: {
      title: '我的订单',
      requiresAuth: true
    }
  },
  {
    path: '/transfers',
    name: 'Transfers',
    component: () => import('@/views/Transfers.vue'),
    meta: {
      title: '转账',
      requiresAuth: true
    }
  },
  {
    path: '/matching',
    name: 'Matching',
    component: () => import('@/views/Matching.vue'),
    meta: {
      title: '货款匹配',
      requiresAuth: true
    }
  },
  {
    path: '/agent/login',
    name: 'AgentLogin',
    component: () => import('@/views/AgentLogin.vue'),
    meta: {
      title: '代理登录'
    }
  },
  {
    path: '/agent/dashboard',
    name: 'AgentDashboard',
    component: () => import('@/views/AgentDashboard.vue'),
    meta: {
      title: '代理后台',
      requiresAuth: true,
      isAgent: true
    }
  },
  {
    path: '/agent/withdrawals',
    name: 'AgentWithdrawals',
    component: () => import('@/views/AgentWithdrawals.vue'),
    meta: {
      title: '佣金提现',
      requiresAuth: true,
      isAgent: true
    }
  },
  {
    path: '/customerservice',
    name: 'CustomerService',
    component: () => import('@/views/CustomerService.vue'),
    meta: {
      title: '客服中心'
    }
  },
  {
    path: '/productsummary/:id',
    name: 'productSummary',
    component: () => import('@/views/ProductSummary.vue'),
    meta: {
      title: '商品汇总'
    }
  },
  {
    path: '/buydetail',
    name: 'BuyDetail',
    component: () => import('../views/BuyDetails.vue'),
    meta: { title: '确认订单' }
  },
  {
    path: '/pay/:orderId',
    name: 'Pay',
    component: () => import('@/views/Pay.vue'),
    meta: { title: '确认支付' },
    props: route => ({ orderId: route.query.orderId })
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('@/views/Cart.vue'),
    meta: { title: '购物车' }
  },
  {
    path: '/address',
    name: 'Address',
    component: () => import('@/views/Address.vue'),
    meta: { title: '地址管理', requiresAuth: true }
  },
  {
    path: '/payloading',
    name: 'PayLoading',
    component: () => import('@/views/PayLoading.vue'),
    meta: { title: '支付确认' },
    props: route => ({ orderId: route.query.orderId })
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: {
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory('/frontend/'),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  const userStore = useUserStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 炬融圈`
  }

  // 检查维护模式
  try {
    const { data } = await api.get('/system/maintenance-status', { showLoading: false })
    console.log(data, 'data');

    if (data.success) {
      if (data.data.maintenance_mode) {
        // 维护模式开启，且不在维护页面，跳转到维护页面
        if (to.name !== 'Loading') {
          next({ name: 'Loading' })
          return
        }
      } else {
        // 维护模式关闭，且在维护页面，跳转到首页
        if (to.name === 'Loading') {
          next({ name: 'MainPage' })
          return
        }
      }
    }
  } catch (error) {
    // 如果检查维护状态失败，继续正常流程
    console.warn('检查维护状态失败:', error)
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 检查是否是代理页面
    if (to.meta.isAgent) {
      // 代理页面认证逻辑
      const agentInfo = localStorage.getItem('agentInfo')
      const agentToken = localStorage.getItem('token')

      if (!agentInfo || !agentToken) {
        next({
          path: '/mylogin',
          query: { redirect: to.fullPath }
        })
        return
      }
    } else {
      // 普通用户页面认证逻辑
      console.log(userStore.isAuthenticated,'isAuthenticated');

      if (!userStore.isAuthenticated) {
        // 尝试从本地存储恢复登录状态
        await userStore.checkAuth()

        if (!userStore.isAuthenticated) {
          next({
            name: 'MyLogin',
            query: { redirect: to.fullPath }
          })
          return
        }
      }

      // 检查支付状态（管理员除外）
      console.log(userStore.user);

      if (userStore.user && userStore.user.role !== 'admin' && userStore.user.payment_status === 'unpaid') {
        console.log('进来了');

        // 如果当前不在支付页面，静默重定向到支付页面（不显示额外通知）
        if (to.name !== 'Payment') {
          next({
            name: 'Payment',
            query: { redirect: to.fullPath }
          })
          return
        } else {
          next()
        }
      }
    }
  }

  // 如果已登录用户访问登录/注册页面，重定向到转账管理（改成了主页）
  if (to.meta.hideForAuth && userStore.isAuthenticated) {
    next({ name: 'MainPage' })
    return
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router