<template>
  <div class="login-bg">
    <div class="login-card">
      <div class="login-side">
        <div class="brand">
          <img src="@/assets/svgs/logo-w.svg" alt="Logo" style="color: white;width: 50px;" />
          <span class="brand-title">后台管理系统</span>
        </div>
        <div class="illus">
          <svg viewBox="0 0 300 160" style="max-width: 100%" fill="none">
            <ellipse cx="150" cy="140" rx="120" ry="16" fill="#edf4fd" />
            <rect x="57" y="58" width="60" height="40" rx="12" fill="#64b6f7" />
            <rect x="125" y="46" width="110" height="64" rx="14" fill="#389bf7" opacity="0.11" />
            <rect x="136" y="60" width="60" height="41" rx="10" fill="#b8e1ff" />
          </svg>
        </div>
        <!-- 版权信息 -->
        <div class="copyright">© 2026 Yunzer 管理系统</div>
      </div>
      <div class="login-panel">
        <h2 class="login-title">欢迎登录租户端</h2>
        <div class="login-desc">请填写您的账号信息</div>
        <div class="form-group icon-input-group">
          <span class="input-icon">
            <i class="fa-solid fa-building-columns"></i>
          </span>
          <input v-model="tenant_name" type="text" placeholder="租户名称" autocomplete="tenant_name"
            class="input input-with-icon" />
        </div>
        <div class="form-group icon-input-group">
          <span class="input-icon">
            <i class="fa-solid fa-user"></i>
          </span>
          <input
            v-model="account"
            type="text"
            :placeholder="verifyType === 'sms' ? '手机号' : verifyType === 'email' ? '邮箱' : '用户名'"
            :autocomplete="verifyType === 'sms' ? 'tel' : 'account'"
            class="input input-with-icon"
          />
        </div>
        <div class="form-group icon-input-group">
          <span class="input-icon">
            <i class="fa-solid fa-lock"></i>
          </span>
          <input v-model="password" :type="passwordVisible ? 'text' : 'password'" placeholder="密码"
            autocomplete="current-password" class="input input-with-icon" />
          <span class="visible-btn" @click="passwordVisible = !passwordVisible"
            :title="passwordVisible ? '隐藏密码' : '显示密码'">
            <i v-if="passwordVisible" class="fa-regular fa-eye"></i>
            <i v-else class="fa-solid fa-eye-slash"></i>
          </span>
        </div>
        <div v-if="openVerifyEnabled && verifyType === 'captcha'" class="form-group code-row">
          <input v-model="captchaInput" type="text" placeholder="请输入4位验证码" class="input code-input" />
          <button class="code-btn" type="button" @click="generateCaptcha">{{ captchaText }}</button>
        </div>
        <div v-if="openVerifyEnabled && (verifyType === 'sms' || verifyType === 'email')" class="form-group code-row">
          <input v-model="smsCode" type="text" placeholder="短信验证码" class="input code-input" />
          <button class="code-btn" :disabled="codeLoading || countdown > 0" @click="handleSendLoginCode">
            {{ countdown > 0 ? `${countdown}s` : (codeLoading ? "发送中..." : "发送验证码") }}
          </button>
        </div>


        <!-- 极验验证码容器 -->
        <div style="display: none;" v-if="openVerifyEnabled && verifyType === 'geetest' && showCaptchaContainer" class="geetest-container" ref="captchaContainer"></div>

        <div class="remember-me-row">
          <label class="remember-me-label">
            <input type="checkbox" v-model="rememberMe" class="remember-me-checkbox" @change="handleRememberMeChange" />
            <span>记住我</span>
          </label>
          <div class="action-links">
            <a class="register-link" @click.prevent="goRegister">注册账号</a>
            <span class="divider">|</span>
            <a class="forget-link" @click.prevent="goForget">忘记密码?</a>
          </div>
        </div>
        <transition name="fade">
          <div v-if="errorMsg" class="error-msg">{{ errorMsg }}</div>
        </transition>
        <button class="login-btn" @click="handleLogin" :disabled="loading">
          {{ loading ? "登录中..." : "登 录" }}
        </button>
      </div>
    </div>
    <!-- 背景光效 -->
    <div class="login-light light1"></div>
    <div class="login-light light2"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import { login, getOpenVerify, getGeetest4Infos, sendLoginCode } from "@/api/login";
import "@/assets/js/gt4.js";
import { ElMessageBox, ElMessage } from "element-plus";

const router = useRouter();
const authStore = useAuthStore();

// --- 表单数据 ---
const tenant_name = ref("");
// 页面加载阶段先不展示验证码，等 getOpenVerify 拉取真实配置后再决定渲染
const openVerifyEnabled = ref(false);
const verifyType = ref<"captcha" | "sms" | "geetest" | "email">("captcha");
const account = ref("");
const password = ref("");
const smsCode = ref("");
const captchaInput = ref("");
const captchaText = ref("");
const passwordVisible = ref(false);
const rememberMe = ref(false);
const loading = ref(false);
const codeLoading = ref(false);
const countdown = ref(0);
let countdownTimer: ReturnType<typeof setInterval> | null = null;
const errorMsg = ref("");

// --- 极验相关变量 ---
const showCaptchaContainer = ref(false);
const captchaContainer = ref<HTMLElement | null>(null);
const captchaInstance = ref<any>(null);

// --- 初始化登录验证配置 ---
const initVerifyConfig = async () => {
  try {
    const verifyRes = await getOpenVerify();
    let openVerify = "0";
    let verifyTypeVal: any = "captcha";

    if (verifyRes && verifyRes.code === 200 && Array.isArray(verifyRes.data)) {
      verifyRes.data.forEach((item: any) => {
        if (item.label === "openVerify") {
          openVerify = item.value || "0";
        }
        if (item.label === "verifyType") {
          verifyTypeVal = item.value || "captcha";
        }
      });
    }

    openVerifyEnabled.value = openVerify === "1";
    verifyType.value = verifyTypeVal as any;

    // 仅 captcha 模式需要生成本地验证码文案
    if (openVerifyEnabled.value && verifyType.value === "captcha") {
      generateCaptcha();
    }
  } catch (err) {
    // 配置拉取失败时：默认关闭验证码模块，避免误展示
    openVerifyEnabled.value = false;
  }
};

// --- 加载JS脚本 ---
const loadScript = (url: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    script.onload = () => resolve();
    script.onerror = () => reject(new Error(`加载脚本失败: ${url}`));
    document.head.appendChild(script);
  });
};

// --- 清理验证码实例 ---
const cleanCaptchaInstance = () => {
  if (captchaInstance.value) {
    try {
      captchaInstance.value.destroy();
    } catch (e) {
      console.warn("销毁验证码实例失败:", e);
    }
    captchaInstance.value = null;
    showCaptchaContainer.value = false;
  }
};

// --- 执行登录请求 ---
const performLoginRequest = async () => {
  // 根据不同验证方式，把正确的 code 传给后端
  const codeToSend =
    openVerifyEnabled.value && verifyType.value === "captcha" ? captchaInput.value : smsCode.value;

  const res = await login({
    tenant_name: tenant_name.value,
    account: account.value,
    password: password.value,
    code: codeToSend
  });

  if (res && res.code === 200) {
    // 登录成功：处理"记住我"
    if (rememberMe.value) {
      localStorage.setItem("loginAccount", account.value);
      localStorage.setItem("loginTenantName", tenant_name.value);
      localStorage.setItem("loginPassword", password.value);
      localStorage.setItem("loginRememberMe", "true");
    } else {
      localStorage.removeItem("loginAccount");
      localStorage.removeItem("loginTenantName");
      localStorage.removeItem("loginPassword");
      localStorage.setItem("loginRememberMe", "false");
    }

    authStore.setLoginInfo(res.data);

    // 重置 Tabs 状态
    const { useTabsStore } = await import("@/stores");
    const tabsStore = useTabsStore();
    tabsStore.resetTabs();

    router.push({ path: "/home" });
    ElMessage.success("登录成功！");
    return true;
  } else {
    errorMsg.value = res.msg || "登录失败";
    return false;
  }
};

const generateCaptcha = () => {
  captchaText.value = `${Math.floor(1000 + Math.random() * 9000)}`;
};

const startCountdown = () => {
  countdown.value = 60;
  if (countdownTimer) clearInterval(countdownTimer);
  countdownTimer = setInterval(() => {
    countdown.value -= 1;
    if (countdown.value <= 0) {
      if (countdownTimer) clearInterval(countdownTimer);
      countdownTimer = null;
    }
  }, 1000);
};

const handleSendLoginCode = async () => {
  if (codeLoading.value || countdown.value > 0) return;
  if (!tenant_name.value.trim()) {
    errorMsg.value = "请输入租户名称";
    return;
  }
  if (!account.value.trim()) {
    errorMsg.value = "请输入用户名";
    return;
  }
  codeLoading.value = true;
  errorMsg.value = "";
  try {
    const res = await sendLoginCode({
      tenant_name: tenant_name.value,
      account: account.value,
      channel: verifyType.value,
    });
    if (res && res.code === 200) {
      ElMessage.success("验证码已发送");
      startCountdown();
    } else {
      errorMsg.value = res?.msg || "发送验证码失败";
    }
  } catch (err: any) {
    errorMsg.value = err?.response?.data?.msg || err?.message || "发送验证码失败";
  } finally {
    codeLoading.value = false;
  }
};

  // --- 初始化极验4.0 ---
const startGeetest4 = async () => {
  showCaptchaContainer.value = true;
  await nextTick();

  if (!captchaContainer.value) {
    errorMsg.value = "验证码容器未找到";
    loading.value = false;
    // 验证码容器未找到，跳过验证直接登录
    return await performLoginRequest();
  }

  // 获取极验4.0配置
  const res4 = await getGeetest4Infos();
  if (!res4 || res4.code !== 200 || !res4.data || !res4.data.captcha_id) {
    errorMsg.value = "获取极验配置失败，跳过验证直接登录";
    showCaptchaContainer.value = false;
    // 配置获取失败，跳过验证直接登录
    return await performLoginRequest();
  }

  const config = res4.data;

  // @ts-ignore
  if (!window.initGeetest4) {
    errorMsg.value = "极验4.0 SDK 加载失败，跳过验证直接登录";
    loading.value = false;
    showCaptchaContainer.value = false;
    return await performLoginRequest();
  }

  // @ts-ignore
  window.initGeetest4({
    captchaId: config.captcha_id,
    product: 'bind',
    language: 'zh-CN',
    container: captchaContainer.value
  }, (instance: any) => {
    captchaInstance.value = instance;

    // 验证成功回调
    instance.onSuccess(async () => {
      const result = instance.getValidate();
      // 将验证结果添加到登录参数中
      const loginRes = await login({
        tenant_name: tenant_name.value,
        account: account.value,
        password: password.value,
        captcha_id: result?.captcha_id || "",
        lot_number: result?.lot_number || "",
        pass_token: result?.pass_token || "",
        gen_time: result?.gen_time || "",
        captcha_output: result?.captcha_output || ""
      });

      if (loginRes && loginRes.code === 200) {
        if (rememberMe.value) {
          localStorage.setItem("loginAccount", account.value);
          localStorage.setItem("loginTenantName", tenant_name.value);
          localStorage.setItem("loginPassword", password.value);
          localStorage.setItem("loginRememberMe", "true");
        } else {
          localStorage.removeItem("loginAccount");
          localStorage.removeItem("loginTenantName");
          localStorage.removeItem("loginPassword");
          localStorage.setItem("loginRememberMe", "false");
        }

        authStore.setLoginInfo(loginRes.data);
        const { useTabsStore } = await import("@/stores");
        const tabsStore = useTabsStore();
        tabsStore.resetTabs();
        router.push({ path: "/home" });
        ElMessage.success("登录成功！");
      } else {
        errorMsg.value = loginRes.msg || "登录失败";
      }
      loading.value = false;
      cleanCaptchaInstance();
    });

    // 验证失败回调
    instance.onFail(() => {
      errorMsg.value = "验证码验证失败，请重试";
      loading.value = false;
    });

    // 错误回调 - 网络错误时跳过验证直接登录
    instance.onError((err: any) => {
      errorMsg.value = "验证码加载失败，跳过验证直接登录";
      loading.value = false;
      cleanCaptchaInstance();
      // 跳过验证直接登录
      performLoginRequest();
    });

    // 显示验证码
    instance.showCaptcha();
  });
  return true;
};

/**
 * 登录请求
 */
const handleLogin = async () => {
  // 清空错误提示
  errorMsg.value = "";

  // 表单验证
  if (!tenant_name.value.trim()) {
    errorMsg.value = "请输入租户名称";
    return;
  }
  if (!account.value.trim()) {
    errorMsg.value = "请输入用户名";
    return;
  }
  if (!password.value.trim()) {
    errorMsg.value = "请输入密码";
    return;
  }
  if (loading.value) return;
  loading.value = true;

  try {
    const verifyRes = await getOpenVerify();
    let openVerify = "0";
    let verifyTypeVal = "captcha";
    if (verifyRes && verifyRes.code === 200 && Array.isArray(verifyRes.data)) {
      verifyRes.data.forEach((item: any) => {
        if (item.label === "openVerify") {
          openVerify = item.value || "0";
        }
        if (item.label === "verifyType") {
          verifyTypeVal = item.value || "captcha";
        }
      });
    }
    openVerifyEnabled.value = openVerify === "1";
    verifyType.value = verifyTypeVal as any;
    if (openVerifyEnabled.value && verifyType.value === "captcha" && !captchaText.value) {
      generateCaptcha();
    }

    if (openVerifyEnabled.value && verifyType.value === "captcha") {
      if (!captchaInput.value.trim()) {
        errorMsg.value = "请输入验证码";
        return;
      }
      if (captchaInput.value.trim() !== captchaText.value) {
        errorMsg.value = "验证码错误";
        generateCaptcha();
        return;
      }
    }
    if (openVerifyEnabled.value && (verifyType.value === "sms" || verifyType.value === "email") && !smsCode.value.trim()) {
      errorMsg.value = "请输入验证码";
      return;
    }

    if (openVerifyEnabled.value && verifyType.value === "geetest") {
      await startGeetest4();
    } else {
      await performLoginRequest();
    }
  } catch (err: any) {
    errorMsg.value = err?.response?.data?.msg || err?.message || "登录失败，请重试";
  } finally {
    loading.value = false;
  }
};

// 记住我逻辑优化
const handleRememberMeChange = async () => {
  if (rememberMe.value) {
    try {
      await ElMessageBox.confirm(
        '请确认电脑环境是可信的，登录成功后会自动记住密码。',
        '安全提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        }
      );
    } catch {
      rememberMe.value = false;
    }
  }
};

// 页面加载处理
onMounted(async () => {
  // 从本地存储恢复表单
  const savedRemember = localStorage.getItem("loginRememberMe");
  if (savedRemember === "true") {
    tenant_name.value = localStorage.getItem("loginTenantName") || "";
    account.value = localStorage.getItem("loginAccount") || "";
    password.value = localStorage.getItem("loginPassword") || "";
    rememberMe.value = true;
  }

  // 拉取登录验证配置，决定是否展示验证码模块
  await initVerifyConfig();
});

onUnmounted(() => {
  if (countdownTimer) clearInterval(countdownTimer);
});

const goRegister = () => router.push("/register");
const goForget = () => router.push("/forget");
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(120deg, #e6f0ff 0%, #f5fcff 55%, #eaf6ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.login-card {
  display: flex;
  min-width: 770px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 22px;
  box-shadow:
    0 8px 36px 0 rgba(73, 150, 255, 0.14),
    0 1.5px 4px 0 rgba(30, 42, 79, 0.05);
  overflow: hidden;
  z-index: 10;
}

.login-side {
  width: 320px;
  background: #52a8ff;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 44px 16px 32px 16px;
  box-shadow: 4px 0 32px 0 rgba(189, 231, 255, 0.13) inset;
  position: relative;
}

.brand {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 42px;
  user-select: none;
}

.brand-title {
  font-size: 25px;
  letter-spacing: 2px;
  font-weight: 700;
  color: #fff;
}

.illus {
  margin-top: 30px;
  user-select: none;
  opacity: 0.95;
}

/* 版权信息样式 */
.copyright {
  width: 100%;
  text-align: center;
  font-size: 13px;
  color: #fff;
  margin-top: auto;
  margin-bottom: 2px;
  letter-spacing: 0.2px;
  padding-top: 25px;
  user-select: none;
}

.login-panel {
  flex: 1;
  padding: 52px 54px 48px 54px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: transparent;
  min-width: 320px;
}

.login-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #2560a9;
  text-align: left;
  letter-spacing: 1px;
}

.login-desc {
  color: #7391c4;
  font-size: 15px;
  margin-bottom: 28px;
  letter-spacing: 0.2px;
}

.mode-switch {
  display: flex;
  gap: 8px;
  margin-bottom: 14px;
}

.mode-btn {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid #d6e6fa;
  border-radius: 7px;
  background: #f7fbfe;
  color: #407ad6;
  cursor: pointer;
}

.mode-btn.active {
  background: #e8f3ff;
  border-color: #7cb8ff;
  color: #1d63c2;
  font-weight: 600;
}

.form-group {
  margin-bottom: 15px;
  position: relative;
}

/* 输入框前置图标样式 */
.icon-input-group {
  display: flex;
  align-items: center;
  position: relative;
}

.input-with-icon {
  padding-left: 36px !important;
}

.input-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  z-index: 2;
  width: 20px;
  height: 20px;
  color: #4da1ff;
  opacity: 0.95;
}

.visible-btn {
  position: absolute;
  right: 11px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  z-index: 2;
  padding: 2px 2px;
  display: flex;
  align-items: center;
  opacity: 0.82;
  user-select: none;
}

.visible-btn:hover {
  opacity: 1;
}

/* 防止密码输入框可见按钮和输入内容重叠 */
.icon-input-group .input-with-icon {
  padding-right: 34px;
}

.input {
  width: 100%;
  padding: 12px 14px;
  font-size: 16px;
  border: 1.3px solid #d6e6fa;
  border-radius: 7px;
  box-sizing: border-box;
  transition:
    border 0.2s,
    box-shadow 0.2s;
  background: #f7fbfe;
  margin-bottom: 3px;
}

.input:focus {
  border-color: #4da1ff;
  outline: none;
  box-shadow: 0 0 0 2px #e3f2ffb1;
}

.code-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.code-input {
  margin-bottom: 0;
  flex: 1;
}

.code-btn {
  width: 120px;
  height: 44px;
  border: 1.3px solid #d6e6fa;
  border-radius: 7px;
  background: #fff;
  color: #3a78ca;
  cursor: pointer;
}

.code-btn:disabled {
  opacity: 0.65;
  cursor: not-allowed;
}

/* 极验验证码容器样式 */
.geetest-container {
  margin: 10px 0;
  padding: 5px 0;
  width: 100%;
  min-height: 60px;
  border-radius: 7px;
  background: #f7fbfe;
  border: 1.3px solid #d6e6fa;
}

/* 记住我单选框 */
.remember-me-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0;
  margin-top: 3px;
  min-height: 32px;
  font-size: 15px;
  color: #6d8eb8;
  user-select: none;
}

.remember-me-label {
  display: flex;
  align-items: center;
  gap: 7px;
  cursor: pointer;
}

.remember-me-checkbox {
  width: 16px;
  height: 16px;
  accent-color: #4da1ff;
  margin-right: 2px;
}

.login-btn {
  width: 100%;
  padding: 13px 0;
  font-size: 17px;
  background: linear-gradient(90deg, #3494e6 0%, #52a8ff 100%);
  color: #fff;
  border: none;
  border-radius: 7px;
  box-shadow: 0 2px 12px 0 rgba(81, 173, 255, 0.13);
  font-weight: 600;
  letter-spacing: 1px;
  margin-top: 15px;
  cursor: pointer;
  transition:
    background 0.2s,
    transform 0.13s;
}

.login-btn:active {
  transform: scale(0.98);
}

.login-btn:disabled {
  background: #b6dafc;
  cursor: not-allowed;
}

.error-msg {
  color: #e4574a;
  background: #fdeceb;
  text-align: center;
  border-radius: 4px;
  padding: 7px 4px;
  margin-bottom: 2px;
  font-size: 14.5px;
  letter-spacing: 0.3px;
  animation: shake 0.28s;
}

@keyframes shake {
  0% {
    transform: translateX(0);
  }

  20% {
    transform: translateX(-6px);
  }

  40% {
    transform: translateX(6px);
  }

  60% {
    transform: translateX(-2px);
  }

  80% {
    transform: translateX(2px);
  }

  100% {
    transform: translateX(0);
  }
}

/* 注册、忘记密码链接 */
.action-links {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 14.1px;
  color: #6592c3;
  margin-bottom: 0;
  min-height: 22px;
}

.action-links a {
  cursor: pointer;
  color: #407ad6;
  text-decoration: none;
  transition: color 0.16s;
}

.action-links a:hover {
  color: #165eec;
  text-decoration: underline;
}

.action-links .divider {
  color: #bbd3ee;
  margin: 0 6px;
  font-size: 13px;
}

.register-link {
  margin-right: 0px;
}

.forget-link {
  margin-left: 0px;
}

/* 渐隐提示 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.24s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 炫彩光斑装饰 */
.login-light {
  position: absolute;
  border-radius: 50%;
  pointer-events: none;
  filter: blur(45px);
  opacity: 0.4;
  z-index: 1;
}

.light1 {
  width: 340px;
  height: 340px;
  top: -90px;
  left: -60px;
  background: radial-gradient(circle at 60% 50%, #55b7f988 0%, #e1e8fa11 95%);
}

.light2 {
  width: 260px;
  height: 260px;
  right: -60px;
  bottom: -90px;
  background: radial-gradient(circle at 55% 60%, #f3e7ff99 0%, #daf3ff10 100%);
}

@media (max-width: 940px) {
  .login-card {
    min-width: 330px;
    flex-direction: column;
  }

  .login-side {
    width: 100%;
    min-width: 0;
    border-radius: 0 0 18px 18px;
  }

  .login-panel {
    padding: 30px 22px 34px 22px;
    min-width: 0;
  }

  .copyright {
    padding-top: 13px;
  }
}
</style>