<template>
  <view class="container">
    <view class="bg-shape shadow"></view>
    <view class="bg-shape2 shadow"></view>

    <view class="loading-box">
      <uv-loading-icon color="#3b82f6" size="30"></uv-loading-icon>
      <text class="loading-text">正在自动登录，请稍候...</text>
    </view>

    <uv-toast ref="toastRef"></uv-toast>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { getDingTalkAuthCode } from '@/utils/dingtalk';
import * as dd from 'dingtalk-jsapi';

const userStore = useUserStore();
const toastRef = ref<any>(null);

onMounted(async () => {
  // --- 逻辑拦截 ---
  // 如果缓存里已经有 Token，说明当前处于已登录状态
  if (userStore.token) {
    uni.switchTab({ url: '/pages/home/index' }).catch(() => {
      uni.reLaunch({ url: '/pages/home/index' });
    });
    return;
  }

  // 仅在钉钉环境下尝试免登
  if (dd.env.platform !== 'notInDingTalk') {
    try {
      const corpId = uni.getLaunchOptionsSync()?.query?.corpId || import.meta.env.VITE_DINGTALK_CORPID;
      const code = await getDingTalkAuthCode(corpId);
      if (code) {
        await userStore.dingTalkLogin(code);
        toastRef.value.show({ message: '登录成功', type: 'success' });
        // 成功，跳转首页
        setTimeout(() => {
          uni.switchTab({ url: '/pages/home/index' }).catch(() => {
            uni.reLaunch({ url: '/pages/home/index' });
          });
        }, 800);
      } else {
        throw new Error('未获取到授权码');
      }
    } catch (error) {
      console.error('DingTalk Login Failure in Login Page:', error);
      // 免登失败（或账号未绑定），引导去注册
      uni.reLaunch({ url: '/pages/login/register' });
    }
  } else {
    // 不在钉钉环境下，直接跳转到注册页（因为不需要登录页）
    uni.reLaunch({ url: '/pages/login/register' });
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  position: relative;
  background: #f8fafc;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 40rpx;
}

.bg-shape {
  position: absolute;
  top: -100rpx;
  right: -100rpx;
  width: 500rpx;
  height: 500rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6 0%, #2dd4bf 100%);
  opacity: 0.15;
  filter: blur(40rpx);
}

.bg-shape2 {
  position: absolute;
  bottom: -150rpx;
  left: -100rpx;
  width: 600rpx;
  height: 600rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #8b5cf6 0%, #ec4899 100%);
  opacity: 0.15;
  filter: blur(50rpx);
}

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
  /* 与左侧输入框 60(height) + 40(padding) + 4(border) 高度保持一致 */
  border-radius: 20rpx;
  background: #f1f5f9;
  flex-shrink: 0;
  cursor: pointer;
}

.options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 50rpx;
}

.forgot {
  font-size: 26rpx;
  color: #3b82f6;
  font-weight: 500;
  padding: 10rpx 0;
}

.footer {
  margin-top: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.footer-text {
  font-size: 26rpx;
  color: #64748b;
}

.footer-link {
  font-size: 26rpx;
  color: #3b82f6;
  font-weight: 600;
  margin-left: 10rpx;
}
</style>
