<template>
  <div v-if="visible" class="login-modal-overlay">
    <div class="login-modal" @click.stop>
      <div class="login-modal-header">
        <h2>用户登录</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <div class="login-modal-body">
        <form @submit.prevent="handleLogin" class="login-form">
          <!-- 用户名 -->
          <div class="form-group">
            <label for="username">用户名</label>
            <input
              id="username"
              v-model="loginForm.username"
              type="text"
              placeholder="请输入用户名"
              required
              :disabled="loading"
            />
          </div>
          
          <!-- 密码 -->
          <div class="form-group">
            <label for="password">密码</label>
            <div class="password-input-container">
              <input
                id="password"
                v-model="loginForm.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                required
                :disabled="loading"
              />
              <button
                type="button"
                class="password-toggle-btn"
                @click="togglePassword"
                :disabled="loading"
                :title="showPassword ? '隐藏密码' : '显示密码'"
              >
                <span class="password-icon">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</span>
              </button>
            </div>
          </div>
          
          <!-- 验证码 -->
          <div class="form-group">
            <label for="captcha">验证码</label>
            <div class="captcha-container">
              <input
                id="captcha"
                v-model="loginForm.captcha"
                type="text"
                placeholder="请输入验证码"
                required
                :disabled="loading"
                maxlength="4"
              />
              <div class="captcha-image-container">
                <img
                  v-if="captchaImage"
                  :src="captchaImage"
                  alt="验证码"
                  @click="refreshCaptcha"
                  class="captcha-image"
                />
                <div v-else class="captcha-placeholder" @click="refreshCaptcha">
                  <span v-if="captchaLoading">验证码加载中...</span>
                  <span v-else>点击获取验证码</span>
                  <span v-if="captchaLoading" class="captcha-loading-spinner"></span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 登录按钮 -->
          <div class="form-actions">
            <button
              type="submit"
              class="login-btn"
              :disabled="loading || !isFormValid"
            >
              <span v-if="loading" class="loading-spinner"></span>
              {{ loading ? '登录中...' : '登录' }}
            </button>
            

          </div>
          
          <!-- 错误提示 -->
          <div v-if="errorMessage" class="error-message" role="alert">
            <span class="error-icon">⚠️</span>
            {{ errorMessage }}
          </div>
          

        </form>
      </div>
      
      <div class="login-modal-footer">
        <p class="login-tips">
          <span>提示：</span>
          <span>默认管理员账号：admin</span>
          <span>默认密码：password</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { userService } from '@/modules/user-management'
import * as ipUtils from '@/modules/core/utils/ipUtils'

const { getClientIP } = ipUtils

export default {
  name: 'LoginModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      captchaLoading: false,
      showPassword: false,
      errorMessage: '',
      captchaImage: '',
      captchaId: '',
      clientIP: '',
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      }
    }
  },
  computed: {
    isFormValid() {
      return this.loginForm.username.trim() && 
             this.loginForm.password.trim() && 
             this.loginForm.captcha.trim() &&
             this.captchaImage // 确保验证码图片已加载
    },
    

  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm()
        this.getClientIP()  // 获取客户端IP
        this.refreshCaptcha()
        this.loadSavedLoginInfo() // 加载保存的登录信息
      }
    }
  },
  methods: {
    // 加载保存的登录信息
    loadSavedLoginInfo() {
      try {
        const savedLoginInfo = localStorage.getItem('gofaster-login-info')
        if (savedLoginInfo) {
          const loginInfo = JSON.parse(savedLoginInfo)
          if (loginInfo.username && loginInfo.password) {
            this.loginForm.username = loginInfo.username
            this.loginForm.password = loginInfo.password
            console.log('已自动填充保存的登录信息')
          }
        }
      } catch (error) {
        console.error('加载保存的登录信息失败:', error)
      }
    },

    // 保存登录信息到本地存储
    saveLoginInfo() {
      try {
        // 检查用户设置中的"记住密码"选项
        const userSettings = localStorage.getItem('gofaster-settings')
        if (userSettings) {
          const settings = JSON.parse(userSettings)
          if (settings.rememberPassword) {
            const loginInfo = {
              username: this.loginForm.username,
              password: this.loginForm.password,
              timestamp: Date.now()
            }
            localStorage.setItem('gofaster-login-info', JSON.stringify(loginInfo))
            console.log('已保存登录信息到本地存储')
          } else {
            // 如果用户选择不记住密码，清除保存的登录信息
            localStorage.removeItem('gofaster-login-info')
            console.log('用户选择不记住密码，已清除保存的登录信息')
          }
        }
      } catch (error) {
        console.error('保存登录信息失败:', error)
      }
    },

    async handleLogin() {
      if (!this.isFormValid) {
        this.errorMessage = '请填写完整的登录信息'
        return
      }
      
      this.loading = true
      this.errorMessage = ''
      
      try {
        // 调用登录接口
        const response = await userService.login({
          username: this.loginForm.username,
          password: this.loginForm.password,
          captcha: this.loginForm.captcha,
          captcha_id: this.captchaId,  // 修复字段名：后端期望 snake_case
          client_ip: this.clientIP      // 传入客户端IP
        })
        
        // 登录成功后保存登录信息
        this.saveLoginInfo()
        
        // 登录成功
        this.$emit('login-success', response)
        this.closeModal()
        
        // 显示成功提示
        this.$emit('show-message', {
          type: 'success',
          title: '登录成功',
          content: `欢迎回来，${response.data?.user?.username || response.user?.username || this.loginForm.username || '用户'}！`
        })
        
      } catch (error) {
        // 增强错误提示，显示具体的错误原因
        console.log('登录错误详情:', error)
        console.log('错误响应状态:', error.response?.status)
        console.log('错误响应数据:', error.response?.data)
        
        let errorMsg = '登录失败，请重试'
        
                 if (error.response) {
           // 服务器返回错误响应
           const status = error.response.status
           const data = error.response.data
           
           // 优先检查错误消息内容，判断是否为验证码错误
           if (data.message && data.message.includes('验证码')) {
             errorMsg = '验证码错误，请重新输入'
           } else if (data.error && data.error.includes('验证码')) {
             errorMsg = '验证码错误，请重新输入'
           } else if (status === 400) {
             // 400 状态码，可能是验证码错误或其他参数错误
             if (data.message) {
               errorMsg = data.message
             } else if (data.error) {
               errorMsg = data.error
             } else {
               errorMsg = '请求参数错误，请检查输入信息'
             }
           } else if (status === 401) {
             // 401 是用户名或密码错误，显示模糊信息
             errorMsg = '用户名或密码错误'
           } else if (status === 422) {
             // 422 通常是验证失败
             if (data.message) {
               errorMsg = data.message
             } else {
               errorMsg = '验证失败，请检查输入信息'
             }
           } else if (status === 423) {
             // 账户被锁定
             if (data.error) {
               errorMsg = data.error
             } else if (data.message) {
               errorMsg = data.message
             } else {
               errorMsg = '账户被锁定，请稍后重试'
             }
           } else if (status === 500) {
             errorMsg = '服务器内部错误，请稍后重试'
           }
         } else if (error.message) {
           // 网络错误或其他错误
           if (error.message.includes('验证码')) {
             errorMsg = '验证码错误，请重新输入'
           } else if (error.message.includes('用户名') || error.message.includes('密码')) {
             // 账户密码相关错误显示模糊信息
             errorMsg = '用户名或密码错误'
           } else {
             errorMsg = error.message
           }
         }
        
        console.log('最终显示的错误信息:', errorMsg)
        this.errorMessage = errorMsg
        
        // 强制触发视图更新
        this.$nextTick(() => {
          console.log('错误信息已设置到界面:', this.errorMessage)
        })
        
        // 登录失败时刷新验证码，但不清空错误信息
        this.refreshCaptchaWithoutClearError()
      } finally {
        this.loading = false
      }
    },
    
    async refreshCaptcha() {
      try {
        this.captchaLoading = true
        this.errorMessage = ''
        // 调用获取验证码接口
        const response = await userService.getCaptcha()
        // 修复字段映射：后端返回的是 snake_case，前端使用 camelCase
        this.captchaImage = response.data.captcha_image
        this.captchaId = response.data.captcha_id
        this.loginForm.captcha = ''
        console.log('验证码获取成功:', response)
      } catch (error) {
        console.error('获取验证码失败:', error)
        this.errorMessage = '获取验证码失败，请重试'
        this.captchaImage = ''
        this.captchaId = ''
      } finally {
        this.captchaLoading = false
      }
    },
    
    async refreshCaptchaWithoutClearError() {
      try {
        this.captchaLoading = true
        // 不清空错误信息
        // 调用获取验证码接口
        const response = await userService.getCaptcha()
        // 修复字段映射：后端返回的是 snake_case，前端使用 camelCase
        this.captchaImage = response.data.captcha_image
        this.captchaId = response.data.captcha_id
        this.loginForm.captcha = ''
        console.log('验证码获取成功（不清空错误）:', response)
      } catch (error) {
        console.error('获取验证码失败:', error)
        // 不清空错误信息，只设置验证码相关的错误
        this.captchaImage = ''
        this.captchaId = ''
      } finally {
        this.captchaLoading = false
      }
    },
    
    // 获取客户端IP地址
    async getClientIP() {
      try {
        this.clientIP = await getClientIP()
        console.log('获取到客户端IP:', this.clientIP)
      } catch (error) {
        console.error('获取客户端IP失败:', error)
        this.clientIP = '127.0.0.1'
      }
    },
    
    resetForm() {
      this.loginForm = {
        username: '',
        password: '',
        captcha: ''
      }
      this.showPassword = false
      this.errorMessage = ''
      this.captchaImage = ''
      this.captchaId = ''
    },
    
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    
    closeModal() {
      this.$emit('update:visible', false)
      this.resetForm()
    }
  }
}
</script>

<style scoped>
.login-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.login-modal {
  background: var(--bg-primary);
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 400px;
  max-height: 90vh;
  overflow: hidden;
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.login-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color);
  background: var(--header-bg);
}

.login-modal-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.login-modal-body {
  padding: 24px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: var(--text-primary);
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  background: var(--bg-secondary);
  color: var(--text-primary);
  transition: all 0.2s;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
}

.form-group input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 密码输入框容器 */
.password-input-container {
  position: relative;
  display: flex;
  align-items: center;
}

.password-input-container input {
  padding-right: 50px; /* 为密码切换按钮留出空间 */
}

.password-toggle-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.password-toggle-btn:hover {
  background: var(--bg-secondary);
}

.password-toggle-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.password-icon {
  font-size: 16px;
  line-height: 1;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: stretch;
}

.captcha-container input {
  flex: 1;
}

.captcha-image-container {
  width: 100px;
  height: 44px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid var(--border-color);
  transition: all 0.2s;
}

.captcha-image-container:hover {
  border-color: var(--primary-color);
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-placeholder {
  width: 100%;
  height: 100%;
  background: var(--bg-secondary);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  font-size: 12px;
  text-align: center;
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.captcha-placeholder:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.captcha-hint {
  font-size: 10px;
  opacity: 0.7;
  margin-top: 2px;
}

.captcha-loading-spinner {
  width: 12px;
  height: 12px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-top: 4px;
}

.form-actions {
  margin-top: 8px;
}

.login-btn {
  width: 100%;
  padding: 14px 24px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

/* 深色主题下的登录按钮样式 */
.theme-dark .login-btn {
  background: var(--primary-color);
  color: #333333;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.theme-dark .login-btn:hover:not(:disabled) {
  background: var(--primary-hover);
  color: #222222;
}

.login-btn:hover:not(:disabled) {
  background: var(--primary-hover);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.3);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}



.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  background: var(--error-bg);
  color: var(--error-text);
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  border: 1px solid var(--error-border);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 16px;
  animation: errorShake 0.5s ease-in-out;
}

.error-icon {
  font-size: 16px;
  flex-shrink: 0;
}

@keyframes errorShake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 深色主题下的错误提示样式优化 */
.theme-dark .error-message {
  background: rgba(244, 67, 54, 0.2);
  color: #ffab91;
  border: 1px solid rgba(244, 67, 54, 0.5);
  font-weight: 500;
}

.login-modal-footer {
  padding: 16px 24px;
  border-top: 1px solid var(--border-color);
  background: var(--bg-secondary);
}

.login-tips {
  margin: 0;
  font-size: 12px;
  color: var(--text-secondary);
  text-align: center;
  line-height: 1.5;
}

.login-tips span {
  display: block;
  margin-bottom: 4px;
}

.login-tips span:first-child {
  font-weight: 600;
  color: var(--text-primary);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-modal {
    width: 95%;
    margin: 20px;
  }
  
  .login-modal-header,
  .login-modal-body,
  .login-modal-footer {
    padding: 16px 20px;
  }
  
  .captcha-container {
    flex-direction: column;
    gap: 8px;
  }
  
  .captcha-image-container {
    width: 100%;
    height: 40px;
  }
}
</style>
