<template>
  <div class="inspection-task-map-container">
    <div id="inspectionTaskMap" style="width: 100%; height: 600px;"></div>
  </div>
</template>

<script>
import { queryInspectionTaskDetail } from '@/api/inspection/inspectionPointApi'
import { getCommunityId } from '@/api/community/communityApi'

export default {
  name: 'InspectionTaskMap',
  data() {
    return {
      map: null,
      communityId: '',
      taskPoints: [],
      markers: [],
      texts: [],
      polylines: []
    }
  },
  mounted() {
    this.communityId = getCommunityId()
  },
  methods: {
    loadData(task) {
      console.log('loadData', task)
      this.initMap()
      this.loadTask(task)
    },
    initMap() {
      this.clearAll()

      const center = [116.397128, 39.916527]
      const container = document.getElementById('inspectionTaskMap')
      if (!container) return

      this.map = new window.AMap.Map(container, {
        center: center,
        zoom: 13,
        resizeEnable: true
      })
    },

    async loadTask(task) {
      if (!task || !task.taskId) return

      try {
        const params = {
          communityId: this.communityId,
          taskId: task.taskId,
          page: 1,
          row: 1000
        }

        const response = await queryInspectionTaskDetail(params)
        this.taskPoints = response.data
        this.addPointsToMap(this.taskPoints)
      } catch (error) {
        console.error('获取任务点失败:', error)
        this.$message.error(this.$t('inspectionTaskMap.fetchError'))
      }
    },

    addPointsToMap(points) {
      if (!this.map || !points || points.length === 0) return

      this.clearOverlays()

      const path = []

      points.forEach(point => {
        if (!point.lat || !point.lng) return

        const position = [point.lng, point.lat]
        const isDone = point.state === '20200405'

        // 标记
        const markerIcon = new window.AMap.Icon({
          size: new window.AMap.Size(25, 35),
          imageSize: new window.AMap.Size(25, 35),
          image: isDone ? '/img/inspection_do.png' : '/img/inspection.png'
        })
        const marker = new window.AMap.Marker({
          map: this.map,
          position: position,
          icon: markerIcon
        })
        this.markers.push(marker)

        // 标签
        const text = new window.AMap.Text({
          map: this.map,
          text: point.inspectionName,
          position: position,
          offset: new window.AMap.Pixel(0, 15),
          style: {
            color: isDone ? '#CC0000' : '#3777FF',
            'font-size': '12px',
            'background-color': 'rgba(255,255,255,0.8)',
            'padding': '2px 4px',
            'border-radius': '2px'
          }
        })
        this.texts.push(text)

        path.push(position)
      })

      // 路径 - 双色双层折线模拟描边效果
      if (path.length > 1) {
        // 外层（描边）
        const outerPolyline = new window.AMap.Polyline({
          map: this.map,
          path: path,
          strokeColor: '#FFF',
          strokeWeight: 10,
          strokeOpacity: 1,
          lineJoin: 'round'
        })
        this.polylines.push(outerPolyline)

        // 内层（主线）
        const innerPolyline = new window.AMap.Polyline({
          map: this.map,
          path: path,
          strokeColor: '#3777FF',
          strokeWeight: 6,
          strokeOpacity: 0.9,
          lineJoin: 'round'
        })
        this.polylines.push(innerPolyline)
      }

      if (path.length > 0) {
        this.map.setCenter(path[0])
        this.map.setZoom(16)
      }
    },

    clearAll() {
      this.clearOverlays()
      if (this.map) {
        this.map.destroy()
        this.map = null
      }
    },

    clearOverlays() {
      this.markers.forEach(m => m.setMap(null))
      this.markers = []
      this.texts.forEach(t => t.setMap(null))
      this.texts = []
      this.polylines.forEach(p => p.setMap(null))
      this.polylines = []
    }
  },
  beforeDestroy() {
    this.clearAll()
  }
}
</script>

<style scoped>
.inspection-task-map-container {
  width: 100%;
  height: 100%;
}
</style>
