<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) {
      try {
        // 尝试从 URL 获取 corpId（钉钉微应用通常在打开时会自动在 URL 后带上 corpId）
        // 也可以从环境变量 VITE_DINGTALK_CORPID 获取
        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);
          alert(code)
          await userStore.dingTalkLogin(code);
          console.log('DingTalk Login Success');
        }
      } catch (err) {
        console.error('DingTalk Auto Login Failed:', err);
        // 如果免登失败且没有 Token，通常需要引导至手动登录也或报错
        // 这里视业务需求而定，通常免登失败我们不再强制阻塞，除非是纯免登系统
      }
    }
  }
});

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

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

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