<template>
  <div class="login-page">
    <!-- Animated background -->
    <div class="bg-gradient"></div>
    <div class="bg-orbs">
      <div class="orb orb-1"></div>
      <div class="orb orb-2"></div>
      <div class="orb orb-3"></div>
      <div class="orb orb-4"></div>
    </div>

    <!-- Login card -->
    <div class="login-card" :class="{ 'card-visible': cardVisible }">
      <!-- Header section -->
      <div class="card-header">
        <div class="logo-icon">
          <svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect width="40" height="40" rx="10" fill="url(#logo-grad-t)" />
            <path d="M13 16h14M13 20h14M13 24h10" stroke="white" stroke-width="2.2" stroke-linecap="round"/>
            <defs>
              <linearGradient id="logo-grad-t" x1="0" y1="0" x2="40" y2="40">
                <stop stop-color="#0ea5e9"/>
                <stop offset="1" stop-color="#6366f1"/>
              </linearGradient>
            </defs>
          </svg>
        </div>
        <h1 class="card-title">核销管理系统</h1>
        <p class="card-subtitle">租户登录</p>
      </div>

      <!-- Tenant code badge -->
      <div class="tenant-badge">
        <svg viewBox="0 0 20 20" fill="none" style="width:14px;height:14px;flex-shrink:0">
          <path d="M10 2L3 6v4c0 4.42 2.98 8.56 7 9.6 4.02-1.04 7-5.18 7-9.6V6l-7-4z" fill="currentColor" opacity="0.8"/>
        </svg>
        <span>租户编码：<strong>{{ tenantCode }}</strong></span>
      </div>

      <!-- Form -->
      <el-form :model="form" class="login-form" @keyup.enter="handleLogin">
        <div class="input-group">
          <label class="input-label">手机号</label>
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            size="large"
            :prefix-icon="PhoneIcon"
            clearable
          />
        </div>

        <div class="input-group">
          <label class="input-label">密码</label>
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="LockIcon"
            show-password
            clearable
          />
        </div>

        <div class="input-group">
          <label class="input-label">验证码</label>
          <div class="captcha-row">
            <el-input
              v-model="form.captchaCode"
              placeholder="请输入验证码"
              size="large"
              clearable
              class="captcha-input"
            />
            <img
              v-if="captchaImg"
              :src="captchaImg"
              class="captcha-img"
              @click="loadCaptcha"
              title="点击刷新验证码"
            />
            <div v-else class="captcha-placeholder" @click="loadCaptcha">加载中</div>
          </div>
        </div>

        <!-- 登录错误提示 -->
        <div v-if="lockCountdown > 0" class="login-alert login-alert-danger">
          <svg viewBox="0 0 20 20" fill="currentColor" style="width:16px;height:16px;flex-shrink:0">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
          </svg>
          <span>账号已锁定，请 {{ formatCountdown(lockCountdown) }} 后重试</span>
        </div>
        <div v-else-if="remainingAttempts !== null && remainingAttempts <= 3" class="login-alert login-alert-warning">
          <svg viewBox="0 0 20 20" fill="currentColor" style="width:16px;height:16px;flex-shrink:0">
            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.72-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
          </svg>
          <span>您还有 {{ remainingAttempts }} 次尝试机会</span>
        </div>

        <el-button
          type="primary"
          size="large"
          class="login-btn"
          :loading="loading"
          :disabled="lockCountdown > 0"
          @click="handleLogin"
        >
          <span v-if="!loading">登 录</span>
        </el-button>
      </el-form>

      <!-- Footer -->
      <div class="card-footer">
        <span class="footer-text">© {{ new Date().getFullYear() }} 核销管理系统</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, onMounted, onUnmounted, h } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { login, fetchCaptcha } from "../../api/modules";
import { useAuthStore } from "../../stores/auth";

// Simple icon render functions for prefix-icon
const PhoneIcon = h("i", { class: "login-icon" }, [
  h(
    "svg",
    {
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      "stroke-width": "2",
      "stroke-linecap": "round",
      "stroke-linejoin": "round",
      style: "width:16px;height:16px",
    },
    [
      h("path", {
        d: "M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z",
      }),
    ]
  ),
]);

const LockIcon = h("i", { class: "login-icon" }, [
  h(
    "svg",
    {
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      "stroke-width": "2",
      "stroke-linecap": "round",
      "stroke-linejoin": "round",
      style: "width:16px;height:16px",
    },
    [
      h("rect", { x: "3", y: "11", width: "18", height: "11", rx: "2", ry: "2" }),
      h("path", { d: "M7 11V7a5 5 0 0110 0v4" }),
    ]
  ),
]);

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const loading = ref(false);
const cardVisible = ref(false);
const tenantCode = computed(() => String(route.params.tenantCode || "").trim());

const captchaId = ref("");
const captchaImg = ref("");
const remainingAttempts = ref<number | null>(null);
const lockCountdown = ref(0);
let lockTimer: ReturnType<typeof setInterval> | null = null;

const form = reactive({
  phone: "13800000000",
  password: "123456",
  captchaCode: "",
});

const loadCaptcha = async () => {
  try {
    const resp = await fetchCaptcha();
    captchaId.value = resp?.data?.captchaId || "";
    captchaImg.value = resp?.data?.image || "";
  } catch {
    captchaImg.value = "";
  }
};

const formatCountdown = (seconds: number): string => {
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
};

const startLockCountdown = (seconds: number) => {
  if (lockTimer) clearInterval(lockTimer);
  lockCountdown.value = seconds;
  lockTimer = setInterval(() => {
    lockCountdown.value--;
    if (lockCountdown.value <= 0) {
      if (lockTimer) clearInterval(lockTimer);
      lockTimer = null;
      remainingAttempts.value = null;
    }
  }, 1000);
};

onMounted(() => {
  setTimeout(() => {
    cardVisible.value = true;
  }, 100);
  loadCaptcha();
});

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

const handleLogin = async () => {
  if (loading.value || lockCountdown.value > 0) return;
  if (!tenantCode.value) {
    ElMessage.error("租户编码不能为空");
    return;
  }
  loading.value = true;
  try {
    authStore.clearAuthStorage();
    const resp = await login({
      tenantCode: tenantCode.value,
      phone: form.phone,
      password: form.password,
      captchaId: captchaId.value,
      captchaCode: form.captchaCode,
    });
    remainingAttempts.value = null;
    authStore.saveAuthPayload({
      ...(resp?.data || {}),
      tenantCode: resp?.data?.tenantCode || tenantCode.value,
      scope: "TENANT",
    });
    ElMessage.success("登录成功");
    await router.push("/projects");
  } catch (e: any) {
    const data = e?.response?.data;
    const errors = data?.errors || {};
    // 处理锁定
    if (errors.lockRemainingSeconds) {
      startLockCountdown(Number(errors.lockRemainingSeconds));
    }
    // 处理剩余次数
    if (errors.remainingAttempts !== undefined) {
      remainingAttempts.value = Number(errors.remainingAttempts);
    }
    ElMessage.error(data?.message || e?.message || "登录失败");
    // 刷新验证码
    form.captchaCode = "";
    await loadCaptcha();
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* ===== Page layout ===== */
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  font-family: "Inter", "PingFang SC", "Microsoft YaHei", sans-serif;
}

/* ===== Animated gradient background ===== */
.bg-gradient {
  position: fixed;
  inset: 0;
  background: var(--wo-login-bg-tenant);
  z-index: 0;
}

/* ===== Floating orbs ===== */
.bg-orbs {
  position: fixed;
  inset: 0;
  z-index: 1;
  pointer-events: none;
}

.orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(80px);
  opacity: 0.45;
  animation: float 20s ease-in-out infinite;
}

.orb-1 {
  width: 380px;
  height: 380px;
  background: radial-gradient(circle, var(--wo-login-orb-tenant-1), transparent 70%);
  top: -80px;
  right: -60px;
  animation-delay: 0s;
}

.orb-2 {
  width: 320px;
  height: 320px;
  background: radial-gradient(circle, var(--wo-login-orb-tenant-2), transparent 70%);
  bottom: -100px;
  left: -80px;
  animation-delay: -5s;
  animation-duration: 25s;
}

.orb-3 {
  width: 220px;
  height: 220px;
  background: radial-gradient(circle, var(--wo-login-orb-tenant-3), transparent 70%);
  top: 40%;
  left: 15%;
  animation-delay: -10s;
  animation-duration: 18s;
}

.orb-4 {
  width: 180px;
  height: 180px;
  background: radial-gradient(circle, var(--wo-login-orb-tenant-4), transparent 70%);
  top: 20%;
  right: 25%;
  animation-delay: -15s;
  animation-duration: 22s;
}

@keyframes float {
  0%, 100% { transform: translate(0, 0) scale(1); }
  25% { transform: translate(30px, -40px) scale(1.05); }
  50% { transform: translate(-20px, 20px) scale(0.95); }
  75% { transform: translate(40px, 10px) scale(1.02); }
}

/* ===== Glass card ===== */
.login-card {
  position: relative;
  z-index: 10;
  width: 420px;
  padding: 48px 40px 36px;
  background: rgba(255, 255, 255, 0.07);
  backdrop-filter: blur(24px) saturate(1.4);
  -webkit-backdrop-filter: blur(24px) saturate(1.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    0 0 0 1px rgba(255, 255, 255, 0.05) inset;

  /* Entrance animation */
  opacity: 0;
  transform: translateY(30px) scale(0.96);
  transition: all 0.7s cubic-bezier(0.16, 1, 0.3, 1);
}

.login-card.card-visible {
  opacity: 1;
  transform: translateY(0) scale(1);
}

/* ===== Header ===== */
.card-header {
  text-align: center;
  margin-bottom: 28px;
}

.logo-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 56px;
  height: 56px;
  margin-bottom: 16px;
  animation: logo-pop 0.6s 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) both;
}

.logo-icon svg {
  width: 56px;
  height: 56px;
  filter: drop-shadow(0 4px 12px rgba(14, 165, 233, 0.4));
}

@keyframes logo-pop {
  from { transform: scale(0); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.card-title {
  font-size: 26px;
  font-weight: 700;
  color: #ffffff;
  margin: 0 0 6px 0;
  letter-spacing: 1px;
}

.card-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.55);
  margin: 0;
  font-weight: 400;
}

/* ===== Tenant badge ===== */
.tenant-badge {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  padding: 10px 14px;
  margin-bottom: 24px;
  background: rgba(14, 165, 233, 0.1);
  border: 1px solid rgba(14, 165, 233, 0.2);
  border-radius: 10px;
  color: rgba(255, 255, 255, 0.65);
  font-size: 13px;
}

.tenant-badge strong {
  color: #38bdf8;
  font-weight: 600;
}

/* ===== Form ===== */
.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.input-label {
  font-size: 13px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.7);
  padding-left: 2px;
}

/* Element Plus input overrides */
.login-form :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  box-shadow: none;
  transition: all 0.3s ease;
  padding: 4px 14px;
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: rgba(14, 165, 233, 0.4);
  background: rgba(255, 255, 255, 0.08);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: #0ea5e9;
  background: rgba(14, 165, 233, 0.08);
  box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.15);
}

.login-form :deep(.el-input__inner) {
  color: #ffffff;
  font-size: 15px;
}

.login-form :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.3);
}

.login-form :deep(.el-input__prefix) {
  color: rgba(255, 255, 255, 0.45);
}

.login-form :deep(.el-input__suffix) {
  color: rgba(255, 255, 255, 0.45);
}

.login-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* ===== Login button ===== */
.login-btn {
  width: 100%;
  height: 48px;
  margin-top: 8px;
  border-radius: 12px;
  border: none;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 4px;
  background: linear-gradient(135deg, #0ea5e9 0%, #6366f1 50%, #8b5cf6 100%);
  background-size: 200% 200%;
  animation: btn-shimmer 3s ease-in-out infinite;
  box-shadow: 0 4px 16px rgba(14, 165, 233, 0.35);
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 24px rgba(14, 165, 233, 0.5);
}

.login-btn:active {
  transform: translateY(0);
}

@keyframes btn-shimmer {
  0%, 100% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
}

/* ===== Footer ===== */
.card-footer {
  text-align: center;
  margin-top: 32px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.06);
}

.footer-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.3);
}

/* ===== Responsive ===== */
@media (max-width: 480px) {
  .login-card {
    width: calc(100vw - 32px);
    padding: 36px 24px 28px;
    border-radius: 16px;
  }
}

/* ===== Captcha ===== */
.captcha-row {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-img {
  height: 40px;
  border-radius: 8px;
  cursor: pointer;
  transition: opacity 0.2s;
  flex-shrink: 0;
}

.captcha-img:hover {
  opacity: 0.8;
}

.captcha-placeholder {
  width: 130px;
  height: 40px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.08);
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.35);
  font-size: 13px;
  cursor: pointer;
  flex-shrink: 0;
}

/* ===== Login alerts ===== */
.login-alert {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 14px;
  border-radius: 10px;
  font-size: 13px;
  animation: alert-in 0.3s ease;
}

.login-alert-warning {
  background: rgba(234, 179, 8, 0.15);
  border: 1px solid rgba(234, 179, 8, 0.3);
  color: #fbbf24;
}

.login-alert-danger {
  background: rgba(239, 68, 68, 0.15);
  border: 1px solid rgba(239, 68, 68, 0.3);
  color: #f87171;
}

@keyframes alert-in {
  from { opacity: 0; transform: translateY(-6px); }
  to { opacity: 1; transform: translateY(0); }
}

.login-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
