<script setup lang="ts">
/**
 * 登录页面
 *
 * 全屏品牌背景图 + 半透明表单的登录界面。
 * 支持账号密码登录，可选验证码。
 */
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getCaptcha } from '@/api/common'
import { showToast, Checkbox } from 'vant'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

// ── 系统信息 ──
const systemName = ref('舆图智慧水务')
const version = ref('v2.0.0')

// ── 表单状态 ──
const username = ref('')
const password = ref('')
const code = ref('')
const uuid = ref('')
const codeUrl = ref('')
const captchaEnabled = ref(false)
const loading = ref(false)
const savePsw = ref(true)
const isInputActive = ref(false)

// 恢复记住的账号密码
username.value = localStorage.getItem('yuto-user') || ''
password.value = localStorage.getItem('yuto-password') || ''

// ── 获取验证码 ──
async function fetchCaptcha(): Promise<void> {
  try {
    const res = await getCaptcha()
    captchaEnabled.value = res.captchaEnabled
    if (res.captchaEnabled) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      uuid.value = res.uuid
    }
  } catch {
    // 验证码获取失败，不阻塞登录流程
  }
}

// ── 提交登录 ──
async function onSubmit(): Promise<void> {
  if (!username.value) {
    showToast('请输入账号')
    return
  }
  if (!password.value) {
    showToast('请输入密码')
    return
  }
  if (captchaEnabled.value && !code.value) {
    showToast('请输入验证码')
    return
  }

  loading.value = true
  try {
    await userStore.login({
      username: username.value,
      password: password.value,
      code: captchaEnabled.value ? code.value : undefined,
      uuid: captchaEnabled.value ? uuid.value : undefined,
    })

    // 记住密码
    localStorage.setItem('yuto-user', username.value)
    if (savePsw.value) {
      localStorage.setItem('yuto-password', password.value)
    } else {
      localStorage.removeItem('yuto-password')
    }

    showToast('登录成功')
    router.replace('/home')
  } catch {
    // 错误已在拦截器中统一处理
  } finally {
    loading.value = false
    code.value = ''
    fetchCaptcha()
  }
}

// ── 隐私政策 ──
function onShowPrivacy(): void {
  router.push({ name: 'PrivacyPolicy' })
}

// ── 键盘弹起时隐藏底部 ──
function handleResize(): void {
  isInputActive.value = window.innerHeight < 500
}

onMounted(() => {
  // 从系统配置读取名称和版本
  if (appStore.globalConfig?.system) {
    systemName.value = appStore.globalConfig.system.name || systemName.value
    version.value = appStore.globalConfig.system.version || version.value
  }
  window.addEventListener('resize', handleResize)
  fetchCaptcha()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="login-page">
    <!-- 透明导航栏 (叠加在背景图之上) -->
    <van-nav-bar
      :title="''"
      :left-arrow="false"
      :border="false"
      :fixed="false"
      class="login-navbar"
    />

    <!-- 背景图 + 内容层 -->
    <div class="login-bg">
      <!-- Logo 区 -->
      <div class="login-logo">
        <div class="login-logo__avatar">
          <img
            src="@/assets/login_logo.png"
            alt="Logo"
            class="login-logo__img"
          />
        </div>
        <h1 class="login-logo__title">{{ systemName }}</h1>
      </div>

      <!-- 登录提示 -->
      <div class="login-subtitle">账号密码登录</div>

      <!-- 表单 -->
      <van-form @submit="onSubmit" class="login-form">
        <van-field
          v-model="username"
          placeholder="请输入账号"
          class="login-field"
          :rules="[{ required: true, message: '请输入账号' }]"
        />
        <van-field
          v-model="password"
          type="password"
          placeholder="请输入密码"
          class="login-field"
          :rules="[{ required: true, message: '请输入密码' }]"
        />
        <van-field
          v-if="captchaEnabled"
          v-model="code"
          placeholder="请输入验证码"
          class="login-field"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <template #right-icon>
            <img
              class="login-captcha-img"
              :src="codeUrl"
              alt="验证码"
              @click="fetchCaptcha"
            />
          </template>
        </van-field>

        <!-- 记住密码 -->
        <div class="login-save">
          <van-checkbox v-model="savePsw" icon-size="16px" checked-color="#1E74FF">
            记住密码
          </van-checkbox>
        </div>

        <!-- 登录按钮 -->
        <div class="login-btn-wrapper">
          <van-button
            v-if="!loading"
            block
            round
            native-type="submit"
            color="linear-gradient(135deg, $color-primary, $color-primary-light)"
            class="login-btn"
          >
            登 录
          </van-button>
          <van-button
            v-else
            block
            round
            loading
            loading-text="登录中..."
            color="linear-gradient(135deg, $color-primary, $color-primary-light)"
            class="login-btn"
          />
        </div>

        <!-- 隐私政策 -->
        <div class="login-tips">
          登录即代表同意<span class="login-tips__link" @click="onShowPrivacy">《隐私政策》</span>
        </div>
      </van-form>

      <!-- 底部技术支持 -->
      <div
        class="login-footer"
        :class="{ 'login-footer--hidden': isInputActive }"
      >
        <div class="login-footer__version">版本 {{ version }}</div>
        <div class="login-footer__support">技术支持：测绘股份 舆图科技</div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// ══════════════════════════════════════════════
// 登录页面 — 品牌背景 + 半透明表单
// ══════════════════════════════════════════════

.login-page {
  position: relative;
  width: 100%;
  min-height: 100vh;
  overflow: hidden;
}

// ── NavBar 透明叠加在背景上方 ──
.login-navbar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;

  :deep(.van-nav-bar) {
    background: transparent !important;
  }

  :deep(.van-nav-bar__content) {
    background: transparent !important;
  }

  :deep(.van-nav-bar__title) {
    color: #fff;
  }

  // 隐藏分割线
  :deep(.van-hairline--bottom::after) {
    display: none;
  }
}

// ── 背景层 (全屏品牌背景图) ──
.login-bg {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(180deg, #E8F0FE 0%, #F4F7F8 40%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: calc(20px + env(safe-area-inset-bottom));
}

// ── Logo 区 ──
.login-logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 114px;

  &__avatar {
    width: 78px;
    height: 78px;
    border-radius: 50%;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &__img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  &__title {
    font-size: 22px;
    font-weight: 700;
    color: #1A3973;
    margin-top: 12px;
    letter-spacing: 2px;
  }
}

// ── 登录子标题 ──
.login-subtitle {
  font-weight: 500;
  font-size: 16px;
  color: $color-text-regular;
  margin: 50px 0 12px 30px;
  align-self: flex-start;
}

// ── 表单 ──
.login-form {
  width: 100%;
}

// ── 输入框 (透明底 + 半透明白色背景) ──
.login-field {
  width: calc(100% - 60px);
  margin: 0 30px 12px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  :deep(.van-cell) {
    background: rgba(255, 255, 255, 0.9) !important;
  }

  :deep(.van-field__control) {
    &::placeholder {
      color: $color-text-placeholder;
    }
  }
}

// ── 验证码图片 ──
.login-captcha-img {
  width: 95px;
  height: 35px;
  border-radius: 8px;
  cursor: pointer;
}

// ── 记住密码 ──
.login-save {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-right: 30px;
  font-size: 12px;
  color: $color-text-placeholder;
  user-select: none;
}

// ── 登录按钮 ──
.login-btn-wrapper {
  margin: 20px 30px;
}

.login-btn {
  height: 44px;
  font-size: 16px;
  letter-spacing: 4px;

  :deep(.van-button__text) {
    font-weight: 500;
  }
}

// ── 隐私政策提示 ──
.login-tips {
  margin: 0 30px;
  font-size: 12px;
  color: $color-text-secondary;
  text-align: center;

  &__link {
    color: $color-primary;
    text-decoration: underline;
    cursor: pointer;
  }
}

// ── 底部 ──
.login-footer {
  margin-top: auto;
  padding-top: 30px;
  text-align: center;
  width: 100%;
  font-size: 12px;
  color: $color-text-secondary;
  transition: opacity 0.3s ease;
  line-height: 1.8;

  &__version {
    font-size: 11px;
    color: $color-text-placeholder;
  }

  &__support {
    font-size: 12px;
  }

  &--hidden {
    opacity: 0;
  }
}
</style>
