<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import { login } from "@/api/login";
import { getAllMenus } from "@/api/menu";

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

const tenant = ref("默认租户");
const username = ref("");
const password = ref("");
const passwordVisible = ref(false);
const rememberMe = ref(false);
const loading = ref(false);
const errorMsg = ref("");

onMounted(() => {
  const savedUser = localStorage.getItem("loginUsername");
  const savedTenant = localStorage.getItem("tenant");
  const savedRemember = localStorage.getItem("loginRememberMe");

  if (savedRemember === "true" && savedTenant) {
    // 只有勾选“记住我”且有缓存租户时，才用缓存值
    tenant.value = savedTenant;
    username.value = savedUser;
    rememberMe.value = true;
  } else {
    // 没有缓存时，显示默认值（这里手动赋值确保生效）
    tenant.value = "默认租户";
  }
});

// 写入租户数据到缓存工具函数
function cacheTenant(tenantValue) {
  localStorage.setItem("tenant", tenantValue);
  sessionStorage.setItem("tenant", tenantValue);
}

const handleLogin = async () => {
  errorMsg.value = "";
  if (!tenant.value || !username.value || !password.value) {
    errorMsg.value = "请输入租户名称、用户名和密码";
    return;
  }
  // 验证租户名称不能为空
  const tenantName = tenant.value.trim();
  if (!tenantName) {
    errorMsg.value = "租户名称不能为空";
    return;
  }
  // 记住我本地存储
  if (rememberMe.value) {
    localStorage.setItem("loginUsername", username.value);
    localStorage.setItem("loginRememberMe", "true");
    localStorage.setItem("tenant", tenantName); // 仅勾选时存租户
  } else {
    localStorage.removeItem("loginUsername");
    localStorage.setItem("loginRememberMe", "false");
    localStorage.removeItem("tenant"); // 不勾选时清除租户缓存
  }
  // 写入租户到缓存（无论记住与否都要写，便于系统获取租户上下文）
  cacheTenant(tenantName);
  loading.value = true;
  try {
    const res = await login(username.value, password.value, tenantName);
    if (res && res.code === 0 && res.data) {
      authStore.setLoginInfo(res.data);
      // 登录如果有返回租户信息
      cacheTenant(tenantName);
      
      // 登录成功后重置 tabs store 为初始状态
      const { useTabsStore } = await import('@/stores');
      const tabsStore = useTabsStore();
      tabsStore.resetTabs();
      
      // 登录成功后缓存菜单
      try {
        const menuRes = await getAllMenus();
        if (menuRes && menuRes.data && menuRes.data.length > 0) {
          localStorage.setItem('menu_cache', JSON.stringify(menuRes.data));
        }
      } catch (menuError) {
        console.error('Failed to cache menu on login', menuError);
        // 菜单缓存失败不影响登录流程
      }
      
      router.push({ path: "/dashboard" });
    } else {
      errorMsg.value = res.message || "登录失败";
    }
  } catch (err) {
    errorMsg.value =
      err?.response?.data?.message || err?.message || "登录失败，请重试";
  } finally {
    loading.value = false;
  }
};

// 跳转注册、忘记密码页面
const goRegister = () => {
  router.push({ path: "/register" });
};
const goForget = () => {
  router.push({ path: "/forget" });
};
</script>

<template>
  <div class="login-bg">
    <div class="login-card">
      <div class="login-side">
        <div class="brand">
          <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
            <rect width="48" height="48" rx="18" fill="#eef8fc" />
            <circle cx="24" cy="24" r="14" fill="#52a8ff" opacity="0.15" />
            <circle cx="24" cy="24" r="9" fill="#3b7ddd" opacity="0.12" />
            <text
              x="24"
              y="30"
              text-anchor="middle"
              fill="#2d5fa7"
              font-size="16"
              font-family="Arial"
              font-weight="bold"
            >
              Mete
            </text>
          </svg>
          <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">© 2024 Mete 管理系统</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">
            <!-- 租户图标 -->
            <svg width="19" height="19" viewBox="0 0 20 20" fill="none">
              <rect
                x="2.2"
                y="4.2"
                width="15.6"
                height="11.6"
                rx="2"
                stroke="#4da1ff"
                stroke-width="1.4"
              />
              <rect x="6" y="8" width="8" height="4" rx="1" fill="#b9dbff" />
              <rect
                x="6.7"
                y="8.7"
                width="6.6"
                height="2.6"
                rx="0.7"
                fill="#fff"
              />
            </svg>
          </span>
          <input
            v-model="tenant"
            type="text"
            placeholder="租户名称"
            autocomplete="organization"
            class="input input-with-icon"
          />
        </div>
        <div class="form-group icon-input-group">
          <span class="input-icon">
            <!-- 用户图标 -->
            <svg width="19" height="19" viewBox="0 0 20 20" fill="none">
              <circle
                cx="10"
                cy="7"
                r="3.2"
                stroke="#4da1ff"
                stroke-width="1.4"
              />
              <ellipse
                cx="10"
                cy="14.1"
                rx="5.5"
                ry="3.3"
                stroke="#4da1ff"
                stroke-width="1.4"
              />
            </svg>
          </span>
          <input
            v-model="username"
            type="text"
            placeholder="用户名"
            autocomplete="username"
            class="input input-with-icon"
          />
        </div>
        <div class="form-group icon-input-group">
          <span class="input-icon">
            <!-- 密码图标 -->
            <svg width="19" height="19" viewBox="0 0 20 20" fill="none">
              <rect
                x="3"
                y="8"
                width="14"
                height="7"
                rx="2"
                stroke="#4da1ff"
                stroke-width="1.4"
              />
              <circle
                cx="10"
                cy="11.5"
                r="1.5"
                stroke="#4da1ff"
                stroke-width="1.2"
              />
              <rect
                x="7"
                y="5"
                width="6"
                height="3"
                rx="1.5"
                stroke="#4da1ff"
                stroke-width="1"
              />
            </svg>
          </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 ? '隐藏密码' : '显示密码'"
          >
            <svg
              v-if="passwordVisible"
              width="20"
              height="20"
              fill="none"
              viewBox="0 0 20 20"
            >
              <!-- 可见(eye)图标 -->
              <path
                d="M2 10c2-4 5-6 8-6s6 2 8 6c-2 4-5 6-8 6s-6-2-8-6z"
                stroke="#7bb7fa"
                stroke-width="1.4"
                fill="#eef5ff"
              />
              <circle
                cx="10"
                cy="10"
                r="2.5"
                stroke="#3794f7"
                stroke-width="1.4"
                fill="#fff"
              />
            </svg>
            <svg v-else width="20" height="20" fill="none" viewBox="0 0 20 20">
              <!-- 不可见(eye-off)图标 -->
              <path
                d="M2 10c2-4 5-6 8-6s6 2 8 6c-2 4-5 6-8 6s-6-2-8-6z"
                stroke="#b7c7db"
                stroke-width="1.3"
                fill="#f2f6fd"
              />
              <path d="M5 15L15 5" stroke="#b7c7db" stroke-width="1.2" />
            </svg>
          </span>
        </div>
        <div class="remember-me-row">
          <label class="remember-me-label">
            <input
              type="checkbox"
              v-model="rememberMe"
              class="remember-me-checkbox"
            />
            <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>

<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;
  /* text-shadow: 0 0 6px #d4ecfc; */
}
.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;
}
.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;
}

/* 记住我单选框 */
.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>
