import Vue from "vue";
import VueRouter from "vue-router";
import layout from "@/layout/index.vue";
import { checkWxWorkEnvAndUserCache, getAgentFrom } from '@/utils/index'
import { checkLoginStatus, initGuidInfo, doWecomLogin, getQyCode, getGuid, getMD5 } from '@/utils/wecomLogin.ts';
import { doWxidLogin } from "@/api/indexAI";
Vue.use(VueRouter);

const router = new VueRouter({
  mode: process.env.NODE_ENV !== "development" ? "history" : "history",
  base: process.env.BASE_URL,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  },
  routes: [
    {
      path: "/",
      component: layout,
      redirect: "/AIDesign",
      children: [
        {
          path: "/AIDesign",
          component: () => import("../views/AIDesign/index.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        {
          path: "/login",
          component: () => import("../views/login/index.vue"),
          meta: { title: "登录" }
        },
        {
          path: "/error/:code",
          component: () => import("../views/errorPage/index.vue")
        },
        {
          path: "/error",
          component: () => import("../views/errorPage/weixinerr.vue")
        },
        //设计页
        {
          path: "/AIDesign/design",
          component: () => import("../views/AIDesign/design.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        //结果页
        {
          path: "/AIDesign/result",
          component: () => import("../views/AIDesign/result.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        //历史页
        {
          path: "/AIDesign/history",
          component: () => import("../views/AIDesign/history.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        //内墙-设计页
        {
          path: "/AIDesign/insideDesign",
          component: () => import("../views/AIDesign/insideDesign.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        //一键诊断-生成页
        {
          path: "/AIDesign/diagnose",
          component: () => import("../views/AIDesign/diagnose.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        //一键诊断-历史页
        {
          path: "/AIDesign/diagnoseHistory",
          component: () => import("../views/AIDesign/diagnoseHistory.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        //一键诊断-结果页
        {
          path: "/AIDesign/diagnoseResult",
          component: () => import("../views/AIDesign/diagnoseResult.vue"),
          meta: { requiresAuth: true } // 标记需要登录的页面
        },
        // 生成方案
        {
          path: "/AIDesign/GeneratePlan",
          component: () => import("../views/AIDesign/GeneratePlan.vue"),
          meta: { requiresAuth: true }
        },
      ]
    },
  ]
});
// 全局前置守卫：只对需要登录的页面进行登录校验
router.beforeEach(async (to, from, next) => {
  console.log("to=", to)
  if (!to.meta || (to.meta && !to.meta.requiresAuth)) {
    next();
    return;
  }
  try {
    //先判断企微环境
    // checkWxWorkEnvAndUserCache();
    const { loginType, wxid, WecomType } = to.query;
    // 初始化登录模式标识
    initLoginModeFlag(loginType);
    // 判断当前登录模式，分发处理逻辑
    const isNewLoginMode = sessionStorage.getItem('isNewLoginMode') === 'true';
    if (isNewLoginMode) {
      await handleWxidLoginMode(to, next, wxid, WecomType);
    } else {
      await handleCodeLoginMode(to, next);
    }
  } catch (error) {
    console.error("登录校验过程异常:", error);
    next({ path: "/error" });
  }
});


/**
 * 新登录方式处理：强制检测登录 → 获取Token → 缓存 → 放行/失败跳转
 * @param to 目标路由
 * @param next 路由放行方法
 */
async function handleWxidLoginMode(to, next, wxid, WecomType) {
  try {
    window.localStorage.setItem('loginMode', 'wxidLogin');
    if (wxid) {
      window.localStorage.setItem('weChat', wxid);
    }
    if (WecomType) {
      const agentFrom = getAgentFrom(WecomType);
      window.localStorage.setItem('agentFrom', agentFrom);
      window.localStorage.setItem('agentFromAI', agentFrom);
    }
    // 3. 初始化鉴权信息，校验登录状态
    initGuidInfo();
    if (checkLoginStatus()) return next();
    // 4. wxid参数校验
    let wxId = wxid ? wxid : window.localStorage.getItem("weChat");
    if (!wxId) return redirectToError(next, "wxid参数缺失，无权限");
    const formData = new FormData();
    const timestamp = new Date().getTime().toString();
    const nonce = getGuid();
    const sign = getMD5(nonce, timestamp, wxId);
    formData.append('wxId', wxId);
    formData.append('timestamp', timestamp);
    formData.append('nonce', nonce);
    formData.append('sign', sign);
    doWxidLogin(formData)
      .then((res) => {
        if (res && res.StatusCode === 200 && res.Data && res.Data.token) {
          const userInfoV1 = JSON.stringify(res.Data);
          window.localStorage.setItem('userInfoV1', userInfoV1);
          window.localStorage.setItem('AIToken', res.Data.token);
          window.localStorage.setItem('isRefreshProvider', res.Data.isRefreshProvider);
          window.localStorage.setItem('weChat', res.Data.weChat);
          console.log(`新登录成功，Token已缓存，即将进入 ${to.path}`);
          // debugger
          next();
        } else {
          throw new Error('新登录失败，未获取到Token');
        }
      })
      .catch(() => {
        // 登录失败：跳转错误页
        next({ path: "/error", replace: true });
      });
  } catch (err) {
    console.error('新登录方式处理异常：', err);
    next({ path: "/error", replace: true });
  }
}

/**
 * 旧登录方式处理：原有企微code授权登录逻辑
 * @param to 目标路由
 * @param next 路由放行方法
 */
function handleCodeLoginMode(to, next) {
  const org_loginMode = window.localStorage.getItem('loginMode');
  if (org_loginMode != 'codeLogin') {
    window.localStorage.clear();
  }
  window.localStorage.setItem('loginMode', 'codeLogin');
  //验证时间戳和token
  initGuidInfo();
  if (checkLoginStatus()) return next();
  const code = to.query.code as string;
  let finalCode;
  if (Array.isArray(code)) {
    finalCode = code.length > 0 ? code[code.length - 1] : null;
  } else {
    finalCode = code || null;
  }
  if (finalCode) {
    doWecomLogin(finalCode)
      .then(() => {
        // debugger
        next();
        console.log(`登录成功，即将进入 ${to.path}`);
      })
      .catch(() => {
        next({ path: "/error" });
      });
  } else {
    // debugger
    console.log(`访问 ${to.path} 需登录，正在跳转到授权页面`);
    getQyCode();
  }
}

/**
 * 初始化登录模式标识 - 保证会话内登录方式统一
 * @param {string} loginType 路由传参的登录类型
 */
function initLoginModeFlag(loginType) {
  const isNewLoginMode = loginType && String(loginType) === '2';
  // 保证本次会话的登录方式不变
  if (isNewLoginMode) {
    sessionStorage.setItem("isNewLoginMode", 'true');
  }
}

/**
 * 跳转错误页并存储错误信息
 * @param {Function} next 路由放行函数
 * @param {string} msg 错误提示信息
 */
function redirectToError(next, msg = '参数缺失，无权限') {
  sessionStorage.setItem("errorMsgTit", msg);
  next({ path: '/error', replace: true });
}
export default router;
