<template>
  <div class="map-detail" v-if="map">
    <div class="back-button">
      <button @click="goBack" class="back-btn">
        <span class="back-icon">←</span> 返回列表
      </button>
    </div>
    <div class="map-header">
      <h1>{{ map.chinese_name }}</h1>
      <p class="author">作者: {{ map.user }}</p>
    </div>
    
    <div class="map-content">
      <div class="map-image">
        <img :src="map.img_file" :alt="map.chinese_name">
      </div>
      <div class="map-info">
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">下载次数</span>
            <span class="info-value">{{ map.download_count }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">收藏次数</span>
            <span class="info-value">{{ map.favourite_count }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">玩家数量</span>
            <span class="info-value">{{ map.player_count }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">创建时间</span>
            <span class="info-value">{{ formatDate(map.create_time) }}</span>
          </div>
          <div>
            <span class="info-label">地图评分</span>
            <span class="info-value">{{ mapRating ? mapRating.toFixed(1) : '暂无评分' }}</span>
          </div>
        </div>
        
        <div class="tags">
          <h3>标签</h3>
          <div class="tag-list">
            <span v-for="tag in map.tags" :key="tag" class="tag">{{ tag }}</span>
          </div>
        </div>
        
        <div class="actions">
          <a :href="map.zip_file" class="download-btn" download @click="handleDownload">下载地图</a>
          <a 
            class="score-btn" 
            :class="{ 'disabled': userMapInfo && userMapInfo.is_rewarded }"
            @click="handleScoreClick"
          >
            {{ userMapInfo && userMapInfo.is_rewarded ? '已评分' : '地图评分' }}
          </a>
        </div>
      </div>
    </div>
    
    <!-- 评分弹窗 -->
    <div v-if="showScoreDialog" class="score-dialog">
      <div class="dialog-overlay" @click="showScoreDialog = false"></div>
      <div class="dialog-content">
        <div class="dialog-header">
          <h2>评分</h2>
          <button class="close-btn" @click="showScoreDialog = false">&times;</button>
        </div>
        <div class="dialog-body">
          <div class="score-section">
            <h3>地图评分</h3>
            <div class="rating">
              <span 
                v-for="star in 5" 
                :key="'map-'+star" 
                class="star"
                :class="{ active: star <= mapScore }"
                @click="mapScore = star"
              >★</span>
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="showScoreDialog = false">取消</button>
          <button class="submit-btn" @click="submitScores">提交评分</button>
        </div>
      </div>
    </div>
    <!-- 添加错误弹窗 -->
    <ErrorDialog
      :visible="showError"
      :title="errorTitle"
      :message="errorMessage"
      @close="handleErrorClose"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getMapDetail } from '../../api/maps.js'
import { submitMapReward, updateUserDownloadMapInfo, getUserMapInfo, getAppointMapRating } from '../../api/centre_maps.js'
import { hasValidToken } from '../../utils/jwt'
import ErrorDialog from '@/components/ErrorDialog.vue'

const route = useRoute()
const router = useRouter()
const map = ref(null)
const mapRating = ref(null)

// 错误弹窗相关
const showError = ref(false)
const errorTitle = ref('')
const errorMessage = ref('')
const pendingAction = ref(null)

const showErrorMessage = (message, title = '', action = null) => {
  errorMessage.value = message
  errorTitle.value = title
  showError.value = true
  pendingAction.value = action
}

const handleErrorClose = () => {
  showError.value = false
  if (pendingAction.value) {
    pendingAction.value()
    pendingAction.value = null
  }
}

// 评分相关的响应式变量
const showScoreDialog = ref(false)
const mapScore = ref(0)
const hasDownloaded = ref(false)
const userMapInfo = ref(null)

// 获取地图评分
const fetchMapRating = async () => {
  try {
    const ratingData = await getAppointMapRating(map.value.name)
    mapRating.value = ratingData.rewards
  } catch (error) {
    console.error('获取地图评分失败:', error)
  }
}

// 处理下载点击
const handleDownload = async () => {
  try {
    await updateUserDownloadMapInfo(map.value.name)
    hasDownloaded.value = true
    // 重新获取用户地图信息
    await fetchUserMapInfo()
  } catch (error) {
    console.error('更新下载信息失败:', error)
    // 即使更新失败，也允许用户继续操作
    hasDownloaded.value = true
  }
}

// 获取用户地图信息
const fetchUserMapInfo = async () => {
  if (!hasValidToken()) return
  
  try {
    userMapInfo.value = await getUserMapInfo(map.value.name)
    hasDownloaded.value = userMapInfo.value.is_download
  } catch (error) {
    console.error('获取用户地图信息失败:', error)
  }
}

// 处理评分点击
const handleScoreClick = () => {
  // 如果已经评分，直接返回
  if (userMapInfo.value && userMapInfo.value.is_rewarded) {
    return
  }
  
  if (!hasValidToken()) {
    showErrorMessage('请先登录后再进行评分', '', () => {
      router.push({
        path: '/backend/login',
        query: { redirect: route.fullPath }
      })
    })
    return
  }
  
  if (!hasDownloaded.value) {
    showErrorMessage('请先下载地图后再进行评分')
    return
  }
  
  showScoreDialog.value = true
}

const fetchMapDetail = async () => {
  try {
    map.value = await getMapDetail(route.params.id)
    // 获取地图详情后，获取用户地图信息和地图评分
    await Promise.all([
      fetchUserMapInfo(),
      fetchMapRating()
    ])
  } catch (error) {
    console.error('获取地图详情失败:', error)
    showErrorMessage('获取地图详情失败，请稍后重试')
  }
}

const goBack = () => {
  router.back()
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 提交评分
const submitScores = async () => {
  if (mapScore.value === 0) {
    showErrorMessage('请为地图进行评分')
    return
  }
  
  try {
    // 调用评分 API
    await submitMapReward(map.value.name, mapScore.value)
    
    // 关闭弹窗并重置表单
    showScoreDialog.value = false
    mapScore.value = 0
    
    // 重新获取用户地图信息和地图评分
    await Promise.all([
      fetchUserMapInfo(),
      fetchMapRating()
    ])
    
    showErrorMessage('评分成功！')
  } catch (error) {
    console.error('评分失败:', error)
    showErrorMessage('评分失败，请稍后重试')
  }
}

onMounted(() => {
  fetchMapDetail()
})
</script>

<style scoped>
.map-detail {
  padding: 15px;
  max-width: 1200px;
  margin: 0 auto;
}

.back-button {
  margin-bottom: 15px;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  color: #333;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
}

.back-btn:hover {
  background: #e9ecef;
  border-color: #d0d0d0;
}

.back-icon {
  margin-right: 6px;
  font-size: 16px;
}

.map-header {
  margin-bottom: 20px;
}

.map-header h1 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
}

.author {
  color: #666;
  margin-top: 5px;
  font-size: 0.9rem;
}

.map-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

@media (min-width: 768px) {
  .map-content {
    flex-direction: row;
  }
  
  .map-image {
    flex: 1;
  }
  
  .map-info {
    flex: 1;
  }
}

.map-image img {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.map-info {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 0.8rem;
  color: #666;
}

.info-value {
  font-size: 1rem;
  font-weight: 500;
  color: #333;
}

.tags {
  margin-bottom: 20px;
}

.tags h3 {
  margin-bottom: 10px;
  font-size: 1.1rem;
  color: #333;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  background: #e9ecef;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  color: #495057;
}

.download-btn {
  display: inline-block;
  width: 100%;
  padding: 12px;
  background: #007bff;
  color: white;
  text-align: center;
  text-decoration: none;
  border-radius: 5px;
  transition: background 0.2s;
  font-size: 1rem;
}

.download-btn:hover {
  background: #0056b3;
}

.score-btn {
  display: inline-block;
  width: 100%;
  padding: 12px;
  background: #a8d1fb;
  color: white;
  text-align: center;
  text-decoration: none;
  border-radius: 5px;
  transition: background 0.2s;
  font-size: 1rem;
}

.score-btn:hover {
  background: #6c8bb9;
}

.score-btn.disabled {
  background: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
}

.score-btn.disabled:hover {
  background: #ccc;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

@media (max-width: 480px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .map-header h1 {
    font-size: 1.3rem;
  }
  
  .author {
    font-size: 0.85rem;
  }
}

/* 评分弹窗样式 */
.score-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1001;
}

.dialog-content {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  z-index: 1002;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.dialog-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0 5px;
}

.score-section {
  margin-bottom: 20px;
}

.score-section h3 {
  margin: 0 0 10px;
  font-size: 1rem;
  color: #444;
}

.rating {
  display: flex;
  gap: 8px;
  margin-bottom: 10px;
}

.star {
  font-size: 24px;
  cursor: pointer;
  color: #ddd;
  transition: color 0.2s;
}

.star:hover,
.star.active {
  color: #ffd700;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f5f5f5;
  border: 1px solid #ddd;
  color: #666;
}

.cancel-btn:hover {
  background: #eee;
}

.submit-btn {
  background: #007bff;
  border: 1px solid #0056b3;
  color: white;
}

.submit-btn:hover {
  background: #0056b3;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .dialog-content {
    width: 95%;
    padding: 15px;
  }
  
  .star {
    font-size: 20px;
  }
}
</style>