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

    <view class="login-box">
      <view class="header">
        <text class="title">欢迎登录</text>
        <text class="subtitle">登录科研钉钉平台</text>
      </view>

      <view class="form-group">
        <text class="label">账号</text>
        <uv-input v-model="loginForm.userName" placeholder="请输入您的账号" placeholderClass="placeholder-style" border="none"
          shape="circle" clearable
          customStyle="background: #f1f5f9; padding: 20rpx 30rpx; height: 60rpx; border: 2rpx solid transparent; transition: all 0.3s ease; border-radius: 20rpx;">
          <template #prefix>
            <uv-icon name="account" size="22" color="#94a3b8" customStyle="margin-right: 16rpx"></uv-icon>
          </template>
        </uv-input>
      </view>

      <view class="form-group">
        <text class="label">密码</text>
        <uv-input v-model="loginForm.password" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码"
          placeholderClass="placeholder-style" border="none" shape="circle"
          customStyle="background: #f1f5f9; padding: 20rpx 30rpx; height: 60rpx; border: 2rpx solid transparent; transition: all 0.3s ease; border-radius: 20rpx;">
          <template #prefix>
            <uv-icon name="lock" size="22" color="#94a3b8" customStyle="margin-right: 16rpx"></uv-icon>
          </template>
          <template #suffix>
            <uv-icon :name="showPassword ? 'eye-fill' : 'eye-off'" size="22" color="#94a3b8"
              @click="showPassword = !showPassword" customStyle="margin-left: 16rpx; cursor: pointer"></uv-icon>
          </template>
        </uv-input>
      </view>

      <view class="form-group" v-if="configSetting.isCaptcha === '10'">
        <text class="label">验证码</text>
        <view class="captcha-group">
          <uv-input v-model="loginForm.idValueC" placeholder="请输入验证码" placeholderClass="placeholder-style" border="none"
            shape="circle" clearable
            customStyle="flex: 1; background: #f1f5f9; padding: 20rpx 30rpx; height: 60rpx; border: 2rpx solid transparent; transition: all 0.3s ease; border-radius: 20rpx;">
            <template #prefix>
              <uv-icon name="photo" size="22" color="#94a3b8" customStyle="margin-right: 16rpx"></uv-icon>
            </template>
          </uv-input>
          <image v-if="codeUrl" :src="codeUrl" class="captcha-img" @click="getCaptchaImg" mode="aspectFit"></image>
        </view>
      </view>

      <view class="options">
        <uv-checkbox-group v-model="rememberMeArr">
          <uv-checkbox label="记住密码" name="remember" shape="square" activeColor="#3b82f6" labelSize="13" iconSize="14"
            size="16" labelColor="#475569"></uv-checkbox>
        </uv-checkbox-group>

        <!-- <text class="forgot">忘记密码？</text> -->
      </view>

      <uv-button text="登 录" @click="handleLogin" :loading="loading" shape="circle"
        color="linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)"
        customStyle="height: 100rpx; font-size: 32rpx; font-weight: 600; letter-spacing: 2rpx; box-shadow: 0 10rpx 20rpx rgba(37, 99, 235, 0.3); border: none; margin-top: 20rpx;" />

      <!-- 钉钉免登按钮 (仅在钉钉环境下显示) -->
      <view v-if="isInDingTalk" style="margin-top: 30rpx;">
        <uv-button text="钉钉一键登录" @click="handleDingTalkLogin" :loading="dingTalkLoading" shape="circle" plain
          color="#0089ff"
          customStyle="height: 100rpx; font-size: 30rpx; font-weight: 500; border: 2rpx solid #0089ff; color: #0089ff;">
          <template #prefix>
            <uv-icon name="dingtalk" size="24" color="#0089ff" customStyle="margin-right: 12rpx"></uv-icon>
          </template>
        </uv-button>
      </view>

      <view class="footer">
        <text class="footer-text">还没有账号？</text>
        <text class="footer-link" @click="goToRegister">立即注册</text>
      </view>
    </view>

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

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store/modules/user';
import type { LoginParams } from '@/types/user';
import { CACHE_KEY } from '@/constants/index';
// @ts-ignore
import { Local } from '@/utils/storage';
import { useLoginApi } from '@/api/system/login';
import { encryptWithBackendConfig } from '@/utils/aesCrypto';
import { getDingTalkAuthCode } from '@/utils/dingtalk';
import * as dd from 'dingtalk-jsapi';

const userStore = useUserStore();

const { configSetting } = storeToRefs(userStore);

const { checkCaptcha, login, dingTalkLogin } = userStore;

const loginApi = useLoginApi();

const loginForm = reactive<LoginParams>({
  userName: '',
  password: '',
  idValueC: '',
  idKeyC: '',
  saltValue: '',
});

const codeUrl = ref('');
const loading = ref(false);
const dingTalkLoading = ref(false);
const showPassword = ref(false);
const rememberMeArr = ref<string[]>([]);
const toastRef = ref<any>(null);

// 是否在钉钉环境中
const isInDingTalk = ref(dd.env.platform !== 'notInDingTalk');

onMounted(async () => {
  // --- 新增：登录拦截 ---
  // 如果缓存里已经有 Token，说明当前处于已登录状态
  // 不应该停留在当前登录大厅，直接跳走回首页
  const existingToken = Local.get(CACHE_KEY.TOKEN);
  if (existingToken) {
    uni.switchTab({ url: '/pages/home/index' }).catch((err) => {
      console.warn('switchTab failed, trying reLaunch:', err);
      uni.reLaunch({ url: '/pages/home/index' });
    });
    return; // 不要继续执行后面的加载验证码之类
  }

  // 检查是否有记住的密码
  const savedUser = Local.get(CACHE_KEY.REMEMBER_USER);
  if (savedUser) {
    // 可能是对象也可能是 JSON
    const user = typeof savedUser === 'string' ? JSON.parse(savedUser) : savedUser;
    loginForm.userName = user.userName || user.username;
    loginForm.password = user.password;
    rememberMeArr.value = ['remember'];
  }

  await checkCaptcha();
  if (configSetting.value.isCaptcha === '10') {
    getCaptchaImg();
  }
});

const getCaptchaImg = async () => {
  try {
    const res = await loginApi.getCaptchaImg();
    codeUrl.value = res?.data?.base64stringC || '';
    loginForm.idKeyC = res?.data?.idKeyC || '';
  } catch (error) {
    console.error('获取验证码失败', error);
  }
};

const handleLogin = async () => {
  if (!loginForm.userName) {
    toastRef.value.show({ message: '请输入账号', type: 'error' });
    return;
  }
  if (!loginForm.password) {
    toastRef.value.show({ message: '请输入密码', type: 'error' });
    return;
  }

  if (configSetting.value.isCaptcha === '10' && !loginForm.idValueC) {
    toastRef.value.show({ message: '请输入验证码', type: 'error' });
    return;
  }

  loading.value = true;

  try {
    // 使用与后端完全匹配的加密函数加密密码
    const encryptedPassword = encryptWithBackendConfig(loginForm.password);
    loginForm.saltValue = encryptedPassword; // 后端AES IV常量 登录的时候 增加saltValue

    // 调用 store 处理真实请求和持久化
    await login(loginForm);

    // 记住密码逻辑独立于全局token的持久化
    if (rememberMeArr.value.includes('remember')) {
      Local.set(CACHE_KEY.REMEMBER_USER, {
        userName: loginForm.userName,
        password: loginForm.password
      });
    } else {
      Local.remove(CACHE_KEY.REMEMBER_USER);
    }

    toastRef.value.show({ message: '登录成功', type: 'success' });

    // 登录成功跳转首页
    setTimeout(() => {
      uni.switchTab({ url: '/pages/home/index' }).catch((err) => {
        console.warn('switchTab failed, trying reLaunch:', err);
        uni.reLaunch({ url: '/pages/home/index' });
      });
    }, 1000);

  } catch (error) {
    console.error('Login Failed', error);
    // 登录失败若有验证码，刷新验证码
    if (configSetting.value.isCaptcha === '10') {
      loginForm.idValueC = '';
      getCaptchaImg();
    }
  } finally {
    loading.value = false;
  }
};

const goToRegister = () => {
  uni.navigateTo({ url: '/pages/login/register' });
};

/**
 * 钉钉免登逻辑
 */
const handleDingTalkLogin = async () => {
  dingTalkLoading.value = true;
  try {
    // 尝试从当前 URL 获取 corpId，或者使用配置
    // 注意：如果是通过 HBuilderX 运行到浏览器的，通常需要手动传入 corpId 调试
    const corpId = uni.getLaunchOptionsSync()?.query?.corpId || import.meta.env.VITE_DINGTALK_CORPID;

    const code = await getDingTalkAuthCode(corpId);

    if (!code) {
      throw new Error('获取授权码失败');
    }

    await dingTalkLogin(code);

    toastRef.value.show({ message: '钉钉免登成功', type: 'success' });

    // 跳转首页
    setTimeout(() => {
      uni.switchTab({ url: '/pages/home/index' }).catch((err) => {
        uni.reLaunch({ url: '/pages/home/index' });
      });
    }, 1000);

  } catch (error: any) {
    console.error('DingTalk Login Error:', error);
    toastRef.value.show({
      message: error.message || error.errorMessage || '钉钉免登失败',
      type: 'error'
    });
  } finally {
    dingTalkLoading.value = false;
  }
};
</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);
}

.login-box {
  width: 100%;
  max-width: 600rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 40rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
  border: 2rpx solid rgba(255, 255, 255, 0.5);
}

.header {
  margin-bottom: 60rpx;
}

.title {
  font-size: 56rpx;
  font-weight: 800;
  color: #1e293b;
  display: block;
  margin-bottom: 16rpx;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.subtitle {
  font-size: 28rpx;
  color: #64748b;
  display: block;
}

.form-group {
  margin-bottom: 40rpx;
}

.label {
  font-size: 26rpx;
  font-weight: 600;
  color: #334155;
  margin-bottom: 16rpx;
  display: block;
}

/* 移除原有的 input-container 和 checkbox 样式，采用 uvui 内置属性或者 customStyle 修改样式 */

:deep(.placeholder-style) {
  color: #94a3b8 !important;
  font-size: 28rpx;
}

.captcha-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.captcha-img {
  width: 200rpx;
  height: 104rpx;
  /* 与左侧输入框 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>
