<template>
  <div class="login-layout">
    <!-- 左侧背景区域：仅显示背景图 -->
    <div class="login-left-bg"></div>

    <!-- 右侧登录区域 -->
    <div class="right-login-area-full">


      <!-- 登录卡片 -->
      <div class="login-card">
        <!-- 人脸识别界面 -->
        <div v-if="needFaceAuth" class="face-auth-container">
          <div class="login-header">
            <div class="logo-icon">📱</div>
            <h2 class="login-title">人脸识别验证</h2>
          </div>

          <div class="qr-container">
            <div v-if="!qrCodeUrl" class="loading-qr">
              <div class="spinner"></div>
              <span>生成二维码中...</span>
            </div>
            <img v-else :src="qrCodeUrl" class="qr-image" alt="人脸识别二维码" />
          </div>

          <p class="face-auth-tip">请使用移动端扫描二维码完成人脸识别</p>
          <p v-if="faceAuthFailed" class="error-text">人脸识别失败，请重试</p>

          <button v-if="!faceAuthChecking" class="back-btn" @click="resetLogin">返回登录</button>
        </div>

        <!-- 双因子验证界面 -->
        <div v-else-if="needTwoFactor" class="two-factor-container">
          <div class="login-header">
            <div class="logo-icon">📧</div>
            <h2 class="login-title">邮箱验证</h2>
            <p class="login-subtitle">验证码已发送至 {{ maskedEmail }}</p>
          </div>

          <div class="code-input-container">
            <div class="code-input-group">
              <span class="input-icon">🔢</span>
              <input
                v-model="twoFactorCode"
                type="text"
                class="code-input"
                placeholder="请输入6位验证码"
                maxlength="6"
                autocomplete="off"
                @keyup.enter="submitTwoFactorCode"
                @input="onCodeInput"
              />
            </div>
            <p v-if="twoFactorError" class="error-text">{{ twoFactorError }}</p>
          </div>

          <button
            type="button"
            class="primary-btn"
            :class="{ 'loading-btn': twoFactorLoading }"
            :disabled="twoFactorLoading || twoFactorCode.length !== 6"
            @click="submitTwoFactorCode"
          >
            <span v-if="!twoFactorLoading">验证并登录</span>
            <span v-else>验证中...</span>
          </button>

          <div class="two-factor-actions">
            <button v-if="resendCountdown === 0" class="resend-btn" :disabled="resendLoading" @click="resendTwoFactorCode">
              <span v-if="!resendLoading">重新发送验证码</span>
              <span v-else>发送中...</span>
            </button>
            <span v-else class="resend-countdown">{{ resendCountdown }}秒后可重发</span>
            <button class="back-btn" @click="resetLogin">返回登录</button>
          </div>
        </div>

        <!-- 登录表单 -->
        <div v-else class="login-form">
          <div class="login-header">
            <h2 class="login-title">共享服务中心</h2>
          </div>

          <el-form ref="loginRef" :model="loginForm" :rules="loginRules" @submit.prevent="handleLogin" hide-required-asterisk>
            <div class="form-group">
              <span class="input-icon">👤</span>
              <el-form-item prop="username">
                <input v-model="loginForm.username" type="text" class="form-input" placeholder="请输入账号" autocomplete="off" />
              </el-form-item>
            </div>

            <div class="form-group">
              <span class="input-icon">🔒</span>
              <el-form-item prop="password">
                <input
                  v-model="loginForm.password"
                  type="password"
                  class="form-input"
                  placeholder="请输入密码"
                  autocomplete="off"
                  @keyup.enter="handleLogin"
                />
              </el-form-item>
            </div>

            <div v-if="captchaEnabled" class="form-group captcha-group">
              <div class="captcha-input">
                <span class="input-icon">🛡️</span>
                <el-form-item prop="code">
                  <input
                    v-model="loginForm.code"
                    type="text"
                    class="form-input"
                    placeholder="验证码"
                    autocomplete="off"
                    @keyup.enter="handleLogin"
                  />
                </el-form-item>
              </div>
              <img :src="codeUrl" @click="getCode" class="captcha-image" title="点击刷新验证码" />
            </div>

            <button
              type="button"
              class="primary-btn login-btn"
              :class="{ 'loading-btn': loading }"
              :disabled="loading"
              @click="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </button>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { checkFaceAuthStatus, getFaceAuthQrCodeBase64 } from '@/api/face-auth';

const ENABLE_THEME_RESET = true;

const userStore = useUserStore();
const router = useRouter();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
  faceAuthVerified: false,
  faceAuthQrCodeId: '',
  twoFactorCode: '',
  twoFactorId: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const codeUrl = ref('');
const loading = ref(false);
const captchaEnabled = ref(true);
const tenantEnabled = ref(true);

// 人脸识别相关
const needFaceAuth = ref(false);
const qrCodeUrl = ref('');
const qrCodeId = ref('');
const faceAuthChecking = ref(false);
const faceAuthTimer = ref<ReturnType<typeof setInterval> | null>(null);
const faceAuthFailed = ref(false);

// 双因子验证相关
const needTwoFactor = ref(false);
const twoFactorCode = ref('');
const twoFactorId = ref('');
const twoFactorLoading = ref(false);
const twoFactorError = ref('');
const maskedEmail = ref('');
const resendCountdown = ref(0);
const resendTimer = ref<ReturnType<typeof setInterval> | null>(null);
const resendLoading = ref(false);

const register = ref(false);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
const tenantList = ref<TenantVO[]>([]);

// 获取人脸识别二维码Base64
const getFaceAuthQrCode = async (qrCodeId: string) => {
  try {
    const [err, res] = await to(getFaceAuthQrCodeBase64(qrCodeId));
    if (err) {
      console.error('获取二维码失败:', err);
      ElMessage.error('获取人脸识别二维码失败，请重试');
      return;
    }
    if (res.code === 200) {
      qrCodeUrl.value = 'data:image/png;base64,' + res.data.img;
    } else {
      ElMessage.error('获取人脸识别二维码失败');
      console.error('获取二维码响应错误:', res.data);
    }
  } catch (error) {
    console.error('获取二维码失败:', error);
    ElMessage.error('获取人脸识别二维码失败，请重试');
  }
};

// 邮箱脱敏显示
const maskEmail = (email: string): string => {
  if (!email) return '';
  const [localPart, domain] = email.split('@');
  if (localPart.length <= 2) {
    return `${localPart}***@${domain}`;
  }
  const maskedLocal = localPart.charAt(0) + '*'.repeat(Math.max(0, localPart.length - 2)) + localPart.charAt(localPart.length - 1);
  return `${maskedLocal}@${domain}`;
};

// 验证码输入处理（只允许数字）
const onCodeInput = (event: Event) => {
  const target = event.target as HTMLInputElement;
  target.value = target.value.replace(/\D/g, '');
  twoFactorCode.value = target.value;
  if (twoFactorError.value) {
    twoFactorError.value = '';
  }
};

// 提交双因子验证码
const submitTwoFactorCode = async () => {
  if (twoFactorCode.value.length !== 6) {
    twoFactorError.value = '请输入6位验证码';
    return;
  }

  twoFactorLoading.value = true;
  twoFactorError.value = '';

  try {
    loginForm.value.twoFactorCode = twoFactorCode.value;
    loginForm.value.twoFactorId = twoFactorId.value;

    const [err, res] = await to(userStore.login(loginForm.value));
    if (err) {
      if (err.message.includes('验证码')) {
        twoFactorError.value = '验证码错误或已过期，请重新输入';
      } else {
        twoFactorError.value = err.message || '验证失败，请重试';
      }
      return;
    }

    const result = res.data;
    if (result.loginStatus === 0) {
      ElMessage.success('登录成功');
      await router.push(redirect.value || '/');
    } else {
      twoFactorError.value = result.message || '验证失败，请重试';
    }
  } catch (error) {
    console.error('双因子验证失败:', error);
    twoFactorError.value = '验证失败，请重试';
  } finally {
    twoFactorLoading.value = false;
  }
};

// 重发验证码
const resendTwoFactorCode = async () => {
  resendLoading.value = true;
  try {
    const tempLoginForm = { ...loginForm.value };
    delete tempLoginForm.twoFactorCode;
    delete tempLoginForm.twoFactorId;

    const [err, res] = await to(userStore.login(tempLoginForm));
    if (!err && res.data.loginStatus === 2) {
      twoFactorId.value = res.data.twoFactorId || '';
      twoFactorCode.value = '';
      twoFactorError.value = '';
      ElMessage.success('验证码已重新发送');
      startResendCountdown();
    } else {
      ElMessage.error('重发验证码失败，请重试');
    }
  } catch (error) {
    console.error('重发验证码失败:', error);
    ElMessage.error('重发验证码失败，请重试');
  } finally {
    resendLoading.value = false;
  }
};

// 开始重发倒计时
const startResendCountdown = () => {
  resendCountdown.value = 60;
  if (resendTimer.value) {
    clearInterval(resendTimer.value);
  }
  resendTimer.value = setInterval(() => {
    resendCountdown.value--;
    if (resendCountdown.value <= 0) {
      clearInterval(resendTimer.value!);
      resendTimer.value = null;
    }
  }, 1000);
};

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;

      loginForm.value.twoFactorCode = '';
      loginForm.value.twoFactorId = '';

      const [err, res] = await to(userStore.login(loginForm.value));
      if (err) {
        if (captchaEnabled.value) {
          await getCode();
        }
        loading.value = false;
        return;
      }
      const result = res.data;
      if (result.loginStatus === 0) {
        await router.push(redirect.value || '/');
      } else if (result.loginStatus === 1) {
        needFaceAuth.value = true;
        qrCodeId.value = result.faceAuthQrCodeId || '';
        await getFaceAuthQrCode(qrCodeId.value);
        loginForm.value.faceAuthQrCodeId = qrCodeId.value;
        startFaceAuthCheck();
        ElMessage.info(result.message || '请完成人脸识别');
      } else if (result.loginStatus === 2) {
        needTwoFactor.value = true;
        twoFactorId.value = result.twoFactorId || '';
        maskedEmail.value = maskEmail(result.userEmail || '');
        twoFactorCode.value = '';
        twoFactorError.value = '';
        loginForm.value.twoFactorId = twoFactorId.value;
        startResendCountdown();
        ElMessage.info(result.message || '请输入邮箱验证码');
      } else {
        ElMessage.warning(result.message || '登录状态异常');
      }
      loading.value = false;
    } else {
      console.log('表单验证未通过:', fields);
    }
  });
};

// 开始检查人脸识别状态
const startFaceAuthCheck = () => {
  faceAuthChecking.value = true;
  faceAuthFailed.value = false;

  if (faceAuthTimer.value) {
    clearInterval(faceAuthTimer.value);
  }

  faceAuthTimer.value = setInterval(async () => {
    const [checkErr, checkRes] = await to(checkFaceAuthStatus(qrCodeId.value));
    if (checkErr) {
      console.error('检查人脸识别状态失败:', checkErr);
      return;
    }
    if (checkRes.code === HttpStatus.SUCCESS && checkRes.data) {
      stopFaceAuthCheck();
      ElMessage.success('人脸识别成功');
      loginForm.value.faceAuthVerified = true;
      const [loginErr, loginRes] = await to(userStore.login(loginForm.value));
      if (loginErr) {
        console.error('人脸识别后登录失败:', loginErr);
        ElMessage.error('人脸识别成功，但登录失败，请重试');
        resetLogin();
        return;
      }
      const loginResult = loginRes.data;
      if (loginResult.loginStatus === 0) {
        await router.push(redirect.value || '/');
      } else {
        ElMessage.warning(loginResult.message || '登录状态异常');
        resetLogin();
      }
    }
  }, 2000);

  setTimeout(() => {
    if (faceAuthChecking.value) {
      stopFaceAuthCheck();
      faceAuthFailed.value = true;
      ElMessage.error('人脸识别超时，请重试');
    }
  }, 120000);
};

// 停止检查人脸识别状态
const stopFaceAuthCheck = () => {
  faceAuthChecking.value = false;
  if (faceAuthTimer.value) {
    clearInterval(faceAuthTimer.value);
    faceAuthTimer.value = null;
  }
};

// 重置登录状态
const resetLogin = () => {
  stopFaceAuthCheck();
  needFaceAuth.value = false;
  faceAuthFailed.value = false;
  loginForm.value.faceAuthVerified = false;
  loginForm.value.faceAuthQrCodeId = '';
  qrCodeUrl.value = '';

  needTwoFactor.value = false;
  twoFactorCode.value = '';
  twoFactorId.value = '';
  twoFactorError.value = '';
  maskedEmail.value = '';
  loginForm.value.twoFactorCode = '';
  loginForm.value.twoFactorId = '';

  if (resendTimer.value) {
    clearInterval(resendTimer.value);
    resendTimer.value = null;
  }
  resendCountdown.value = 0;

  if (captchaEnabled.value) {
    getCode();
  }
};

// 获取验证码
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = sessionStorage.getItem('tenantId');
  const username = sessionStorage.getItem('username');
  const password = sessionStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');

  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe),
    faceAuthVerified: false,
    faceAuthQrCodeId: '',
    twoFactorCode: '',
    twoFactorId: ''
  } as LoginData;
};

// 获取租户列表
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

// 监听租户选择变化
watch(
  () => loginForm.value.tenantId,
  () => {
    sessionStorage.setItem('tenantId', String(loginForm.value.tenantId));
  }
);

// 组件销毁时清除定时器
onBeforeUnmount(() => {
  stopFaceAuthCheck();
  if (resendTimer.value) {
    clearInterval(resendTimer.value);
  }
});

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

/* ========== 整体布局 ========== */
.login-layout {
  display: flex;
  height: 100vh;
  width: 100vw;
  position: relative;
  overflow: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 左侧背景区域 */
.login-left-bg {
  flex: 1;
  min-width: 0;
  background: url('@/assets/images/login-background.png') center center / cover no-repeat;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.15);
    pointer-events: none;
  }
}

/* ========== 右侧登录区域 ========== */
.right-login-area-full {
  width: 500px;
  min-width: 500px;
  max-width: 600px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  background: #ffffff;
  position: relative;
  z-index: 10;
  box-shadow: -4px 0 30px rgba(0, 0, 0, 0.12);
}

/* Logo 样式 */
.header-logo {
  position: absolute;
  top: 30px;
  left: 40px;
  z-index: 100;
}

.logo-image {
  height: 52px;
  width: auto;
  display: block;
}

/* 登录卡片 */
.login-card {
  width: 100%;
  max-width: 480px;
  margin-top: 80px;
}

/* ========== 通用样式 ========== */
.login-header {
  text-align: center;
  margin-bottom: 50px;
}

.logo-icon {
  width: 64px;
  height: 64px;
  background: linear-gradient(135deg, #466380, #335290);
  border-radius: 18px;
  margin: 0 auto 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32px;
  box-shadow: 0 10px 30px rgba(0, 102, 92, 0.25);
}

.login-title {
  font-size: 28px;
  color: #1a202c;
  font-weight: 700;
  margin-bottom: 10px;
  letter-spacing: 1px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.login-subtitle {
  color: #64748b;
  font-size: 16px;
  font-weight: 400;
}

/* ========== 表单样式 ========== */
.form-group {
  margin-bottom: 28px;
  position: relative;
}

.form-input {
  width: 100%;
  padding: 18px 22px 18px 56px;
  border: 1px solid #e5e7eb;
  border-radius: 14px;
  font-size: 17px;
  background: #ffffff;
  transition: all 0.3s ease;
  outline: none;
}

.form-input:focus {
  border-color: #2774c1;
  box-shadow: 0 0 0 4px rgba(0, 102, 92, 0.1);
  transform: translateY(-1px);
}

.input-icon {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: #94a3b8;
  font-size: 22px;
  z-index: 1;
}

/* 验证码 */
.captcha-group {
  display: flex;
  gap: 12px; /* 控制验证码输入框和验证码图片之间的间距 */
  align-items: center;
}

.captcha-input {
  flex: 1;
  position: relative;
  .form-input {
    width: 100%; /* 确保验证码输入框占据整个容器的宽度 */
    padding: 18px 22px 18px 56px;
  }
}

.captcha-image {
  width: 130px; // 增加验证码图片的宽度
  height: auto; // 根据宽度自动调整高度
  border-radius: 10px;
  cursor: pointer;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
  background: #ffffff;
}

.captcha-image:hover {
  border-color: #18406e;
  transform: scale(1.05);
  box-shadow: 0 6px 20px rgba(0, 102, 92, 0.2);
}

/* 按钮 */
.primary-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #032161, #0220b1);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 17px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 6px 20px rgba(0, 102, 92, 0.25);
  letter-spacing: 1px;
}

.primary-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.6s;
}

.primary-btn:hover::before {
  left: 100%;
}

.primary-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 10px 30px rgba(0, 102, 92, 0.35);
  background: linear-gradient(135deg, #003877, #005cb8);
}

.primary-btn:active:not(:disabled) {
  transform: translateY(0);
}

.primary-btn:disabled,
.loading-btn {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.login-btn {
  margin-top: 12px;
}

/* ========== 人脸识别 ========== */
.face-auth-container {
  text-align: center;
}

.qr-container {
  width: 200px;
  height: 200px;
  margin: 32px auto;
  border-radius: 16px;
  border: 2px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.qr-image {
  max-width: 180px;
  max-height: 180px;
  border-radius: 8px;
}

.loading-qr {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #64748b;
}

.spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #e5e7eb;
  border-top: 4px solid #003f66;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.face-auth-tip {
  color: #64748b;
  font-size: 14px;
  margin-bottom: 20px;
}

/* ========== 双因子验证 ========== */
.two-factor-container {
  text-align: center;
}

.code-input-container {
  margin-bottom: 28px;
}

.code-input-group {
  position: relative;
  margin-bottom: 8px;
}

.code-input {
  width: 100%;
  padding: 16px 20px 16px 52px;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  font-size: 22px;
  font-weight: 600;
  text-align: center;
  letter-spacing: 6px;
  background: #ffffff;
  transition: all 0.3s ease;
  outline: none;
}

.code-input:focus {
  border-color: #003c66;
  box-shadow: 0 0 0 4px rgba(0, 102, 92, 0.1);
  transform: translateY(-1px);
}

/* 操作按钮 */
.two-factor-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 20px;
}

.resend-btn,
.back-btn {
  background: white;
  border: 2px solid #005a66;
  color: #005366;
  padding: 12px 24px;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 15px;
}

.resend-btn:hover:not(:disabled),
.back-btn:hover {
  background: #003f66;
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(0, 102, 92, 0.25);
}

.resend-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.resend-countdown {
  color: #64748b;
  font-size: 14px;
  padding: 12px;
}

.error-text {
  color: #ef4444;
  font-size: 14px;
  margin: 8px 0;
  text-align: left;
}

/* Element Plus 表单项 */
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 52px;
  font-size: 12px;
  color: #ef4444;
  margin-top: 4px;
}

/* ========== 响应式 ========== */
@media (max-width: 900px) {
  .right-login-area-full {
    width: 100%;
    min-width: 100%;
    padding: 40px 20px;
    box-shadow: none;
  }

  .login-left-bg {
    display: none;
  }

  .header-logo {
    top: 20px;
    left: 20px;
  }

  .login-card {
    max-width: 420px;
    margin-top: 60px;
  }
}

@media (max-width: 768px) {
  .header-logo {
    padding: 10px 18px;
  }

  .logo-image {
    height: 40px;
  }

  .login-title {
    font-size: 22px;
  }

  .primary-btn {
    font-size: 16px;
    padding: 14px;
  }
}
</style>
