<template>
  <div class="login-container" :style="{ backgroundImage: `url(${config.login_bg_image || ''})` }">
    <el-card class="login-card !border-none">
      <template #header>
        <div class="text-center text-4xl font-bold mb-2">{{ config.site_name }}</div>
        <div class="text-center text-sm">请输入您的帐户信息以开始管理您的项目</div>
      </template>
      <el-form class="p-3" :model="loginForm" :rules="loginRules" ref="loginFormRef" label-position="top">
        <el-form-item label="用户名" prop="account">
          <el-input
            v-model="loginForm.account"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
            @keyup.enter="handleEnter"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            ref="passwordInputRef"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            size="large"
            @keyup.enter="handleEnter"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha" v-if="captchaEnabled">
          <div class="w-full flex gap-2">
            <el-input
              class="flex-1"
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              prefix-icon="View"
              size="large"
              @keyup.enter="handleLogin"
            />
            <el-image :src="captchaImg" class="w-auto h-10 cursor-pointer" @click="refreshCaptcha" fit="cover" />
          </div>
        </el-form-item>
        <el-form-item>
          <div class="flex-1 flex items-center justify-between">
            <el-checkbox v-model="loginForm.remember">记住账号</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-button class="w-full" type="primary" size="large" :loading="isLoading" @click="handleLogin">
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules, InputInstance } from 'element-plus'
import { useConfigStore } from '@/stores/modules/config'
import { useUserStore } from '@/stores/modules/user'
import cache from '@/utils/cache'
import { getCaptcha } from '@/api/user'

const loginFormRef = shallowRef<FormInstance>()
const passwordInputRef = shallowRef<InputInstance>()
const route = useRoute()
const router = useRouter()
const configStore = useConfigStore()
const userStore = useUserStore()
const config = computed(() => configStore.config)

// 登录加载状态
const isLoading = ref(false)
// 验证码相关状态
const captchaEnabled = ref(false)
const captchaImg = ref('')
const captchaKey = ref('')
// 登录表单数据
const loginForm = reactive({
  account: '',
  password: '',
  captcha: '',
  remember: false
})
// 表单验证规则
const loginRules = reactive<FormRules>({
  account: [{ required: true, message: '请输入用户名', trigger: ['blur', 'change'] }],
  password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }],
  captcha: [{ required: true, message: '请输入验证码', trigger: ['blur', 'change'] }]
})

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    const res = await getCaptcha()
    captchaEnabled.value = res.enabled === 1
    captchaImg.value = res.img
    captchaKey.value = res.key
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}
// 用户名输入框回车事件
const handleEnter = () => {
  if (!loginForm.account) {
    if (loginFormRef.value) {
      return loginFormRef.value?.validateField('account')
    } else return
  }
  if (!loginForm.password) {
    return passwordInputRef.value?.focus()
  }
  if (captchaEnabled.value && !loginForm.captcha) {
    if (loginFormRef.value) {
      return loginFormRef.value?.validateField('captcha')
    } else return
  }
  handleLogin()
}
// 处理登录
const handleLogin = () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true
      try {
        const loginParams = {
          ...loginForm,
          ...(captchaEnabled.value && { captcha_key: captchaKey.value })
        }
        await userStore.login(loginParams)
        isLoading.value = false
        const redirect = route?.query?.redirect
        const path = typeof redirect === 'string' ? redirect : '/'
        router.push(path)
      } catch (error) {
        isLoading.value = false
        if (captchaEnabled.value) {
          refreshCaptcha()
        }
      }
    }
  })
}

onMounted(() => {
  const account = cache.get<string>('remember_account')
  if (account) {
    loginForm.remember = true
    loginForm.account = account
  }
  captchaEnabled.value = config.value.enable_captcha === 1
  if (captchaEnabled.value) refreshCaptcha()
})
</script>

<style lang="scss" scoped>
.login-container {
  @apply min-h-screen flex items-center justify-end pr-[10%];
  background-size: cover;
  background-position: center;

  .login-card {
    @apply w-full max-w-[400px] md:max-w-[450px];
    border-radius: 12px;
  }
}
</style>
