<template>
  <div class="login-container">
    <div class="login-form">
      <div class="login-header">
        <h2>保险端口后台管理系统</h2>
        <p>请登录您的账户</p>
      </div>
      
      <a-form
        :model="formState"
        name="login"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <a-form-item
          name="username"
          :rules="[{ required: true, message: '请输入用户名!' }]"
        >
          <a-input
            v-model:value="formState.username"
            placeholder="用户名"
            size="large"
          >
            <template #prefix>
              <user-outlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          name="password"
          :rules="[{ required: true, message: '请输入密码!' }]"
        >
          <a-input-password
            v-model:value="formState.password"
            placeholder="密码"
            size="large"
          >
            <template #prefix>
              <lock-outlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="remember">
          <a-checkbox v-model:checked="formState.remember">
            记住登录
          </a-checkbox>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            size="large"
            :loading="loading"
            block
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>

      <div class="login-footer">
        <p>© 2024 保险端口系统 - 后台管理系统</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { authAPI } from '@/utils/api'
import { useUserStore } from '@/stores/user'
import authService from '@/services/authService'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)

const formState = reactive({
  username: '',
  password: '',
  remember: false
})

const onFinish = async (values) => {
  loading.value = true
  try {
    console.log('登录请求参数:', values)
    const response = await authAPI.login(values)
    console.log('登录响应:', response)
    
    // 修复响应结构解析：后端返回的是 response.data.status 而不是 response.status
    if (response.data && (response.data.status === 'success' || response.data.code === 200)) {
      const data = response.data.data
      
      // 检查是否为新的双Token格式
      if (data.accessToken && data.refreshToken) {
        // 新的双Token格式
        console.log('使用新的双Token格式存储认证信息')
        console.log('用户数据:', data.user)
        userStore.setAuthData({
          accessToken: data.accessToken,
          refreshToken: data.refreshToken,
          user: data.user || data.userInfo,
          expiresIn: data.accessTokenExpiresIn || 900 // 默认15分钟
        })
      } else if (data.token) {
        // 兼容旧的单Token格式
        console.log('使用旧的单Token格式存储认证信息')
        userStore.setToken(data.token)
        userStore.setUserInfo(data.user || data.userInfo) // 修复：用户信息在data.user中
      } else {
        throw new Error('响应数据格式不正确：缺少token信息')
      }
      
      // 保存登录凭据（如果用户选择记住登录）
      authService.saveLoginCredentials(values.username, values.remember)
      
      message.success('登录成功')
      router.push('/dashboard')
    } else {
      message.error(response.data?.message || response.message || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    message.error(error.response?.data?.message || error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时检查是否有记住的用户名
onMounted(() => {
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  const rememberLogin = localStorage.getItem('rememberLogin') === 'true'
  
  if (rememberedUsername && rememberLogin) {
    formState.username = rememberedUsername
    formState.remember = true
  }
})

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
</script>

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

.login-form {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 8px;
}

.login-header p {
  color: #666;
  margin: 0;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  color: #999;
}
</style>