<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import loginBanner from '@/assets/login/loginBanner.png'
import { getCodeImg, login } from '@/api/login'
import { setToken } from '@/utils/auth'

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

const appTitle = import.meta.env.VITE_APP_TITLE || '数字畜牧一张图'
const loading = ref(false)
const errorMsg = ref('')
const captchaEnabled = ref(true)
const codeUrl = ref('')

const form = reactive({
  username: '',
  password: '',
  code: '',
  uuid: '',
  rememberMe: false
})

const REMEMBER_KEY = 'screen-login-username'

function loadRemembered() {
  const saved = localStorage.getItem(REMEMBER_KEY)
  if (saved) {
    form.username = saved
    form.rememberMe = true
  }
}

function saveRemembered() {
  if (form.rememberMe && form.username) {
    localStorage.setItem(REMEMBER_KEY, form.username.trim())
  } else {
    localStorage.removeItem(REMEMBER_KEY)
  }
}

async function refreshCaptcha() {
  try {
    const res = await getCodeImg()
    captchaEnabled.value = res.captchaEnabled !== false
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${res.img}`
      form.uuid = res.uuid
      form.code = ''
    }
  } catch {
    captchaEnabled.value = false
  }
}

function validate() {
  if (!form.username.trim()) {
    errorMsg.value = '请输入账号'
    return false
  }
  if (!form.password) {
    errorMsg.value = '请输入密码'
    return false
  }
  if (captchaEnabled.value && !form.code.trim()) {
    errorMsg.value = '请输入验证码'
    return false
  }
  return true
}

async function handleLogin() {
  errorMsg.value = ''
  if (!validate()) {
    return
  }
  loading.value = true
  try {
    const res = await login(
      form.username.trim(),
      form.password,
      form.code,
      form.uuid
    )
    setToken(res.token)
    saveRemembered()
    const redirect = route.query.redirect || '/home'
    router.replace(typeof redirect === 'string' ? redirect : '/home')
  } catch (e) {
    errorMsg.value = e?.message || '登录失败'
    if (captchaEnabled.value) {
      refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}

function onKeyupEnter() {
  handleLogin()
}

onMounted(() => {
  const urlError = route.query.screenLoginError
  if (typeof urlError === 'string' && urlError) {
    errorMsg.value = urlError
    const query = { ...route.query }
    delete query.screenLoginError
    router.replace({ path: '/login', query })
  }
  loadRemembered()
  refreshCaptcha()
})
</script>

<template>
  <div class="screen-login" :style="{ backgroundImage: `url(${loginBanner})` }">
    <div class="screen-login__panel">
      <header class="screen-login__header">
        <h1 class="screen-login__title">{{ appTitle }}</h1>
        <p class="screen-login__subtitle">可视化大屏登录</p>
        <p class="screen-login__subtitle-bo">མངོན་སྟོན་ཆེན་པའི་ཐོ་ཞུགས།</p>
      </header>

      <form class="screen-login__form" @submit.prevent="handleLogin">
        <label class="screen-login__field">
          <span class="screen-login__label">账号</span>
          <input
            v-model="form.username"
            type="text"
            autocomplete="username"
            placeholder="请输入账号"
            class="screen-login__input"
          />
        </label>

        <label class="screen-login__field">
          <span class="screen-login__label">密码</span>
          <input
            v-model="form.password"
            type="password"
            autocomplete="current-password"
            placeholder="请输入密码"
            class="screen-login__input"
            @keyup.enter="onKeyupEnter"
          />
        </label>

        <div v-if="captchaEnabled" class="screen-login__field screen-login__field--captcha">
          <span class="screen-login__label">验证码</span>
          <div class="screen-login__captcha-row">
            <input
              v-model="form.code"
              type="text"
              autocomplete="off"
              placeholder="验证码"
              class="screen-login__input"
              @keyup.enter="onKeyupEnter"
            />
            <img
              v-if="codeUrl"
              :src="codeUrl"
              class="screen-login__captcha-img"
              alt="验证码"
              title="点击刷新"
              @click="refreshCaptcha"
            />
          </div>
        </div>

        <label class="screen-login__remember">
          <input v-model="form.rememberMe" type="checkbox" />
          <span>记住账号</span>
        </label>

        <p v-if="errorMsg" class="screen-login__error">{{ errorMsg }}</p>

        <button type="submit" class="screen-login__btn" :disabled="loading">
          {{ loading ? '登录中…' : '登 录' }}
        </button>
      </form>
    </div>
  </div>
</template>

<style scoped>
.screen-login {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #020617;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  box-sizing: border-box;
  padding: 24px;
}

.screen-login__panel {
  width: 100%;
  max-width: 420px;
  padding: 36px 32px 32px;
  border-radius: 12px;
  background: rgba(3, 26, 21, 0.72);
  border: 1px solid var(--screen-line-dim, rgba(61, 217, 176, 0.42));
  box-shadow:
    0 0 40px rgba(50, 230, 170, 0.12),
    inset 0 1px 0 rgba(110, 255, 210, 0.08);
  backdrop-filter: blur(12px);
}

.screen-login__header {
  text-align: center;
  margin-bottom: 28px;
}

.screen-login__title {
  margin: 0 0 8px;
  font-size: 22px;
  font-weight: 600;
  color: var(--screen-text-primary, #fff);
  letter-spacing: 1px;
}

.screen-login__subtitle {
  margin: 0;
  font-size: 14px;
  color: var(--screen-text-secondary, #a8d4c8);
}

.screen-login__subtitle-bo {
  margin: 4px 0 0;
  font-size: 12px;
  color: var(--screen-text-muted, #6a9f90);
}

.screen-login__form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.screen-login__field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.screen-login__label {
  font-size: 13px;
  color: var(--screen-text-secondary, #a8d4c8);
}

.screen-login__input {
  height: 40px;
  padding: 0 12px;
  font-size: 14px;
  color: var(--screen-text-primary, #fff);
  background: rgba(4, 48, 40, 0.55);
  border: 1px solid var(--screen-line-dim, rgba(61, 217, 176, 0.35));
  border-radius: 6px;
  outline: none;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.screen-login__input::placeholder {
  color: var(--screen-text-muted, #6a9f90);
}

.screen-login__input:focus {
  border-color: var(--screen-line-bright, #5ef0c8);
  box-shadow: 0 0 0 2px rgba(94, 240, 200, 0.15);
}

.screen-login__captcha-row {
  display: flex;
  gap: 10px;
  align-items: center;
}

.screen-login__captcha-row .screen-login__input {
  flex: 1;
}

.screen-login__captcha-img {
  width: 108px;
  height: 40px;
  border-radius: 6px;
  cursor: pointer;
  border: 1px solid var(--screen-line-dim, rgba(61, 217, 176, 0.35));
  object-fit: cover;
}

.screen-login__remember {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: var(--screen-text-secondary, #a8d4c8);
  cursor: pointer;
  user-select: none;
}

.screen-login__remember input {
  accent-color: var(--screen-line, #3dd9b0);
}

.screen-login__error {
  margin: 0;
  font-size: 13px;
  color: #ffb4b4;
  text-align: center;
}

.screen-login__btn {
  height: 44px;
  margin-top: 4px;
  font-size: 16px;
  font-weight: 600;
  color: #031a15;
  cursor: pointer;
  border: 1px solid var(--screen-btn-active-border, rgba(110, 255, 210, 0.95));
  border-radius: 6px;
  background: linear-gradient(
    180deg,
    var(--screen-btn-active-top, #45f0b8) 0%,
    var(--screen-btn-active-mid, #22c997) 55%,
    var(--screen-btn-active-bottom, #0f8f72) 100%
  );
  box-shadow: 0 4px 16px var(--screen-btn-active-glow, rgba(50, 230, 170, 0.35));
  transition: opacity 0.2s, transform 0.15s;
}

.screen-login__btn:hover:not(:disabled) {
  transform: translateY(-1px);
}

.screen-login__btn:disabled {
  opacity: 0.65;
  cursor: not-allowed;
}
</style>
