<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationBarTitleText: '',
  },
}
</route>
<template>
  <view class="px-4 py-3" @click="closeUserMenu">
    <!-- 顶部栏 -->
    <view class="flex items-center justify-between mb-6">
      <text class="text-lg font-bold">可报名考试</text>
      <view class="flex items-center relative" @click.stop>
        <i class="i-carbon-user-filled text-xl mr-2 text-gray-600"></i>
        <text
          class="text-base font-bold text-gray-700 mr-4 cursor-pointer transition-colors duration-200 hover:text-gray-900"
          @click="toggleUserMenu"
        >
          {{ userName }}
        </text>
        <!-- 用户菜单 -->
        <transition name="menu-fade" mode="out-in">
          <view
            v-if="showUserMenu"
            class="absolute top-full right-0 mt-2 bg-white rounded-lg shadow-lg border border-gray-200 z-50 min-w-32 transform origin-top-right"
          >
            <view
              class="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer border-b border-gray-100 transition-colors duration-150"
              @click="handleModifyPassword"
            >
              修改密码
            </view>
            <view
              class="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer border-b border-gray-100 transition-colors duration-150"
              @click="handleModifyProfile"
            >
              修改个人信息
            </view>
            <view
              class="px-4 py-2 text-sm text-red-600 hover:bg-red-50 cursor-pointer transition-colors duration-150"
              @click="handleLogout"
            >
              退出登录
            </view>
          </view>
        </transition>
      </view>
    </view>

    <!-- 考试列表 -->
    <view class="space-y-6">
      <view
        v-for="exam in examList"
        :key="exam.id"
        class="bg-white rounded-lg shadow-xl p-4 border-2 border-gray-400 relative transition-all duration-300 hover:shadow-2xl hover:-translate-y-1 hover:border-gray-500 cursor-pointer"
        style="
          box-shadow:
            0 8px 16px -4px rgba(0, 0, 0, 0.15),
            0 4px 8px -2px rgba(0, 0, 0, 0.1),
            inset 0 1px 0 rgba(255, 255, 255, 0.1);
        "
        @mouseenter="handleCardHover(exam.id)"
        @mouseleave="handleCardLeave(exam.id)"
      >
        <!-- 第一行：考试名称 -->
        <view class="mb-2">
          <text class="text-xl font-bold text-gray-800">{{ exam.examName }}</text>
        </view>

        <!-- 第二行：考试时间 -->
        <view class="mb-2">
          <text class="text-base text-gray-600">
            {{ formatExamTime(exam.examDate, exam.startTime, exam.endTime) }}
          </text>
        </view>

        <!-- 第三行：考试地点 -->
        <view class="mb-2">
          <text class="text-base text-gray-600">
            {{
              formatExamLocation(exam.provinceName, exam.cityName, exam.address, exam.locationName)
            }}
          </text>
        </view>

        <!-- 第四、五行：空白间距 -->
        <view class="h-4"></view>
        <view class="h-4"></view>

        <!-- 第六行：报名截止信息 -->
        <view class="mb-4">
          <text class="text-sm text-gray-500">报名截止：{{ exam.registrationDeadline }}</text>
        </view>

        <!-- 报名按钮：右下角 -->
        <view class="absolute bottom-4 right-4">
          <button
            class="bg-black text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-800 transition-colors duration-200"
            @click="handleRegisterExam(exam)"
          >
            报名
          </button>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="text-center py-8">
      <text class="text-gray-500">加载中...</text>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && examList.length === 0" class="text-center py-8">
      <text class="text-gray-500">暂无可报名的考试</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { getCanBookExamListAPI } from '@/service/exam'

defineOptions({
  name: 'Home',
})

const userName = ref('')
const showUserMenu = ref(false)
const examList = ref([])
const loading = ref(false)

// 获取考试列表
const getExamList = async () => {
  loading.value = true
  try {
    const res = await getCanBookExamListAPI()
    examList.value = res.data.list || []
  } catch (error) {
    console.error('获取考试列表失败:', error)
    uni.showToast({
      title: '获取考试列表失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 格式化考试时间
const formatExamTime = (examDate: string, startTime: string, endTime: string) => {
  if (!examDate || !startTime || !endTime) return ''
  return `${examDate} ${startTime}-${endTime}`
}

// 格式化考试地点
const formatExamLocation = (
  provinceName: string,
  cityName: string,
  address: string,
  locationName: string,
) => {
  const parts = [provinceName, cityName, address, locationName].filter(Boolean)
  return parts.join(' ')
}

// 报名考试
const handleRegisterExam = (exam: any) => {
  uni.showModal({
    title: '确认报名',
    content: `确定要报名参加"${exam.examName}"吗？`,
    success: (res) => {
      if (res.confirm) {
        // TODO: 调用报名接口
        uni.showToast({
          title: '报名成功',
          icon: 'success',
        })
      }
    },
  })
}

// 卡片hover效果
const handleCardHover = (examId: string) => {
  // 可以在这里添加额外的hover逻辑，比如改变按钮样式等
  console.log('卡片hover:', examId)
}

const handleCardLeave = (examId: string) => {
  // 可以在这里添加离开时的逻辑
  console.log('卡片离开:', examId)
}

// 切换用户菜单
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value
}

// 关闭用户菜单
const closeUserMenu = () => {
  showUserMenu.value = false
}

// 修改密码
const handleModifyPassword = () => {
  showUserMenu.value = false
  uni.navigateTo({
    url: '/pages/user/modify-password',
  })
}

// 修改个人信息
const handleModifyProfile = () => {
  showUserMenu.value = false
  uni.navigateTo({
    url: '/pages/user/profile',
  })
}

// 退出登录
const handleLogout = () => {
  showUserMenu.value = false
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除本地存储
        uni.removeStorageSync('token')
        uni.removeStorageSync('loginData')
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/login/index',
        })
      }
    },
  })
}

onLoad(() => {
  // 获取本地存储的用户昵称
  try {
    const loginData = uni.getStorageSync('loginData')
    userName.value = loginData.user.nickName
  } catch (e) {
    userName.value = ''
  }

  // 获取考试列表
  getExamList()
})

// 下拉刷新
onPullDownRefresh(() => {
  getExamList().then(() => {
    uni.stopPullDownRefresh()
  })
})
</script>

<style scoped>
/* 菜单淡入淡出动画 */
.menu-fade-enter-active,
.menu-fade-leave-active {
  transition: all 0.2s ease-in-out;
}

.menu-fade-enter-from {
  opacity: 0;
  transform: scale(0.95) translateY(-10px);
}

.menu-fade-leave-to {
  opacity: 0;
  transform: scale(0.95) translateY(-10px);
}

.menu-fade-enter-to,
.menu-fade-leave-from {
  opacity: 1;
  transform: scale(1) translateY(0);
}
</style>
