<script setup>
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app';
import { useUserStore } from '@/store/modules/user';
import { getDingTalkAuthCode } from '@/utils/dingtalk';
import * as dd from 'dingtalk-jsapi';

const userStore = useUserStore();

onLaunch(async (options) => {
  console.log('App Launch');
  
  // 仅在钉钉环境下尝试免登
  if (dd.env.platform !== 'notInDingTalk') {
    // 如果没有 token，或者用户信息为空，尝试免登
    if (!userStore.token) {
      userStore.setRequestLoading('isLogining', true);
      try {
        const corpId = options?.query?.corpId || import.meta.env.VITE_DINGTALK_CORPID;
        const code = await getDingTalkAuthCode(corpId);
        if (code) {
          console.log('Got DingTalk AuthCode, logging in...', code);
          await userStore.dingTalkLogin(code);
          console.log('DingTalk Login Success');
        }
      } catch (err) {
        console.error('DingTalk Auto Login Failed:', err);
        // 如果免登失败（通常是没找到用户），则跳转注册页面
        uni.reLaunch({ url: '/pages/login/index' });
      } finally {
        userStore.setRequestLoading('isLogining', false);
      }
    }
  } else if (!userStore.token) {
    // 不在钉钉环境下且没登录，也引导去注册或者登录跳转（暂统一引导至注册或默认逻辑）
    uni.reLaunch({ url: '/pages/login/index' });
  }
});

onShow(() => {
  console.log('App Show');
});

onHide(() => {
  console.log('App Hide');
});
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "@/styles/global.scss";
	@import "@/styles/business.scss";
</style>
