<template>
  <div class="login-container">
    <div class="login-box">
      <div class="logo-section">
        <el-icon :size="80" color="#475569"><Box /></el-icon>
        <h1>资产管理系统</h1>
        <p>Asset Management System</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginData"
        :rules="loginRules"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginData.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginData.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item prop="captcha">
          <el-row :gutter="10">
            <el-col :span="14">
              <el-input
                v-model="loginData.captcha"
                placeholder="请输入验证码"
                prefix-icon="Key"
                size="large"
                clearable
              />
            </el-col>
            <el-col :span="10">
              <div class="captcha-box" @click="refreshCaptcha">
                <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" />
                <el-icon v-else :size="40"><Loading /></el-icon>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginData.remember">记住我</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            style="width: 100%"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="footer">
        <p>推荐使用 Chrome 浏览器以获得最佳体验</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores'
import { getCaptcha, login } from '@/api'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

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

const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const captchaUrl = ref('')
const captchaKey = ref('')

const loginData = reactive({
  username: '',
  password: '',
  captcha: '',
  captcha_key: '',
  remember: false
})

const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 50, message: '用户名长度为 4 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为 4 位', trigger: 'blur' }
  ]
}

/**
 * 获取验证码
 */
const fetchCaptcha = async () => {
  try {
    const data = await getCaptcha()
    captchaUrl.value = data.captcha_image
    captchaKey.value = data.captcha_key
    loginData.captcha_key = data.captcha_key
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}

/**
 * 刷新验证码
 */
const refreshCaptcha = () => {
  fetchCaptcha()
  loginData.captcha = ''
}

/**
 * 登录
 */
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    await userStore.login(
      loginData.username,
      loginData.password,
      loginData.captcha,
      loginData.captcha_key
    )

    ElMessage.success('登录成功')

    // 跳转到首页或重定向页面
    const redirect = (route.query.redirect as string) || '/'
    router.push(redirect)
  } catch (error: any) {
    if (error !== false) {
      ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 如果已登录，直接跳转
  if (userStore.isLoggedIn) {
    router.push('/')
    return
  }

  // 获取验证码
  fetchCaptcha()
})
</script>

<style scoped lang="scss">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 20% 50%, rgba(102, 126, 234, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 80% 80%, rgba(118, 75, 162, 0.3) 0%, transparent 50%);
    animation: bg-pan 15s ease infinite;
  }
}

@keyframes bg-pan {
  0% {
    transform: scale(1) translate(0, 0);
  }
  50% {
    transform: scale(1.1) translate(-10px, 10px);
  }
  100% {
    transform: scale(1) translate(0, 0);
  }
}

.login-box {
  position: relative;
  width: 420px;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
  z-index: 1;

  .logo-section {
    text-align: center;
    margin-bottom: 30px;

    h1 {
      font-size: 28px;
      font-weight: 600;
      color: $text-primary;
      margin: 15px 0 5px;
    }

    p {
      color: $text-secondary;
      font-size: 14px;
      margin: 0;
    }
  }

  .login-form {
    margin-top: 30px;

    .captcha-box {
      width: 100%;
      height: 40px;
      border: 1px solid $border-base;
      border-radius: $border-radius-base;
      overflow: hidden;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: $bg-color-page;
      transition: $transition-base;

      &:hover {
        border-color: $primary-color;
      }

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

  .footer {
    margin-top: 20px;
    text-align: center;

    p {
      color: $text-placeholder;
      font-size: 12px;
      margin: 0;
    }
  }
}
</style>
