import { createRouter, createWebHistory } from "vue-router";

import DashboardView from "../views/DashboardView.vue";
import SalesPlanningView from "../views/SalesPlanningView.vue";
import EmployeeManagementView from "../views/EmployeeManagementView.vue";
import ProductManagementView from "../views/ProductManagementView.vue";
import BomManagementView from "../views/BomManagementView.vue";
import ProcessRouteManagementView from "../views/ProcessRouteManagementView.vue";
import LoginView from "../views/LoginView.vue";
import SupplierManagementView from "../views/SupplierManagementView.vue";
import PurchaseOrderView from "../views/PurchaseOrderView.vue";
import PurchaseReceiptView from "../views/PurchaseReceiptView.vue";
import InventoryLedgerView from "../views/InventoryLedgerView.vue";
import ProductionLedgerView from "../views/ProductionLedgerView.vue";
import OperationReportView from "../views/OperationReportView.vue";
import DeliveryManagementView from "../views/DeliveryManagementView.vue";
import EquipmentManagementView from "../views/EquipmentManagementView.vue";
import QualityInspectionView from "../views/QualityInspectionView.vue";
import FinanceReportView from "../views/FinanceReportView.vue";
import ProductSpecLiteView from "../views/ProductSpecLiteView.vue";
import SupplierMaterialLiteView from "../views/SupplierMaterialLiteView.vue";
import SystemPermissionView from "../views/SystemPermissionView.vue";
import SystemExtensionView from "../views/SystemExtensionView.vue";
import MasterDataImportView from "../views/MasterDataImportView.vue";
import { isAuthenticated, readSession } from "../services/api";
import { loadSmartOperationReportConfig } from "../services/systemFeatures";

const masterDataPermissionOrder = [
  {
    routeName: "supplier-management",
    permission: "MENU_SUPPLIER_MANAGEMENT"
  },
  {
    routeName: "supplier-material-lite",
    permissionsAny: ["MENU_SUPPLIER_MANAGEMENT", "MENU_MATERIAL_MANAGEMENT"]
  },
  {
    routeName: "customer-management",
    permission: "MENU_SALES_PLANNING"
  },
  {
    routeName: "product-spec-lite",
    permissionsAny: ["MENU_PRODUCT_MANAGEMENT", "MENU_BOM_MANAGEMENT", "MENU_ROUTE_MANAGEMENT"]
  },
  {
    routeName: "employee-management",
    permission: "MENU_EMPLOYEE_MANAGEMENT"
  }
];

const procurementPermissionOrder = [
  {
    routeName: "purchase-orders",
    permission: "MENU_PURCHASE_ORDER"
  },
  {
    routeName: "purchase-receipts",
    permission: "MENU_PURCHASE_RECEIPT"
  },
  {
    routeName: "quality-inspection",
    permission: "MENU_QUALITY_INSPECTION"
  },
  {
    routeName: "inventory-ledger",
    permission: "MENU_INVENTORY_LEDGER"
  }
];

const productionPermissionOrder = [
  {
    routeName: "production-ledger",
    permission: "MENU_WORK_ORDER"
  },
  {
    routeName: "operation-reports",
    permission: "MENU_OPERATION_REPORT"
  }
];

const deliveryPermissionOrder = [
  {
    routeName: "delivery-management",
    permission: "MENU_DELIVERY_MANAGEMENT"
  }
];

const systemPermissionOrder = [
  {
    routeName: "system-permissions",
    permission: "MENU_SYSTEM_PERMISSION"
  },
  {
    routeName: "system-extension",
    permission: "MENU_SYSTEM_EXTENSION"
  }
];

const navPermissionOrder = [
  { routeName: "dashboard", permission: "MENU_DASHBOARD" },
  {
    routeName: "master-data-workspace",
    permissionsAny: [
      "MENU_PRODUCT_MANAGEMENT",
      "MENU_SUPPLIER_MANAGEMENT",
      "MENU_MATERIAL_MANAGEMENT",
      "MENU_BOM_MANAGEMENT",
      "MENU_ROUTE_MANAGEMENT",
      "MENU_EMPLOYEE_MANAGEMENT",
      "MENU_SALES_PLANNING"
    ]
  },
  { routeName: "order-list", permission: "MENU_SALES_PLANNING" },
  {
    routeName: "procurement-workspace",
    permissionsAny: [
      "MENU_PURCHASE_ORDER",
      "MENU_PURCHASE_RECEIPT",
      "MENU_QUALITY_INSPECTION",
      "MENU_INVENTORY_LEDGER"
    ]
  },
  {
    routeName: "production-workspace",
    permissionsAny: [
      "MENU_WORK_ORDER",
      "MENU_OPERATION_REPORT"
    ]
  },
  {
    routeName: "delivery-workspace",
    permissionsAny: ["MENU_DELIVERY_MANAGEMENT", "MENU_RETURN_MANAGEMENT"]
  },
  { routeName: "finance-reports", permission: "MENU_FINANCE_REPORT" },
  {
    routeName: "system-management",
    permissionsAny: ["MENU_SYSTEM_PERMISSION", "MENU_SYSTEM_EXTENSION"]
  }
];

function hasSystemAdminFallback(permission, roleCodes = []) {
  return String(permission || "").startsWith("MENU_SYSTEM_") && roleCodes.includes("ADMIN");
}

function getFirstAllowedMasterDataRoute(permissionCodes = readSession()?.permission_codes || []) {
  const matched = masterDataPermissionOrder.find((item) => {
    if (item.permission) {
      return permissionCodes.includes(item.permission);
    }
    return item.permissionsAny?.some((permission) => permissionCodes.includes(permission));
  });
  return matched?.routeName || "dashboard";
}

function getFirstAllowedProcurementRoute(permissionCodes = readSession()?.permission_codes || []) {
  const matched = procurementPermissionOrder.find((item) => permissionCodes.includes(item.permission));
  return matched?.routeName || "dashboard";
}

function getFirstAllowedProductionRoute(permissionCodes = readSession()?.permission_codes || []) {
  const matched = productionPermissionOrder.find((item) => permissionCodes.includes(item.permission));
  return matched?.routeName || "dashboard";
}

function getFirstAllowedDeliveryRoute(permissionCodes = readSession()?.permission_codes || []) {
  const matched = deliveryPermissionOrder.find((item) => permissionCodes.includes(item.permission));
  return matched?.routeName || "dashboard";
}

function getFirstAllowedSystemRoute(
  permissionCodes = readSession()?.permission_codes || [],
  roleCodes = readSession()?.role_codes || []
) {
  const matched = systemPermissionOrder.find(
    (item) => permissionCodes.includes(item.permission) || hasSystemAdminFallback(item.permission, roleCodes)
  );
  return matched?.routeName || "dashboard";
}

function getFirstAllowedRoute() {
  const session = readSession();
  const permissionCodes = session?.permission_codes || [];
  const roleCodes = session?.role_codes || [];
  const matched = navPermissionOrder.find((item) => {
    if (item.permission) {
      return permissionCodes.includes(item.permission) || hasSystemAdminFallback(item.permission, roleCodes);
    }
    if (item.permissionsAny) {
      return item.permissionsAny.some((permission) => permissionCodes.includes(permission) || hasSystemAdminFallback(permission, roleCodes));
    }
    return false;
  });
  if (matched?.routeName === "master-data-workspace") {
    return getFirstAllowedMasterDataRoute(permissionCodes);
  }
  if (matched?.routeName === "procurement-workspace") {
    return getFirstAllowedProcurementRoute(permissionCodes);
  }
  if (matched?.routeName === "production-workspace") {
    return getFirstAllowedProductionRoute(permissionCodes);
  }
  if (matched?.routeName === "delivery-workspace") {
    return getFirstAllowedDeliveryRoute(permissionCodes);
  }
  if (matched?.routeName === "system-management") {
    return getFirstAllowedSystemRoute(permissionCodes, roleCodes);
  }
  return matched?.routeName || "dashboard";
}

function hasRoutePermission(to, permissionCodes, roleCodes = []) {
  if (to.meta.permission) {
    return permissionCodes.includes(to.meta.permission) || hasSystemAdminFallback(to.meta.permission, roleCodes);
  }

  if (Array.isArray(to.meta.permissionsAny)) {
    return to.meta.permissionsAny.some((permission) => permissionCodes.includes(permission) || hasSystemAdminFallback(permission, roleCodes));
  }

  return true;
}

const routes = [
  {
    path: "/login",
    name: "login",
    component: LoginView,
    meta: { title: "工业风登录", layout: "auth" }
  },
  {
    path: "/",
    name: "dashboard",
    component: DashboardView,
    meta: { title: "原材料批次生命周期追踪", requiresAuth: true, permission: "MENU_DASHBOARD" }
  },
  {
    path: "/order-planning",
    alias: "/sales-planning",
    name: "sales-planning",
    redirect: { name: "order-list" },
    meta: { title: "订单与计划中心", requiresAuth: true, permission: "MENU_SALES_PLANNING" }
  },
  {
    path: "/customer-management",
    name: "customer-management",
    component: SalesPlanningView,
    meta: { title: "客户名录", requiresAuth: true, permission: "MENU_SALES_PLANNING" }
  },
  {
    path: "/order-list",
    name: "order-list",
    component: SalesPlanningView,
    meta: { title: "销售订单列表", requiresAuth: true, permission: "MENU_SALES_PLANNING" }
  },
  {
    path: "/procurement-workspace",
    name: "procurement-workspace",
    redirect: () => ({ name: getFirstAllowedProcurementRoute() }),
    meta: {
      title: "采购与库存",
      requiresAuth: true,
      permissionsAny: [
        "MENU_PURCHASE_ORDER",
        "MENU_PURCHASE_RECEIPT",
        "MENU_QUALITY_INSPECTION",
        "MENU_INVENTORY_LEDGER",
        "MENU_COMPLETION_RECEIPT"
      ]
    }
  },
  {
    path: "/production-workspace",
    name: "production-workspace",
    redirect: () => ({ name: getFirstAllowedProductionRoute() }),
    meta: {
      title: "生产执行",
      requiresAuth: true,
      permissionsAny: [
        "MENU_WORK_ORDER",
        "MENU_OPERATION_REPORT"
      ]
    }
  },
  {
    path: "/delivery-workspace",
    name: "delivery-workspace",
    redirect: () => ({ name: getFirstAllowedDeliveryRoute() }),
    meta: {
      title: "发货概览",
      requiresAuth: true,
      permissionsAny: ["MENU_DELIVERY_MANAGEMENT", "MENU_RETURN_MANAGEMENT"]
    }
  },
  {
    path: "/master-data-workspace",
    name: "master-data-workspace",
    redirect: () => ({ name: getFirstAllowedMasterDataRoute() }),
    meta: {
      title: "基础资料",
      requiresAuth: true,
      permissionsAny: [
        "MENU_PRODUCT_MANAGEMENT",
        "MENU_SUPPLIER_MANAGEMENT",
        "MENU_MATERIAL_MANAGEMENT",
        "MENU_BOM_MANAGEMENT",
        "MENU_ROUTE_MANAGEMENT",
        "MENU_EMPLOYEE_MANAGEMENT",
        "MENU_SALES_PLANNING"
      ]
    }
  },
  {
    path: "/supplier-material-lite",
    name: "supplier-material-lite",
    component: SupplierMaterialLiteView,
    meta: {
      title: "原材料名录",
      requiresAuth: true,
      permissionsAny: ["MENU_SUPPLIER_MANAGEMENT", "MENU_MATERIAL_MANAGEMENT"]
    }
  },
  {
    path: "/product-spec-lite",
    name: "product-spec-lite",
    component: ProductSpecLiteView,
    meta: {
      title: "产品需规清单",
      requiresAuth: true,
      permissionsAny: ["MENU_PRODUCT_MANAGEMENT", "MENU_BOM_MANAGEMENT", "MENU_ROUTE_MANAGEMENT"]
    }
  },
  {
    path: "/supplier-management",
    name: "supplier-management",
    component: SupplierManagementView,
    meta: { title: "供应商名录", requiresAuth: true, permission: "MENU_SUPPLIER_MANAGEMENT" }
  },
  {
    path: "/purchase-orders",
    name: "purchase-orders",
    component: PurchaseOrderView,
    meta: { title: "采购订单", requiresAuth: true, permission: "MENU_PURCHASE_ORDER" }
  },
  {
    path: "/purchase-receipts",
    name: "purchase-receipts",
    component: PurchaseReceiptView,
    meta: { title: "到货入库", requiresAuth: true, permission: "MENU_PURCHASE_RECEIPT" }
  },
  {
    path: "/inventory-ledger",
    name: "inventory-ledger",
    component: InventoryLedgerView,
    meta: { title: "原材料库存台账与批次", requiresAuth: true, permission: "MENU_INVENTORY_LEDGER" }
  },
  {
    path: "/production-ledger",
    name: "production-ledger",
    component: ProductionLedgerView,
    meta: { title: "生产台账", requiresAuth: true, permission: "MENU_WORK_ORDER" }
  },
  {
    path: "/work-order-ledger",
    name: "work-order-ledger",
    redirect: { name: "production-ledger" },
    meta: { title: "生产台账", requiresAuth: true, permission: "MENU_WORK_ORDER" }
  },
  {
    path: "/operation-reports",
    name: "operation-reports",
    component: OperationReportView,
    meta: { title: "工序报工", requiresAuth: true, permission: "MENU_OPERATION_REPORT" }
  },
  {
    path: "/scrap-rework",
    name: "scrap-rework",
    redirect: { name: "operation-reports" },
    meta: { title: "工序报工", requiresAuth: true, permission: "MENU_OPERATION_REPORT" }
  },
  {
    path: "/delivery-management",
    name: "delivery-management",
    component: DeliveryManagementView,
    meta: { title: "发货台账", requiresAuth: true, permission: "MENU_DELIVERY_MANAGEMENT" }
  },
  {
    path: "/equipment-management",
    name: "equipment-management",
    component: EquipmentManagementView,
    meta: { title: "设备管理", requiresAuth: true, permission: "MENU_EQUIPMENT_MANAGEMENT" }
  },
  {
    path: "/quality-inspection",
    name: "quality-inspection",
    component: QualityInspectionView,
    meta: { title: "质量检验", requiresAuth: true, permission: "MENU_QUALITY_INSPECTION" }
  },
  {
    path: "/finance-reports",
    name: "finance-reports",
    component: FinanceReportView,
    meta: { title: "冲压产品材料成本核算", requiresAuth: true, permission: "MENU_FINANCE_REPORT" }
  },
  {
    path: "/return-management",
    name: "return-management",
    redirect: { name: "inventory-ledger" },
    meta: { title: "退货处理", requiresAuth: true, permission: "MENU_INVENTORY_LEDGER" }
  },
  {
    path: "/material-management",
    name: "material-management",
    redirect: { name: "supplier-material-lite" },
    meta: { title: "原材料名录", requiresAuth: true, permission: "MENU_MATERIAL_MANAGEMENT" }
  },
  {
    path: "/bom-management",
    name: "bom-management",
    component: BomManagementView,
    meta: { title: "BOM管理", requiresAuth: true, permission: "MENU_BOM_MANAGEMENT" }
  },
  {
    path: "/process-route-management",
    name: "process-route-management",
    component: ProcessRouteManagementView,
    meta: { title: "工艺路线管理", requiresAuth: true, permission: "MENU_ROUTE_MANAGEMENT" }
  },
  {
    path: "/employee-management",
    name: "employee-management",
    component: EmployeeManagementView,
    meta: { title: "员工管理", requiresAuth: true, permission: "MENU_EMPLOYEE_MANAGEMENT" }
  },
  {
    path: "/master-data-import",
    name: "master-data-import",
    component: MasterDataImportView,
    meta: {
      title: "基础资料导入导出",
      requiresAuth: true,
      permissionsAny: ["MENU_PRODUCT_MANAGEMENT", "MENU_SUPPLIER_MANAGEMENT", "MENU_MATERIAL_MANAGEMENT", "MENU_BOM_MANAGEMENT", "MENU_ROUTE_MANAGEMENT"]
    }
  },
  {
    path: "/product-management",
    name: "product-management",
    component: ProductManagementView,
    meta: { title: "产品管理", requiresAuth: true, permission: "MENU_PRODUCT_MANAGEMENT" }
  },
  {
    path: "/system-management",
    name: "system-management",
    redirect: () => ({ name: getFirstAllowedSystemRoute() }),
    meta: {
      title: "系统管理",
      requiresAuth: true,
      permissionsAny: ["MENU_SYSTEM_PERMISSION", "MENU_SYSTEM_EXTENSION"]
    }
  },
  {
    path: "/system-permissions",
    name: "system-permissions",
    component: SystemPermissionView,
    meta: { title: "系统权限管理", requiresAuth: true, permission: "MENU_SYSTEM_PERMISSION" }
  },
  {
    path: "/system-extension",
    name: "system-extension",
    component: SystemExtensionView,
    meta: { title: "系统拓展", requiresAuth: true, permission: "MENU_SYSTEM_EXTENSION" }
  }
];

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

router.beforeEach(async (to) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    return { name: "login", query: { redirect: to.fullPath } };
  }

  if (to.name === "login" && isAuthenticated()) {
    return { name: getFirstAllowedRoute() };
  }

  if (to.meta.requiresAuth) {
    const session = readSession();
    const permissionCodes = session?.permission_codes || [];
    const roleCodes = session?.role_codes || [];
    if (!hasRoutePermission(to, permissionCodes, roleCodes)) {
      return { name: getFirstAllowedRoute() };
    }
    if (to.name === "operation-reports") {
      const config = await loadSmartOperationReportConfig();
      if (config.enabled === false) {
        return permissionCodes.includes("MENU_WORK_ORDER") ? { name: "production-ledger" } : { name: "dashboard" };
      }
    }
  }

  return true;
});

export default router;
