import { createRouter, createWebHistory } from 'vue-router';
import { useAuth } from '../stores/useAuth';
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const Home = () => import('@/views/Home.vue');
const About = () => import('@/views/About.vue');
const Login = () => import('@/views/Login.vue');
const NotFound = () => import('@/views/NotFound.vue');
const Projectlist = () => import('@/views/project/projectlist.vue');
const Asset = () => import('@/views/project/asset.vue');
const EnterpriseProject = () => import('@/views/enterprise/project.vue');
const EnterpriseUsage = () => import('@/views/enterprise/usage.vue');
const EnterpriseWatermark = () => import('@/views/enterprise/watermark.vue');
const Drama = () => import('@/views/project/drama.vue');

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/projectlist',
    name: 'Projectlist',
    component: Projectlist,
    meta: { authRequired: true }
  },
  {
    path: '/drama',
    name: 'Drama',
    component: Drama,
    meta: { authRequired: true }
  },
  {
    path: '/asset',
    name: 'Asset',
    component: Asset,
    meta: { authRequired: true }
  },
  {
    path: '/enterprise/project',
    name: 'EnterpriseProject',
    component: EnterpriseProject,
    meta: { authRequired: true }
  },
  {
    path: '/enterprise/usage',
    name: 'EnterpriseUsage',
    component: EnterpriseUsage,
    meta: { authRequired: true }
  },
  {
    path: '/enterprise/watermark',
    name: 'EnterpriseWatermark',
    component: EnterpriseWatermark,
    meta: { authRequired: true }
  },
  {
    path: '/about',
    name: 'About',
    component: About,
    meta: { authRequired: true }
  },

  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach(async (to) => {
  const auth = useAuth();
  const hasToken = auth.isLoggedIn.value;
  if (hasToken) {
    if (to.path === "/login") {
      // 如果已登录，则重定向到首页
      NProgress.done();
      return { path: '/' };
    }
  } else if (to.path !== '/login') {
    return { path: '/login' };
  }
});
router.afterEach(() => {
  NProgress.done();
});

export default router;
