<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <el-icon class="logo-icon">
          <Download />
        </el-icon>
        <h1>文件下载器</h1>
        <p>登录或注册以开始使用</p>
      </div>

      <!-- 切换按钮 -->
      <div class="mode-switch">
        <el-button :type="isLoginMode ? 'primary' : 'default'" @click="switchToLogin" :disabled="isLoginMode">
          登录
        </el-button>
        <el-button :type="!isLoginMode ? 'primary' : 'default'" @click="switchToRegister" :disabled="!isLoginMode">
          注册
        </el-button>
      </div>

      <!-- 错误消息显示 -->
      <div v-if="errorMessage" class="error-message">
        <el-alert :title="errorMessage" type="error" :closable="false" show-icon />
      </div>

      <!-- 成功消息显示 -->
      <div v-if="successMessage" class="success-message">
        <el-alert :title="successMessage" type="success" :closable="false" show-icon />
      </div>

      <!-- 登录表单 -->
      <el-form v-if="isLoginMode" ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form"
        @submit.prevent="handleLogin">
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" placeholder="用户名" prefix-icon="User" size="large" />
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock" size="large"
            show-password @keyup.enter="handleLogin" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form v-else ref="registerFormRef" :model="registerForm" :rules="registerRules" class="login-form"
        @submit.prevent="handleRegister">
        <el-form-item prop="userName">
          <el-input v-model="registerForm.userName" placeholder="用户名（至少3个字符）" prefix-icon="User" size="large" />
        </el-form-item>

        <el-form-item prop="email">
          <el-input v-model="registerForm.email" placeholder="邮箱（可选）" prefix-icon="Message" size="large" />
        </el-form-item>

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

        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" prefix-icon="Lock"
            size="large" show-password @keyup.enter="handleRegister" />
        </el-form-item>

        <!-- 密码强度提示 -->
        <div v-if="registerForm.password" class="password-strength">
          <div class="strength-title">密码要求：</div>
          <div class="strength-items">
            <div class="strength-item" :class="{ valid: registerForm.password.length >= 6 }">
              <el-icon>
                <Check v-if="registerForm.password.length >= 6" />
                <Close v-else />
              </el-icon>
              至少6位
            </div>
            <div class="strength-item" :class="{ valid: /\d/.test(registerForm.password) }">
              <el-icon>
                <Check v-if="/\d/.test(registerForm.password)" />
                <Close v-else />
              </el-icon>
              包含数字
            </div>
            <div class="strength-item" :class="{ valid: /[a-zA-Z]/.test(registerForm.password) }">
              <el-icon>
                <Check v-if="/[a-zA-Z]/.test(registerForm.password)" />
                <Close v-else />
              </el-icon>
              包含字母
            </div>
            <div class="strength-item" :class="{ valid: hasSpecialChar }">
              <el-icon>
                <Check v-if="hasSpecialChar" />
                <Close v-else />
              </el-icon>
              包含特殊字符
            </div>
          </div>
        </div>

        <el-form-item>
          <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleRegister">
            注册
          </el-button>
        </el-form-item>
      </el-form>


    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Close, Download } from '@element-plus/icons-vue'
import { useAuthStore } from '../stores/auth'
import http from '@/utils/request.js';
import config from '@/api/api.js';
import { lo } from 'element-plus/es/locales.mjs'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 状态
const isLoginMode = ref(true)
const loading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 密码验证计算属性
const hasSpecialChar = computed(() => {
  return /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(registerForm.password)
})

// 登录表单
const loginForm = reactive({
  userName: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  userName: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 登录验证规则
const loginRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册验证规则
const registerRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/\d/.test(value)) {
          callback(new Error('密码必须包含数字'))
        } else if (!/[a-zA-Z]/.test(value)) {
          callback(new Error('密码必须包含字母'))
        } else if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)) {
          callback(new Error('密码必须包含特殊字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 切换到登录模式
const switchToLogin = () => {
  isLoginMode.value = true
  clearMessages()
  resetForms()
}

// 切换到注册模式
const switchToRegister = () => {
  isLoginMode.value = false
  clearMessages()
  resetForms()
}

// 清除消息
const clearMessages = () => {
  errorMessage.value = ''
  successMessage.value = ''
}

// 重置表单
const resetForms = () => {
  Object.assign(loginForm, { userName: '', password: '' })
  Object.assign(registerForm, { userName: '', email: '', password: '', confirmPassword: '' })

  if (loginFormRef.value) {
    loginFormRef.value.clearValidate()
  }
  if (registerFormRef.value) {
    registerFormRef.value.clearValidate()
  }
}

// 处理登录
function handleLogin() {
  if (!loginForm.userName.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!loginForm.password.trim()) {
    ElMessage.warning('请输入密码')
    return
  }
  clearMessages()
  loading.value = true

  http.post(config.login, { ...loginForm }).then(res => {
    loading.value = false
    if (res.code === 200) {
      sessionStorage.setItem("token", res.data)
      let user = {
        "id": res.data,
        "username": loginForm.userName,
        "password": loginForm.password,
        "email": "",
        "createdAt": new Date(),
        "lastLoginAt": new Date(),
        "settings": {
            "maxConcurrentDownloads": 3,
            "enableNotifications": true,
            "fileNamePrefix": ""
        }
      }
      authStore.setCurrentUser(user)
      sessionStorage.setItem("userName", loginForm.userName)
      router.push('/downloader')
    } else {
      errorMessage.value = res.message
      ElMessage.error(res.message)
    }
  })
}
const handleLogin1 = async () => {
  try {
    console.log('开始登录处理...')
    // 检查用户名和密码是否为空
    if (!loginForm.userName.trim()) {
      ElMessage.warning('请输入用户名')
      return
    }
    if (!loginForm.password.trim()) {
      ElMessage.warning('请输入密码')
      return
    }

    // 等待 DOM 更新，确保表单引用可用
    await nextTick()
    // 检查表单引用是否存在，如果不存在则跳过验证
    if (loginFormRef.value) {
      try {
        await loginFormRef.value.validate()
      } catch (validationError) {
        console.log('表单验证失败:', validationError)
        ElMessage.error('请检查输入信息是否正确')
        return
      }
    } else {
      console.warn('登录表单引用不存在，跳过表单验证')
    }

    loading.value = true
    clearMessages()

    console.log('登录表单验证通过，用户名:', loginForm.userName)

    await authStore.login(loginForm.userName, loginForm.password)
    console.log('登录成功，跳转到下载器页面')
    ElMessage.success('登录成功！')
    router.push('/downloader')
  } catch (error) {
    console.error('登录失败:', error)
    const errorMsg = error.message || '登录失败，请检查用户名和密码'
    console.log('显示错误消息:', errorMsg)

    // 使用多种方式显示错误消息
    try {
      // 方式1: ElMessage
      ElMessage.error(errorMsg)
      console.log('ElMessage 已调用')
    } catch (msgError) {
      console.error('ElMessage 失败:', msgError)
    }

    // 方式2: 直接设置错误消息到页面
    errorMessage.value = errorMsg
    console.log('错误消息已设置到页面:', errorMessage.value)

    // 方式3: 尝试显示对话框
    setTimeout(async () => {
      try {
        await ElMessageBox.alert(errorMsg, '登录失败', {
          confirmButtonText: '确定',
          type: 'error'
        })
        console.log('对话框显示成功')
      } catch (dialogError) {
        console.error('显示对话框失败:', dialogError)
      }
    }, 100)
  } finally {
    loading.value = false
  }
}

// 处理注册
function handleRegister() {
  if (!registerForm.userName.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }

  if (!registerForm.password.trim()) {
    ElMessage.warning('请输入密码')
    return
  }

  if (!registerForm.confirmPassword.trim()) {
    ElMessage.warning('请确认密码')
    return
  }
  clearMessages()
  loading.value = true

  http.post(config.register, { ...registerForm }).then(res => {
    loading.value = false
    if (res.code === 200) {
      sessionStorage.setItem("token", res.data)
      switchToLogin()
      loginForm.userName = registerForm.userName
    } else {
      errorMessage.value = res.message
      ElMessage.error(res.message)
    }
  })
}
const handleRegister1 = async () => {
  try {
    // 检查用户名和密码是否为空
    if (!registerForm.userName.trim()) {
      ElMessage.warning('请输入用户名')
      return
    }

    if (!registerForm.password.trim()) {
      ElMessage.warning('请输入密码')
      return
    }

    if (!registerForm.confirmPassword.trim()) {
      ElMessage.warning('请确认密码')
      return
    }

    // 等待 DOM 更新，确保表单引用可用
    await nextTick()

    // 检查表单引用是否存在，如果不存在则跳过验证
    if (registerFormRef.value) {
      try {
        await registerFormRef.value.validate()
      } catch (validationError) {
        console.log('注册表单验证失败:', validationError)
        ElMessage.error('请检查输入信息是否正确')
        return
      }
    } else {
      console.warn('注册表单引用不存在，跳过表单验证')
    }

    loading.value = true
    clearMessages()

    // 检查用户名是否已存在
    if (authStore.isUsernameExists(registerForm.userName)) {
      ElMessage.error('用户名已存在')
      errorMessage.value = '用户名已存在'
      return
    }

    // 注册用户
    await authStore.register(registerForm.userName, registerForm.password, registerForm.email)

    ElMessage.success('注册成功！请登录')
    successMessage.value = '注册成功！请登录'

    // 自动切换到登录模式
    setTimeout(() => {
      switchToLogin()
      loginForm.userName = registerForm.userName
    }, 2000)

  } catch (error) {
    console.error('注册失败:', error)
    const errorMsg = error.message || '注册失败'
    console.log('显示注册错误对话框:', errorMsg)

    // 直接使用 ElMessage 显示错误，确保能显示
    ElMessage.error(errorMsg)

    // 尝试显示对话框，但不阻塞
    setTimeout(async () => {
      try {
        await ElMessageBox.alert(errorMsg, '注册失败', {
          confirmButtonText: '确定',
          type: 'error'
        })
      } catch (dialogError) {
        console.error('显示对话框失败:', dialogError)
      }
    }, 100)

    errorMessage.value = errorMsg
  } finally {
    loading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  authStore.initialize()
})
</script>

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

.login-box {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
}

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

.logo-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

.login-header h1 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.mode-switch {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
}

.mode-switch .el-button {
  flex: 1;
}

.login-form {
  margin-bottom: 20px;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.error-message {
  margin-bottom: 20px;
}

.success-message {
  margin-bottom: 20px;
}


.password-strength {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.strength-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 10px;
}

.strength-items {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.strength-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.strength-item.valid {
  color: #67c23a;
}

.strength-item .el-icon {
  font-size: 14px;
}

.strength-item.valid .el-icon {
  color: #67c23a;
}

.strength-item:not(.valid) .el-icon {
  color: #f56c6c;
}

@media (max-width: 480px) {
  .login-box {
    padding: 30px 20px;
  }

  .strength-items {
    grid-template-columns: 1fr;
  }
}
</style>
