<template>
  <div v-if="visible" class="login-modal-overlay" @click="handleOverlayClick">
    <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>
            <input
              id="password"
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              required
              :disabled="loading"
            />
          </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 v-if="!isFormValid && (loginForm.username || loginForm.password || loginForm.captcha)" class="form-validation-hint">
              <span v-if="!loginForm.username.trim()">请填写用户名</span>
              <span v-else-if="!loginForm.password.trim()">请填写密码</span>
              <span v-else-if="!loginForm.captcha.trim()">请填写验证码</span>
              <span v-else-if="!captchaImage">请先获取验证码</span>
            </div>
          </div>
          
          <!-- 错误提示 -->
          <div v-if="errorMessage" class="error-message">
            {{ errorMessage }}
          </div>
        </form>
      </div>
      
      <div class="login-modal-footer">
        <p class="login-tips">
          <span>提示：</span>
          <span>默认管理员账号：sysadmin</span>
          <span>默认密码：sysadmin@123</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { userService } from '../services/userService'

export default {
  name: 'LoginModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      captchaLoading: false,
      errorMessage: '',
      captchaImage: '',
      captchaId: '',
      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.refreshCaptcha()
      }
    }
  },
  methods: {
    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,
          captchaId: this.captchaId
        })
        
        // 登录成功
        this.$emit('login-success', response)
        this.closeModal()
        
        // 显示成功提示
        this.$emit('show-message', {
          type: 'success',
          title: '登录成功',
          content: `欢迎回来，${response.user?.username || '用户'}！`
        })
        
      } catch (error) {
        this.errorMessage = error.message || '登录失败，请重试'
        // 登录失败时刷新验证码
        this.refreshCaptcha()
      } finally {
        this.loading = false
      }
    },
    
    async refreshCaptcha() {
      try {
        this.captchaLoading = true
        this.errorMessage = ''
        // 调用获取验证码接口
        const response = await userService.getCaptcha()
        this.captchaImage = response.captchaImage
        this.captchaId = response.captchaID
        this.loginForm.captcha = ''
        console.log('验证码获取成功:', response)
      } catch (error) {
        console.error('获取验证码失败:', error)
        this.errorMessage = '获取验证码失败，请重试'
        this.captchaImage = ''
        this.captchaId = ''
      } finally {
        this.captchaLoading = false
      }
    },
    
    resetForm() {
      this.loginForm = {
        username: '',
        password: '',
        captcha: ''
      }
      this.errorMessage = ''
      this.captchaImage = ''
      this.captchaId = ''
    },
    
    closeModal() {
      this.$emit('update:visible', false)
      this.resetForm()
    },
    
    handleOverlayClick() {
      this.closeModal()
    }
  }
}
</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 {
  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;
}

.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;
}

.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;
}

/* 表单验证提示样式 */
.form-validation-hint {
  margin-top: 8px;
  padding: 8px 12px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 12px;
  color: var(--text-secondary);
  text-align: center;
}

.form-validation-hint span {
  display: block;
  margin-bottom: 2px;
}

.form-validation-hint span:last-child {
  margin-bottom: 0;
}

.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);
}

/* 深色主题下的错误提示样式优化 */
.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>
