import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'
import { useUserStore } from '@/stores/user'

const routes: Array<RouteRecordRaw> = [
    // 1. 登录页
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/index.vue'),
        meta: { hidden: true }
    },

    // 2. 首页 Dashboard
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: () => import('@/views/dashboard/index.vue'),
                meta: { title: '首页', icon: 'HomeFilled' }
            }
        ]
    },

    // 3. 基础信息
    {
        path: '/material',
        component: Layout,
        redirect: '/material/index',
        children: [
            {
                path: 'index',
                name: 'MaterialBase',
                component: () => import('@/views/material/list.vue'),
                meta: { title: '基础信息', icon: 'Box' }
            }
        ]
    },

    // 4. 库存管理 (入库)
    {
        path: '/inventory',
        component: Layout,
        meta: { title: '入库管理', icon: 'Shop' },
        redirect: '/inventory/buy',
        children: [
            {
                path: 'buy',
                name: 'InventoryBuy',
                component: () => import('@/views/stock/inbound/buy.vue'),
                meta: { title: '采购件' }
            },
            {
                path: 'semi',
                name: 'InventorySemi',
                component: () => import('@/views/stock/inbound/semi.vue'),
                meta: { title: '半成品' }
            },
            {
                path: 'product',
                name: 'InventoryProduct',
                component: () => import('@/views/stock/inbound/product.vue'),
                meta: { title: '成品' }
            },
            // [原有] 入库记录整合
            {
                path: 'summary',
                name: 'InventorySummary',
                component: () => import('@/views/stock/inbound/inbound_summary.vue'),
                meta: { title: '入库记录' }
            },
            {
                path: 'service',
                name: 'InventoryService',
                component: () => import('@/views/stock/inbound/service.vue'),
                meta: { title: '服务权益' }
            },
            // ★ [新增] 库存盘点页面 (查库/消除)
            {
                path: 'stocktake',
                name: 'InventoryStocktake',
                component: () => import('@/views/stock/stocktake/index.vue'),
                meta: { title: '库存盘点' }
            }
        ]
    },

    // 5. 出库管理
    {
        path: '/outbound',
        component: Layout,
        meta: { title: '出库管理', icon: 'Van' },
        redirect: '/outbound/index',
        children: [
            // ★ [新增] 出库选单打印页面
            {
                path: 'selection',
                name: 'OutboundSelection',
                component: () => import('@/views/outbound/Selection.vue'),
                meta: { title: '出库选单' }
            },
            {
                path: 'create',
                name: 'OutboundCreate',
                component: () => import('@/views/outbound/create.vue'),
                meta: { title: '扫码出库' }
            },
            {
                path: 'index',
                name: 'OutboundList',
                component: () => import('@/views/outbound/index.vue'),
                meta: { title: '出库记录' }
            }
        ]
    },

    // 6. 业务操作
    {
        path: '/operation',
        component: Layout,
        meta: { title: '借库管理', icon: 'Operation' },
        redirect: '/operation/borrow',
        children: [
            {
                path: 'borrow',
                name: 'OpBorrow',
                component: () => import('@/views/transaction/borrow.vue'),
                meta: { title: '借库' }
            },
            {
                path: 'repair',
                name: 'OpRepair',
                component: () => import('@/views/transaction/return.vue'),
                meta: { title: '返还' }
            },
            {
                path: 'records',
                name: 'OpRecords',
                component: () => import('@/views/transaction/records.vue'),
                meta: { title: '借还记录' }
            }
        ]
    },

    // 7. 系统管理
    {
        path: '/system',
        component: Layout,
        meta: {
            title: '系统管理',
            icon: 'Setting',
            roles: ['super_admin', 'supervisor']
        },
        children: [
            {
                path: 'user-create',
                name: 'UserCreate',
                component: () => import('@/views/system/UserCreate.vue'),
                meta: { title: '账号开通', icon: 'User' }
            }
        ]
    },

    // 404 路由
    {
        path: '/:pathMatch(.*)*',
        redirect: '/dashboard',
        meta: { hidden: true }
    }
]

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

// ==========================================
// 全局路由守卫
// ==========================================
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()

    const token = userStore.token || localStorage.getItem('token')
    const userRole = userStore.role || localStorage.getItem('role') || 'user'

    if (to.path === '/login') {
        if (token) {
            next('/')
        } else {
            next()
        }
        return
    }

    if (!token) {
        next({ path: '/login', replace: true })
        return
    }

    if (to.meta.roles && Array.isArray(to.meta.roles)) {
        if (to.meta.roles.includes(userRole)) {
            next()
        } else {
            next('/dashboard')
        }
    } else {
        next()
    }
})

export default router