<template>
  <transition name="slide-fade">
    <div v-if="visible" class="building-progress-card">
      <!-- 顶部标题栏 -->
      <div class="card-header">
        <div class="header-left">
          <i class="el-icon-cpu animated-icon"></i>
          <span class="header-title">正在构建地图</span>
        </div>
        <div class="header-right">
          <el-button
            type="text"
            icon="el-icon-close"
            size="mini"
            class="close-btn"
            @click="handleClose"
            title="隐藏进度卡片"
          />
        </div>
      </div>

      <!-- 地图信息 -->
      <div class="card-body">
        <div class="map-info">
          <div class="info-row">
            <span class="info-label">地图名称:</span>
            <span class="info-value">{{ mapName }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">构建进度:</span>
            <span class="info-value progress-value">{{ progress }}%</span>
          </div>
          <div class="info-row" v-if="buildingTime">
            <span class="info-label">已用时间:</span>
            <span class="info-value time-value">{{ buildingTime }}</span>
          </div>
        </div>

        <!-- 进度条 -->
        <div class="progress-bar">
          <el-progress 
            :percentage="progress" 
            :stroke-width="8"
            :color="progressColor"
            :status="progressStatus"
          />
        </div>

        <!-- 操作按钮 -->
        <div class="card-actions">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-back"
            @click="handleBackToList"
          >
            返回查看进度
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-close"
            @click="handleStopBuilding"
          >
            停止构建
          </el-button>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import { getBuildingState } from '@/utils/map-building-state'

export default {
  name: 'BuildingProgressCard',
  props: {
    // 地图名称
    mapName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      visible: false,
      progress: 0,
      buildingStartTime: null,
      buildingTimeTimer: null
    }
  },
  computed: {
    /**
     * 进度条颜色
     */
    progressColor() {
      if (this.progress < 30) {
        return '#F56C6C' // 红色
      } else if (this.progress < 70) {
        return '#E6A23C' // 橙色
      } else if (this.progress < 100) {
        return '#409EFF' // 蓝色
      } else {
        return '#67C23A' // 绿色
      }
    },
    
    /**
     * 进度条状态
     */
    progressStatus() {
      if (this.progress >= 100) {
        return 'success'
      }
      return null
    },
    
    /**
     * 构建用时（格式化）
     */
    buildingTime() {
      if (!this.buildingStartTime) {
        return null
      }
      
      const elapsed = Date.now() - this.buildingStartTime
      const seconds = Math.floor(elapsed / 1000)
      
      if (seconds < 60) {
        return `${seconds}秒`
      } else if (seconds < 3600) {
        const minutes = Math.floor(seconds / 60)
        const remainSeconds = seconds % 60
        return `${minutes}分${remainSeconds}秒`
      } else {
        const hours = Math.floor(seconds / 3600)
        const minutes = Math.floor((seconds % 3600) / 60)
        return `${hours}小时${minutes}分`
      }
    }
  },
  mounted() {
    // 检查是否有正在构建的地图
    this.checkBuildingState()
    
    // 定时刷新构建状态
    this.startPolling()
    
    // 启动计时器
    this.startBuildingTimeUpdate()
  },
  beforeDestroy() {
    // 清除定时器
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
    }
    if (this.buildingTimeTimer) {
      clearInterval(this.buildingTimeTimer)
    }
  },
  methods: {
    /**
     * 检查构建状态
     */
    checkBuildingState() {
      const state = getBuildingState()
      
      if (state && state.isBuilding && state.mapName === this.mapName) {
        this.visible = true
        this.progress = state.progress || 0
        this.buildingStartTime = state.startTime
        
        console.log('[BuildingProgressCard] 检测到正在构建的地图:', state)
      }
    },
    
    /**
     * 启动轮询（每3秒刷新一次状态）
     */
    startPolling() {
      this.pollingTimer = setInterval(() => {
        this.checkBuildingState()
      }, 3000)
    },
    
    /**
     * 启动构建时间更新（每秒更新）
     */
    startBuildingTimeUpdate() {
      this.buildingTimeTimer = setInterval(() => {
        // 触发计算属性更新
        this.$forceUpdate()
      }, 1000)
    },
    
    /**
     * 关闭卡片
     */
    handleClose() {
      this.$confirm('隐藏后仍可通过工具栏返回按钮查看构建进度，确定要隐藏吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.visible = false
        this.$message.info('已隐藏进度卡片')
      }).catch(() => {
        // 用户取消
      })
    },
    
    /**
     * 返回地图列表查看进度
     */
    handleBackToList() {
      this.$confirm('返回地图列表后可以继续查看构建进度，是否返回？', '返回地图列表', {
        confirmButtonText: '返回',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.$router.push('/map/maplist')
      }).catch(() => {
        // 用户取消
      })
    },
    
    /**
     * 停止构建
     */
    handleStopBuilding() {
      this.$confirm('确认停止构建？停止后将无法继续构建。', '停止构建', {
        type: 'warning',
        confirmButtonText: '确认停止',
        cancelButtonText: '继续构建'
      }).then(() => {
        // 跳转回地图列表，并传递停止构建的标记
        // 地图列表页面会自动检测这个参数并调用 stopBuilding 方法
        this.$router.push({
          path: '/map/maplist',
          query: {
            stopBuilding: 'true',
            mapName: this.mapName
          }
        })
        
        this.$message.info('正在返回地图列表执行停止...')
      }).catch(() => {
        // 用户取消
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 动画效果
.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}

.building-progress-card {
  position: fixed;
  top: 80px;
  right: 20px;
  width: 340px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  overflow: hidden;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 6px 30px rgba(0, 0, 0, 0.2);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .animated-icon {
      font-size: 18px;
      animation: pulse 2s infinite;
    }
    
    .header-title {
      font-size: 14px;
      font-weight: 600;
    }
  }
  
  .header-right {
    .close-btn {
      color: #fff;
      padding: 4px;
      
      &:hover {
        background: rgba(255, 255, 255, 0.2);
        border-radius: 4px;
      }
    }
  }
}

.card-body {
  padding: 16px;
}

.map-info {
  margin-bottom: 12px;
  
  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 13px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .info-label {
      color: #909399;
      font-weight: 400;
    }
    
    .info-value {
      color: #303133;
      font-weight: 500;
      
      &.progress-value {
        color: #409EFF;
        font-size: 16px;
        font-weight: 700;
      }
      
      &.time-value {
        color: #E6A23C;
        font-family: 'Courier New', monospace;
      }
    }
  }
}

.progress-bar {
  margin: 16px 0;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  margin-top: 12px;
  
  .el-button {
    flex: 1;
  }
}

// 脉冲动画
@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
}

// 响应式调整
@media screen and (max-width: 768px) {
  .building-progress-card {
    top: 60px;
    right: 10px;
    width: calc(100% - 20px);
    max-width: 340px;
  }
}

// 暗色主题支持
@media (prefers-color-scheme: dark) {
  .building-progress-card {
    background: #1e1e1e;
    border: 1px solid #333;
    
    .card-body {
      .map-info {
        .info-row {
          .info-label {
            color: #aaa;
          }
          
          .info-value {
            color: #eee;
          }
        }
      }
    }
  }
}
</style>

