<template>
  <div class="login">
    <div class="login__card">
      <div class="login__brand">
        <img class="login__logo" src="@/assets/logo.svg" alt="logo" />
        <div class="login__titles">
          <h1 class="login__title">摄像头管理系统</h1>
          <p class="login__subtitle">Sign in to your console</p>
        </div>
      </div>

      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login__form" label-position="top">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            autocomplete="username"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
            autocomplete="current-password"
          />
        </el-form-item>
        <el-form-item v-if="captchaEnabled" prop="code">
          <div class="login__captcha">
            <el-input
              v-model="loginForm.code"
              placeholder="请输入验证码"
              size="large"
              :prefix-icon="Key"
              @keyup.enter="handleLogin"
            />
            <img :src="codeUrl" class="login__captcha-img" @click="getCode" alt="captcha" />
          </div>
        </el-form-item>
        <div class="login__actions">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <span class="login__forgot" @click="goHelp">忘记密码？</span>
        </div>

        <el-button type="primary" size="large" :loading="loading" class="login__submit" @click="handleLogin">
          登 录
        </el-button>
      </el-form>
      <div class="login__version">v{{ version }}</div>
    </div>
    <div class="login__bg" aria-hidden="true"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const version = __APP_VERSION__

const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const captchaEnabled = ref(false)
const codeUrl = ref('')
const rememberMe = ref(true)

const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: ''
})

const loginRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

// Hono API 不支持验证码，禁用验证码功能
function getCode() {
  captchaEnabled.value = false
}

async function handleLogin() {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await userStore.loginAction(loginForm)
        if (res.code === 200) {
          saveLoginInfo() // 保存登录信息
          ElMessage.success('登录成功')
          const redirect = (route.query.redirect as string) || '/'
          router.push(redirect)
        } else {
          ElMessage.error(res.message || '登录失败')
          if (captchaEnabled.value) {
            getCode()
          }
        }
      } catch (error) {
        if (captchaEnabled.value) {
          getCode()
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 记住我 - 保存/读取登录信息
const REMEMBER_KEY = 'login_remember'

function saveLoginInfo() {
  if (rememberMe.value) {
    const data = {
      username: loginForm.username,
      password: btoa(loginForm.password), // base64 编码
      remember: true
    }
    localStorage.setItem(REMEMBER_KEY, JSON.stringify(data))
  } else {
    localStorage.removeItem(REMEMBER_KEY)
  }
}

function loadLoginInfo() {
  const saved = localStorage.getItem(REMEMBER_KEY)
  if (saved) {
    try {
      const data = JSON.parse(saved)
      loginForm.username = data.username || ''
      loginForm.password = data.password ? atob(data.password) : '' // base64 解码
      rememberMe.value = data.remember ?? true
    } catch {
      localStorage.removeItem(REMEMBER_KEY)
    }
  }
}

onMounted(() => {
  getCode()
  loadLoginInfo()
})

// 取消勾选时清除保存的信息
watch(rememberMe, (val) => {
  if (!val) {
    localStorage.removeItem(REMEMBER_KEY)
  }
})

function goHelp() {
  ElMessage.info('请联系管理员重置密码')
}
</script>

<style lang="scss" scoped>
.login {
  position: relative;
  min-height: 100vh;
  display: grid;
  grid-template-columns: 1fr;
  place-items: center;
  background:
    radial-gradient(1200px 600px at 100% 0%, rgba(102, 126, 234, 0.25), transparent 60%),
    radial-gradient(1000px 500px at 0% 100%, rgba(118, 75, 162, 0.25), transparent 60%),
    linear-gradient(135deg, #0f172a 0%, #111827 60%, #0b1220 100%);
  padding: 24px;
  overflow: hidden;
}

.login__bg {
  position: absolute;
  inset: -10% -10% -10% -10%;
  background:
    radial-gradient(800px 400px at 50% -10%, rgba(59, 130, 246, 0.15), transparent 60%),
    radial-gradient(700px 350px at 100% 100%, rgba(236, 72, 153, 0.12), transparent 60%);
  filter: blur(40px);
  pointer-events: none;
}

.login__card {
  width: 100%;
  max-width: 420px;
  padding: 36px 32px 28px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.06);
  backdrop-filter: saturate(180%) blur(14px);
  border: 1px solid rgba(255, 255, 255, 0.12);
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
  color: #e5e7eb;
}

.login__brand {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 18px;
}
.login__logo {
  width: 36px;
  height: 36px;
}
.login__titles {
  display: grid;
  gap: 2px;
}
.login__title {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: #f9fafb;
}
.login__subtitle {
  margin: 0;
  font-size: 13px;
  color: #9ca3af;
}

.login__form {
  margin-top: 8px;
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.92);
  }
  .el-input {
    height: 44px;
  }
}

.login__captcha {
  display: flex;
  width: 100%;
  gap: 10px;
  .el-input {
    flex: 1;
  }
}
.login__captcha-img {
  width: 108px;
  height: 44px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  background: #fff;
  cursor: pointer;
}

.login__actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 2px 0 10px;
  color: #cbd5e1;
}
.login__forgot {
  font-size: 12px;
  color: #93c5fd;
  cursor: pointer;
}

.login__submit {
  width: 100%;
  height: 44px;
  font-size: 15px;
}

.login__version {
  margin-top: 16px;
  text-align: center;
  font-size: 12px;
  color: #6b7280;
}

@media (max-width: 480px) {
  .login__card {
    padding: 28px 20px 22px;
  }
}
</style>
