<template>
  <view class="wh-full">
    <BasicLoading
        :isShow="isShow"
        bgColor="#fff"
        isShowTitle
        textColor="#000"
        title="启动中..."
        :type="1"
    />
  </view>
</template>

<script lang="ts" setup>
import {onLoad} from "@dcloudio/uni-app";
import {useDataStore} from "@/store/modules/data";
import {useMenuStore} from "@/store/modules/menu";
import {useUserStore} from "@/store/modules/user";
import {checkOpenId} from "@/api/system/login";
import {getMobileMenuApi} from "@/api/system/menu";
import {getPermissionChangeTimeApi} from "@/api/system/config";

const dataStore = useDataStore();
const menuStore = useMenuStore();
const { setGlobal, getFile } = dataStore;
const userStore = useUserStore();
const { afterLoginAction } = userStore;
const isShow = ref(true);

function goByqd(data: any) {
  if (data && data.qdId) {
    // 有签到参数，重定向到签到确认页面
    let confirmUrl = `/pages/view/routine/qd/confirm?qdId=${data.qdId}`;
    if (data.rqgqtime) {
      confirmUrl += `&rqgqtime=${data.rqgqtime}`;
    }
    if (data.timestampqd) {
      confirmUrl += `&timestampqd=${data.timestampqd}`;
    }

    console.log('重定向到签到确认页面:', confirmUrl);
    uni.reLaunch({
      url: confirmUrl
    });
    return;
  }

}

function goByJs(js: any) {
  if (js.confirmStatus == "A") {
    // 跳转到自助服务首页
    uni.reLaunch({
      url: "/pages/base/service/index",
    });
  } else {
    dataStore.setFile({
      ...js,
      ...dataStore.getFile,
    });
    setTimeout(() => {
      uni.reLaunch({
        url: "/pages/view/hr/teacherProfile/index",
      });
    }, 1500);
  }
}

onLoad(async (data: any) => {
  console.log('launchPage onLoad - 接收到的参数:', data);
  if (data && data.openId) {
    // ⭐ 先保存参数到 global，确保后续页面可以获取
    setGlobal({
      openId: data.openId,
      menu: data.menu,
      type: data.type || 2,  // 默认为教师端
      profilePhoto: data.profilePhoto,
      qdId: data.qdId,
      rqgqtime: data.rqgqtime,
      timestampqd: data.timestampqd
    });
    console.log('已保存参数到 global:', {openId: data.openId, type: data.type});

    try {
      const res = await checkOpenId({
        openId: data.openId,
        appCode: "JS",
      });
      if (res.resultCode == 1 && res.result) {
        // 执行登录操作
        afterLoginAction(res.result);

        // 判断是否需要拉取菜单：时间戳不一致或本地无菜单则重新请求
        let needFetchMenu = true;
        try {
          const timeRes = await getPermissionChangeTimeApi();
          console.log('[launchPage] getPermissionChangeTime 原始返回:', JSON.stringify(timeRes));
          const serverChangeTime = String((timeRes as any)?.result ?? '');
          const localChangeTime = userStore.getChangeTime || '';
          const localMenu = menuStore.getMobileMenu || [];
          needFetchMenu = serverChangeTime !== localChangeTime || !localMenu?.length;
          console.log('[launchPage] serverChangeTime:', serverChangeTime, 'localChangeTime:', localChangeTime, 'localMenuLength:', localMenu?.length ?? 0, 'needFetchMenu:', needFetchMenu);
          if (serverChangeTime) userStore.setChangeTime(serverChangeTime);
        } catch (e) {
          console.warn('[launchPage] getPermissionChangeTime 失败:', e);
          needFetchMenu = true;
        }

        if (needFetchMenu) {
          console.log('[launchPage] 调用 find-mobile-menu');
          await getMobileMenuApi()
            .then((r) => {
              if (r?.result && Array.isArray(r.result) && r.result.length > 0) {
                menuStore.setMobileMenu(r.result);
              }
            })
            .catch(() => {});
        } else {
          console.log('[launchPage] 跳过 find-mobile-menu，使用本地缓存');
        }

        if (data && data.qdId) {
          goByqd(data);
        } else {
          goByJs(res.result.js);
        }
      } else {
        uni.reLaunch({
          url: "/pages/system/login/login",
        });
      }
    } catch (err) {
      console.error('launchPage onLoad - checkOpenId失败:', err);
      uni.reLaunch({
        url: "/pages/system/login/login"
      });
    }
  } else {
    console.log('launchPage onLoad - 没有openId参数，跳转到登录页面');
    uni.reLaunch({
      url: "/pages/system/login/login"
    });
  }
});
</script>
