<template>
  <div>
    <Echart
      id="centreLeft2Chart"
      ref="centreLeft2ChartRef"
      :options="options"
      height="360px"
      width="330px"
    ></Echart>
  </div>
</template>

<script>
import Echart from '@/common/echart';

export default {
  data() {
    return {
      options: {},
      intervalId: null,
      preSelectMapIndex: 0
    };
  },
  components: {
    Echart,
  },
  props: {
    cdata: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    cdata: {
      handler(newData) {
        this.initMap(newData);
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    initMap(newData) {
    console.log('接收到的地图数据:', newData); // 添加调试日志
    
    // 设置各份的中心点坐标（用于散点图）
    const geoCoordMap = {
      '北京市': [116.405285, 39.904989],
      '天津市': [117.190182, 39.125596],
      '河北省': [114.502461, 38.045474],
      '山西省': [112.549248, 37.857014],
      '内蒙古自治区': [111.670801, 40.818311],
      '辽宁省': [123.429096, 41.796767],
      '吉林省': [125.3245, 43.886841],
      '黑龙江省': [126.642464, 45.756967],
      '上海市': [121.472644, 31.231706],
      '江苏省': [118.767413, 32.041544],
      '浙江省': [120.153576, 30.287459],
      '安徽省': [117.283042, 31.86119],
      '福建省': [119.306239, 26.075302],
      '江西省': [115.892151, 28.676493],
      '山东省': [117.000923, 36.675807],
      '河南省': [113.665412, 34.757975],
      '湖北省': [114.298572, 30.584355],
      '湖南省': [112.982279, 28.19409],
      '广东省': [113.280637, 23.125178],
      '广西壮族自治区': [108.320004, 22.82402],
      '海南省': [110.33119, 20.031971],
      '重庆市': [106.504962, 29.533155],
      '四川省': [104.065735, 30.659462],
      '贵州省': [106.713478, 26.578343],
      '云南省': [102.712251, 25.040609],
      '西藏自治区': [91.132212, 29.660361],
      '陕西省': [108.948024, 34.263161],
      '甘肃省': [103.823557, 36.058039],
      '青海省': [101.778916, 36.623178],
      '宁夏回族自治区': [106.278179, 38.46637],
      '新疆维吾尔自治区': [87.617733, 43.792818],
      '台湾': [121.509062, 25.044332],
      '香港': [114.173355, 22.320048],
      '澳门': [113.54909, 22.198951]
    };

    // 确保数据格式正确 - 处理可能的数据问题
    const processedData = (newData || []).map(item => {
      // 确保每个数据项都有必要的字段
      return {
        name: item.name,
        value: item.value || 0,
        onlineCount: item.onlineCount || 0,
        offlineCount: item.offlineCount || 0
      };
    });

    console.log('处理后的地图数据:', processedData); // 调试日志

    // 生成散点数据
    let convertData = (data) => {
      let scatterData = [];
      for (var i = 0; i < data.length; i++) {
        if (!data[i] || !data[i].name) continue;
        
        var geoCoord = geoCoordMap[data[i].name];
        if (geoCoord) {
          scatterData.push({
            name: data[i].name,
            value: geoCoord.concat(data[i].value || 0),
            onlineCount: data[i].onlineCount || 0,
            offlineCount: data[i].offlineCount || 0
          });
        } else {
          console.warn(`未找到 ${data[i].name} 的坐标信息`);
        }
      }
      return scatterData;
    };

    // 修复配置
    this.options = {
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#00f2fc',
        borderWidth: 1,
        textStyle: {
          fontSize: 12,
          lineHeight: 18,
          color: '#fff'
        },
        formatter: (params) => {
          console.log('Tooltip params:', params); // 调试日志
          
          if (!params || !params.data) {
            return '<div style="color: #999;">暂无数据</div>';
          }
          
          const data = params.data;
          const name = data.name || '未知区域';
          const total = data.value || 0;
          const online = data.onlineCount || 0;
          const offline = data.offlineCount || 0;
          
          return `
            <div style="font-size: 13px; color: #fff; margin-bottom: 4px;">
              <strong>${name}</strong>
            </div>
            <div style="font-size: 12px; color: #ccc; margin-bottom: 2px;">
              设备总数: <strong style="color: #ffd700">${total}台</strong>
            </div>
            <div style="font-size: 12px; color: #19be6b; margin-bottom: 2px;">
              在线设备: <strong>${online}台</strong>
            </div>
            <div style="font-size: 12px; color: #ed3f14;">
              离线设备: <strong>${offline}台</strong>
            </div>
          `;
        }
      },
      visualMap: {
        min: 0,
        max: this.getMaxValue(processedData),
        show: true,
        left: 'left',
        top: 'bottom',
        text: ['高', '低'],
        seriesIndex: [0],
        inRange: {
          color: ['#e0f7ff', '#0066cc']
        },
        textStyle: {
          color: '#fff'
        }
      },
      geo: {
        show: true,
        map: 'china',
        roam: false,
        zoom: 1.2,
        top: '10%',
        left: '5%',
        right: '5%',
        label: {
          emphasis: {
            show: false
          }
        },
        itemStyle: {
          normal: {
            areaColor: 'rgba(19, 54, 162, 0.5)',
            borderColor: 'rgba(0, 242, 252, 0.3)',
            borderWidth: 1
          },
          emphasis: {
            areaColor: 'rgba(79, 127, 255, 0.8)',
            borderColor: 'rgba(0, 242, 252, 0.6)',
            borderWidth: 2
          }
        },
        emphasis: {
          itemStyle: {
            areaColor: '#4f7fff'
          },
          label: {
            show: false
          }
        }
      },
      series: [
        {
          // 主地图系列 - 负责区域颜色和悬停
          name: '设备数量',
          type: 'map',
          map: 'china', // 使用 map 而不是 mapType
          geoIndex: 0,
          data: processedData, // 使用处理后的数据
          emphasis: {
            itemStyle: {
              areaColor: '#4f7fff'
            },
            label: {
              show: false
            }
          }
        },
        {
          // 散点效果系列
          name: '散点效果',
          type: 'effectScatter',
          coordinateSystem: 'geo',
          data: convertData(processedData),
          symbolSize: function(val) {
            return Math.max(6, Math.min(15, (val[2] || 0) / 10));
          },
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke',
            scale: 3,
            period: 4
          },
          hoverAnimation: false,
          itemStyle: {
            color: '#99FBFE',
            shadowBlur: 10,
            shadowColor: '#fff'
          },
          zlevel: 1,
          tooltip: {
            show: false
          }
        }
      ]
    };
    
    console.log('ECharts 配置:', this.options); // 调试日志
    
    // 重新选择区域
    this.$nextTick(() => {
      this.handleMapRandomSelect();
    });
  },

    getMaxValue(data) {
      if (!data || !Array.isArray(data) || data.length === 0) return 10;
      const values = data.map(item => item.value || 0).filter(val => !isNaN(val));
      return values.length > 0 ? Math.max(...values) : 10;
    },

    // 开启定时器
    startInterval() {
      const _self = this;
      const time = 4000;
      if (this.intervalId !== null) {
        clearInterval(this.intervalId);
      }
      this.intervalId = setInterval(() => {
        _self.reSelectMapRandomArea();
      }, time);
    },

    // 重新随机选中地图区域
    reSelectMapRandomArea() {
      const length = this.cdata ? this.cdata.length : 0;
      if (length === 0) return;
      
      this.$nextTick(() => {
        try {
          const map = this.$refs.centreLeft2ChartRef.chart;
          let index = Math.floor(Math.random() * length);
          while (index === this.preSelectMapIndex || index >= length) {
            index = Math.floor(Math.random() * length);
          }
          
          // 高亮新的区域
          map.dispatchAction({
            type: 'highlight',
            seriesIndex: 0, // 地图系列
            dataIndex: index,
          });
          
          // 显示tooltip
          map.dispatchAction({
            type: 'showTip',
            seriesIndex: 0, // 地图系列
            dataIndex: index,
          });
          
          this.preSelectMapIndex = index;
        } catch (error) {
          console.log('地图操作错误:', error)
        }
      });
    },

    handleMapRandomSelect() {
      this.$nextTick(() => {
        try {
          const map = this.$refs.centreLeft2ChartRef.chart;
          const _self = this;
          
          setTimeout(() => {
            _self.reSelectMapRandomArea();
          }, 1000);
          
          // 鼠标悬停在地图区域上的事件
          map.on('mouseover', { seriesIndex: 0 }, function (params) {
            clearInterval(_self.intervalId);
            // 高亮悬停的区域
            map.dispatchAction({
              type: 'highlight',
              seriesIndex: 0,
              dataIndex: params.dataIndex,
            });
            _self.preSelectMapIndex = params.dataIndex;
          });
          
          // 鼠标离开地图区域的事件
          map.on('mouseout', { seriesIndex: 0 }, function () {
            // 取消高亮
            map.dispatchAction({
              type: 'downplay',
              seriesIndex: 0
            });
            _self.startInterval();
          });
          
          this.startInterval();
        } catch (error) {
          console.log('地图事件绑定错误:', error)
        }
      });
    },
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }
};
</script>