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

    <view v-if="showOAuthLoading" class="loading-box">
      <uv-loading-icon color="#3b82f6" size="30"></uv-loading-icon>
      <text class="loading-text">正在登录中...</text>
    </view>

    <view v-else 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 style="margin-top: 30rpx;">
        <uv-button text="企业微信登录" @click="handleEnterpriseLoginClick" :loading="loading" shape="circle" plain
          color="#07c160"
          customStyle="height: 100rpx; font-size: 30rpx; font-weight: 500; border: 2rpx solid #07c160; color: #07c160;">
          <template #prefix>
            <uv-icon name="weixin-fill" size="24" color="#07c160" 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';

const userStore = useUserStore();

const { configSetting } = storeToRefs(userStore);

const { checkCaptcha, login } = userStore;

const loginApi = useLoginApi();

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

const codeUrl = ref('');
const loading = ref(false);
const showPassword = ref(false);
const rememberMeArr = ref<string[]>([]);
const toastRef = ref<any>(null);
// 企业微信免登回调：显示加载态（避免用户看到账号/密码输入框）
const showOAuthLoading = ref<boolean>(false);

const getUrlCode = (): string | undefined => {
  const rawCode = (uni.getLaunchOptionsSync()?.query as any)?.code as undefined | string | string[];
  const urlCode = Array.isArray(rawCode) ? rawCode[0] : rawCode;
  if (urlCode) return urlCode;

  // H5: 形如 ?code=xxx&state=STATE#/pages/login/index，code 在 search 中
  if (typeof window !== 'undefined') {
    try {
      const params = new URLSearchParams(window.location.search);
      const searchCode = params.get('code');
      if (searchCode) return searchCode;

      // 兜底：如果 code 出现在 hash 的参数里，也尝试解析
      const hash = window.location.hash || '';
      const hashParamsIndex = hash.indexOf('?');
      if (hashParamsIndex !== -1) {
        const hashParams = hash.substring(hashParamsIndex + 1);
        const hashSearchParams = new URLSearchParams(hashParams);
        const hashCode = hashSearchParams.get('code');
        if (hashCode) return hashCode;
      }
    } catch (e) {
      // ignore
    }
  }

  return undefined;
};

onMounted(async () => {
  // --- 新增：登录拦截 ---
  // 如果缓存里已经有 Token，说明当前处于已登录状态
  // 不应该停留在当前登录大厅，直接跳走回首页
  const existingToken = Local.get(CACHE_KEY.TOKEN);
  if (existingToken) {
    showOAuthLoading.value = false;
    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'];
  }

  // 检测 URL 是否携带 code (企业微信免登)
  const urlCode = getUrlCode();
  if (urlCode) {
    showOAuthLoading.value = true;
    await handleEnterpriseLogin(urlCode);
    return;
  }

  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 handleEnterpriseLogin = async (code: string) => {
  try {
    loading.value = true;
    await userStore.oAuthLogin(code);
    toastRef.value.show({ message: '登录成功', type: 'success' });
    
    // 成功跳转首页
    setTimeout(() => {
      uni.switchTab({ url: '/pages/home/index' }).catch(() => {
        uni.reLaunch({ url: '/pages/home/index' });
      });
    }, 800);
  } catch (error: any) {
    console.error('Enterprise Login Failure:', error);
    toastRef.value.show({ 
      message: error.message || '企业快捷登录失败', 
      type: 'error' 
    });

    // 免登失败后切回手动登录表单
    showOAuthLoading.value = false;

    // 如果免登失败，正常加载验证码进入手动登录模式
    await checkCaptcha();
    if (configSetting.value.isCaptcha === '10') {
      getCaptchaImg();
    }
  } finally {
    loading.value = false;
  }
};

/**
 * 企业微信登录点击 (重定向获取 code)
 */
const handleEnterpriseLoginClick = () => {
  // 注意：实际 AppID 需要根据后台配置，此处假设通过环境变量或逻辑获取
  // 如果是免登，通常是直接进入这个页面时 URL 就已经带了 code
  // 如果需要手动点击跳转获取，则执行如下逻辑：
  const appid = import.meta.env.VITE_WECOM_APPID || ''; 
  const redirectUri = encodeURIComponent(window.location.href.split('?')[0]);
  const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
  
  // H5 环境下跳转
  window.location.href = url;
};
</script>

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

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
  border-radius: 20rpx;
  background: #f1f5f9;
  flex-shrink: 0;
  padding: 40rpx 30rpx;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 26rpx;
  color: #64748b;
  font-weight: 500;
}

.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>
