<script setup>
import { ref, reactive, onMounted } from 'vue'
import { User, Lock, Bell } from '@element-plus/icons-vue'
import { userLoginService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
// 表单引用
const loginFormRef = ref(null)
// 当前步骤
const currentStep = ref(0)

// 表单数据
const loginForm = reactive({
  account: '',
  passwd: '',
  verifyCode: '',
  role: '',
  rememberMe: false
})
// 用户信息存储
const userStore = useUserStore()
// 路由
const router = useRouter()

// 角色列表
const roles = reactive([
  { id: 'user', name: '普通用户', desc: '学生/教师账号', icon: 'el-icon-user' },
  {
    id: 'admin',
    name: '管理员',
    desc: '场馆管理员账号',
    icon: 'el-icon-s-management'
  },
  {
    id: 'superAdmin',
    name: '超级管理员',
    desc: '系统超级管理员',
    icon: 'el-icon-s-platform'
  }
])

// 选中的角色
const selectedRole = ref('')

// 表单验证规则
const loginRules = ref({
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  passwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.toLowerCase() !== verifyCodeActual.value.toLowerCase()) {
          callback(new Error('验证码不正确'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 加载状态
const loading = ref(false)

// 验证码相关
const verifyCodeImage = ref('')
const verifyCodeActual = ref('')

// 选择角色
const selectRole = (roleId) => {
  selectedRole.value = roleId
  loginForm.role = roleId
}

// 获取角色名称
const getRoleName = () => {
  const role = roles.find((r) => r.id === selectedRole.value)
  return role ? role.name : ''
}

// 获取角色占位符文本
const getRolePlaceholderText = () => {
  const role = roles.find((r) => r.id === selectedRole.value)
  if (!role) return '请输入账号'

  switch (role.id) {
    case 'user':
      return '请输入用户账号'
    case 'admin':
      return '请输入管理员账号'
    case 'superAdmin':
      return '请输入超级管理员账号'
    default:
      return '请输入账号'
  }
}

// 下一步
const nextStep = () => {
  if (!selectedRole.value) {
    ElMessage.warning('请选择您的身份')
    return
  }

  currentStep.value++
  refreshVerifyCode() // 进入下一步时刷新验证码
}

// 上一步
const prevStep = () => {
  currentStep.value--
}

// 生成随机验证码
const generateVerifyCode = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 创建验证码图片
const createVerifyCodeImage = (text) => {
  const width = 120
  const height = 40

  // 创建干扰线
  let lines = ''
  for (let i = 0; i < 3; i++) {
    const x1 = Math.random() * width
    const y1 = Math.random() * height
    const x2 = Math.random() * width
    const y2 = Math.random() * height
    const color = `rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100})`
    lines += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${color}" stroke-width="1" />`
  }

  // 创建文字
  let textElements = ''
  for (let i = 0; i < text.length; i++) {
    const char = text.charAt(i)
    const x = 20 + i * 20 + Math.random() * 5
    const y = 25 + Math.random() * 10
    const rotate = -10 + Math.random() * 20
    const color = `rgb(${Math.random() * 150}, ${Math.random() * 150}, ${Math.random() * 150})`
    textElements += `<text x="${x}" y="${y}" font-size="20" transform="rotate(${rotate}, ${x}, ${y})" fill="${color}" font-family="Arial, sans-serif">${char}</text>`
  }

  // 组合SVG
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
    <rect width="100%" height="100%" fill="#f5f7fa" />
    ${lines}
    ${textElements}
  </svg>`

  // 转换为Base64
  return btoa(unescape(encodeURIComponent(svg)))
}

// 刷新验证码
const refreshVerifyCode = () => {
  loginForm.verifyCode = ''
  verifyCodeActual.value = generateVerifyCode()
  verifyCodeImage.value = createVerifyCodeImage(verifyCodeActual.value)
}

// 登录处理
const handleLogin = () => {
  // 创建加载实例
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '登录中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    loginFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        if (
          loginForm.verifyCode.toLowerCase() !==
          verifyCodeActual.value.toLowerCase()
        ) {
          ElMessage.error('验证码不正确，已刷新')
          refreshVerifyCode()
          loading.value = false
          return
        }
        const {
          data: { data }
        } = await userLoginService(loginForm)
        console.log(data)

        // 检查用户选择身份信息是否与系统返回值相对应
        const roleVal = getRoleName()
        if (
          (data.user.type === 4 && roleVal != '超级管理员') ||
          (data.user.type === 3 && roleVal != '管理员')
        ) {
          ElMessage.error('身份不匹配，请重新选择身份信息')
        } else {
          // 模拟登录处理时间，增强用户体验
          await new Promise((resolve) => setTimeout(resolve, 500))
          // 存储用户信息
          userStore.setUser(data.user)
          userStore.setToken(data.token)
          // 导航到首页
          if (data.user.type === 4) {
            router.push('/index')
          } else {
            router.push('/mobile/index')
          }
          // 显示成功消息
          ElMessage.success({
            message: '登录成功',
            duration: 1500,
            showClose: true
          })
        }
        // 重置表单
        loginFormRef.value.resetFields()
        currentStep.value = 0
        selectedRole.value = ''
        loading.value = false
        // 实际项目中这里应该有跳转逻辑
        // router.push({ name: 'Dashboard', params: { role: loginForm.role } })
      } else {
        loading.value = false
        loadingInstance.close()
        return false
      }
    })
  } catch (error) {
    loading.value = false
    loadingInstance.close()
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    // 确保关闭加载效果
    loadingInstance.close()
    loading.value = false
  }
}

// 页面加载时初始化
onMounted(() => {
  refreshVerifyCode()
  userStore.setUser({})
  userStore.setToken('')
})
</script>

<template>
  <div class="login-container">
    <!-- 动态渐变背景 -->
    <div class="bg-gradient"></div>

    <!-- 浮动装饰元素 -->
    <div class="floating-elements">
      <div class="float-element element-1"></div>
      <div class="float-element element-2"></div>
      <div class="float-element element-3"></div>
      <div class="float-element element-4"></div>
    </div>

    <!-- 主内容区 -->
    <div class="content-wrapper">
      <!-- 居中面板 -->
      <div class="centered-panel">
        <!-- 左侧系统介绍 -->
        <div class="panel-left">
          <div class="panel-content">
            <div class="art-title">
              <h1>校园 e 站通</h1>
              <p class="sub-title">华交场馆管控一体化平台</p>
            </div>

            <div class="system-info">
              <p class="system-desc">
                校园e站通是华东交通大学为提升场馆资源管理效率和服务质量，打造的智能化场馆管控平台。通过先进的信息化技术，实现场馆预约、设备管理、数据分析等功能的一体化管理。
              </p>

              <div class="features">
                <div class="feature-item">
                  <div class="feature-icon">
                    <i class="el-icon-s-marketing"></i>
                  </div>
                  <div class="feature-content">
                    <h3>智能场馆预约</h3>
                    <p>实时查看场馆占用状态，一键预约空闲场地</p>
                  </div>
                </div>

                <div class="feature-item">
                  <div class="feature-icon">
                    <i class="el-icon-s-data"></i>
                  </div>
                  <div class="feature-content">
                    <h3>资源动态管理</h3>
                    <p>设备使用记录追踪，耗材库存智能预警</p>
                  </div>
                </div>

                <div class="feature-item">
                  <div class="feature-icon">
                    <i class="el-icon-s-check"></i>
                  </div>
                  <div class="feature-content">
                    <h3>使用数据分析</h3>
                    <p>场馆使用频率统计，资源优化配置建议</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧登录区 -->
        <div class="panel-right">
          <div class="login-box">
            <div class="login-header">
              <div class="logo">
                <img src="@/assets/login-avatar.jpg" alt="校园e站通logo" />
              </div>
              <h2 class="login-title">欢迎登录</h2>
            </div>

            <!-- 优化后的时间线 -->
            <div class="enhanced-timeline">
              <div
                class="timeline-step"
                :class="{ 'is-active': currentStep === 0 }"
              >
                <div class="step-circle">
                  <i class="el-icon-user-solid"></i>
                </div>
                <div class="step-text">
                  <div class="step-title">选择身份</div>
                  <div class="step-desc">请选择您的用户角色</div>
                </div>
                <div
                  class="step-line"
                  :class="{ 'line-active': currentStep >= 1 }"
                ></div>
              </div>

              <div
                class="timeline-step"
                :class="{ 'is-active': currentStep === 1 }"
              >
                <div class="step-circle">
                  <i class="el-icon-document"></i>
                </div>
                <div class="step-text">
                  <div class="step-title">账号登录</div>
                  <div class="step-desc">请输入账号密码登录</div>
                </div>
              </div>
            </div>

            <!-- 登录步骤内容 -->
            <div class="login-steps">
              <!-- 步骤1：选择身份 -->
              <div class="login-step" v-show="currentStep === 0">
                <h3 class="step-title">请选择您的身份</h3>
                <div class="role-options">
                  <el-card
                    v-for="role in roles"
                    :key="role.id"
                    :class="{ 'role-card-selected': selectedRole === role.id }"
                    @click="selectRole(role.id)"
                    shadow="hover"
                  >
                    <div class="role-content">
                      <div class="role-icon">
                        <i :class="role.icon"></i>
                      </div>
                      <div class="role-info">
                        <div class="role-name">{{ role.name }}</div>
                      </div>
                      <div class="role-desc">{{ role.desc }}</div>
                    </div>
                  </el-card>
                </div>

                <div class="step-actions">
                  <el-button
                    type="primary"
                    @click="nextStep"
                    :loading="loading"
                    :disabled="!selectedRole"
                  >
                    下一步
                  </el-button>
                </div>
              </div>

              <!-- 步骤2：账号密码 -->
              <div class="login-step" v-show="currentStep === 1">
                <h3 class="step-title">请输入登录信息</h3>
                <el-form
                  ref="loginFormRef"
                  :model="loginForm"
                  :rules="loginRules"
                  class="login-form"
                  label-position="left"
                  label-width="0px"
                >
                  <el-form-item prop="account">
                    <el-input
                      :prefix-icon="User"
                      v-model="loginForm.account"
                      :placeholder="getRolePlaceholderText()"
                      clearable
                    >
                    </el-input>
                  </el-form-item>

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

                  <el-form-item prop="verifyCode">
                    <div class="verify-code-wrapper">
                      <el-input
                        :prefix-icon="Bell"
                        v-model="loginForm.verifyCode"
                        placeholder="请输入验证码"
                        clearable
                        style="width: 70%; margin-right: 15px"
                      >
                      </el-input>
                      <div
                        class="verify-code"
                        @click="refreshVerifyCode"
                        :style="{
                          backgroundImage: `url('data:image/svg+xml;base64,${verifyCodeImage}')`
                        }"
                      >
                        <span v-if="!verifyCodeImage">点击刷新</span>
                      </div>
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <el-checkbox v-model="loginForm.rememberMe"
                      >记住密码</el-checkbox
                    >
                    <el-link
                      href="#"
                      type="primary"
                      class="float-right"
                      @click="router.push('/password/reset')"
                      >忘记密码?</el-link
                    >
                  </el-form-item>

                  <div class="step-actions">
                    <el-button @click="prevStep">上一步</el-button>
                    <el-button
                      type="primary"
                      @click="handleLogin"
                      :loading="loading"
                    >
                      登录
                    </el-button>
                  </div>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="footer">
      <p>© 2025 华东交通大学 | 校园e站通・华交场馆管控一体化平台</p>
      <p>建议使用Chrome、Firefox、Edge等现代浏览器访问本系统</p>
    </div>
  </div>
</template>

<style scoped>
/* 基础样式 */
.login-container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  overflow: hidden;
}

/* 动态渐变背景 */
.bg-gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #1e88e5, #43a047, #00acc1);
  background-size: 200% 200%;
  animation: gradientMove 15s ease infinite;
}

@keyframes gradientMove {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* 浮动装饰元素 */
.floating-elements {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.float-element {
  position: absolute;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: float 15s infinite ease-in-out;
}

.element-1 {
  width: 200px;
  height: 200px;
  top: -100px;
  left: -100px;
  animation-delay: 0s;
}

.element-2 {
  width: 150px;
  height: 150px;
  bottom: -75px;
  right: -75px;
  animation-delay: 2s;
}

.element-3 {
  width: 100px;
  height: 100px;
  top: 30%;
  right: 15%;
  animation-delay: 4s;
}

.element-4 {
  width: 120px;
  height: 120px;
  bottom: 20%;
  left: 10%;
  animation-delay: 6s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 主内容区 */
.content-wrapper {
  position: relative;
  z-index: 1;
  width: 100%;
  min-height: 95vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 居中面板 */
.centered-panel {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

/* 左侧面板 - 系统介绍 */
.panel-left {
  flex: 1;
  padding: 40px;
  background: linear-gradient(135deg, #1e88e5, #00acc1);
  color: white;
  display: flex;
  align-items: center;
}

.panel-content {
  width: 100%;
}

.art-title {
  text-align: center;
  margin-bottom: 40px;
}

.art-title h1 {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 10px;
  position: relative;
  display: inline-block;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.art-title h1::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60%;
  height: 3px;
  background: rgba(255, 255, 255, 0.5);
}

.sub-title {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 20px;
  letter-spacing: 1px;
}

.system-info {
  margin-bottom: 40px;
}

.system-desc {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 30px;
  text-align: center;
}

.features {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.feature-item:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateX(5px);
}

.feature-icon {
  font-size: 24px;
  margin-right: 15px;
  width: 30px;
  text-align: center;
}

.feature-content h3 {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.feature-content p {
  font-size: 14px;
  opacity: 0.8;
}

.system-image {
  display: none;
  margin-top: 40px;
  text-align: center;
}

.system-image img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

/* 右侧面板 - 登录区 */
.panel-right {
  flex: 1;
  padding: 40px;
  display: flex;
  align-items: center;
}

.login-box {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

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

.logo {
  margin-bottom: 20px;
}

.logo img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.login-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

/* 优化后的时间线 */
.enhanced-timeline {
  display: flex;
  margin-bottom: 40px;
}

.timeline-step {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.step-circle {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #e4e7ed;
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  z-index: 2;
  transition: all 0.3s ease;
}

.is-active .step-circle {
  background-color: #1e88e5;
  color: white;
  transform: scale(1.1);
  box-shadow: 0 0 15px rgba(30, 136, 229, 0.5);
}

.step-text {
  margin-top: 10px;
  text-align: center;
}

.step-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.step-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.is-active .step-title {
  color: #1e88e5;
}

.is-active .step-desc {
  color: #666;
}

.step-line {
  position: absolute;
  top: 24px;
  left: 50%;
  width: 100%;
  height: 2px;
  background-color: #e4e7ed;
  z-index: 1;
}

.line-active {
  background-color: #1e88e5;
  transition: all 0.5s ease;
}

/* 登录步骤 */
.login-step {
  min-height: 250px;
}

.step-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
  color: #303133;
}

/* 角色选项 */
.role-options {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
  margin-bottom: 30px;
}

.role-card-selected {
  border-color: #1e88e5 !important;
  background-color: #f5f7fa;
}

.role-card-selected .role-icon i {
  color: #1e88e5;
}

.role-card-selected .role-name {
  color: #1e88e5;
}

.role-card-selected::after {
  content: '✓';
  position: absolute;
  right: 10px;
  top: 10px;
  width: 16px;
  height: 16px;
  background-color: #1e88e5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.role-content {
  display: flex;
  align-items: center;
}

.role-icon {
  font-size: 24px;
  margin-right: 15px;
  width: 30px;
  text-align: center;
}

.role-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.role-desc {
  font-size: 12px;
  color: #909399;
  margin-left: auto;
  margin-right: 5vw;
}

.step-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.step-actions button {
  flex: 1;
  margin: 0 5px;
}

.verify-code-wrapper {
  display: flex;
  align-items: center;
}

.verify-code {
  flex: 1;
  height: 40px;
  width: 10vw;
  border-radius: 4px;
  background-color: #f5f7fa;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}
.float-right {
  margin-left: 15vw;
}
/* 页脚 */
.footer {
  color: white;
  text-align: center;
  opacity: 0.8;
  font-size: 14px;
  margin-top: 20px;
}

/* 响应式布局 */
@media (min-width: 768px) {
  .centered-panel {
    flex-direction: row;
  }

  .panel-left,
  .panel-right {
    min-height: 500px;
  }

  .features {
    grid-template-columns: 1fr;
  }

  .system-image {
    display: block;
  }

  .enhanced-timeline {
    margin-bottom: 50px;
  }

  .step-line {
    width: calc(100% - 48px);
  }
}

@media (min-width: 1024px) {
  .features {
    grid-template-columns: 1fr;
  }

  .art-title h1 {
    font-size: 42px;
  }

  .sub-title {
    font-size: 20px;
  }
}
</style>
