<template>
  <div class="container">
    <div :id="mapId" class="map" :style="{ height: height, width: width }"></div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import resize from "../../../components/Charts/mixins/resize";
import strMap from "../mixins/strMap.js";

export default {
  name: "emap",
  mixins: [resize, strMap],
  props: {
    width: String,
    height: String,
    mapData: {
      type: Array,
      default: () => {
        return [{ apiData: 0 }];
      },
    },
    selectArea: String,
    title: {
      type: String,
    },
    mapId:String,
  },
  data() {
    return {
      activeIndex: 0,
      clickIndex: 100,
      clickName:"",
      chart: null,
      // mapList: [], //地图json文件
      selectAreaName: "温州市",
      noneArea: "",
      zoom: 1,
      geoTop: "middle",
      mode: 100,
      timer:{},
    };
  },
  watch: {
    //接口数据
    mapData: {
      deep: true,
      handler(val) {
        this.handleData(val, this.selectAreaName, this.mapList);
      },
      // activeIndex: {
      //   handler(i) {
      //     this.$emit("handleChange", areaData[i]);
      //   },
      //   immediate: true,
      // },
    },
    selectArea(val) {
      this.selectAreaName = this.mapDistriction(val);
    },
    mapList(val){
      clearInterval(this.timer)
      this.activeIndex=0
      this.handleData(this.mapData, this.selectAreaName, val);
    }
  },
  computed:{
    mapList(){
      try{
        return require(`./map/${this.selectAreaName}.json`)
      }
      catch{
        return require(`./map/温州市.json`)
      }
    }
  },
  methods: {
    //选择json文件
    // handleMapJson(areaName, mapData) {
    //   console.log('areaName',areaName)
    //   clearInterval(this.timer)
    //   this.activeIndex=0
    //   try {
    //     this.mapList = require(`./map/${areaName}.json`);
    //   } catch {
    //     this.mapList = require(`./map/温州市.json`);
    //     this.mapClick(areaName, 0); //外部title仍显示温州市
    //     areaName = "温州市";
    //   }
    //   this.handleData(mapData, areaName, this.mapList);
    // },
    //地区数据处理
    handleData(mapData, areaName, mapList) {
      if (!mapData || !areaName || !mapList) {
        return;
      }
      let areaData = [];
      let distCode = "";
      let distValue = 0;
      mapList.features.forEach((data) => {
        distValue = 0;
        distCode = this.mapDict(data.properties.name,this.selectArea);
        if (mapData && mapData.length > 0) {
          mapData.forEach((v) => {
            if (v && v.addressCode == distCode) {
              distValue = Number(v.apiData);
            }
          });
        }
        areaData.push({
          name: data.properties.name || "",
          value: distValue,
          code: distCode,
          center: data.properties.centroid || [],
        });
      });
      this.initMap(areaData, areaName, mapList);
    },
    //地图渲染
    initMap(areaData, areaName, mapList) {
      if (!areaData || !areaName || !mapList) {
        return;
      }
      const this_ = this;

      const myChart = echarts.init(document.getElementById(this.mapId));
      this.chart = myChart; //混入resize
      if (areaName == "温州市") {
        this.mode = 1;
      } else {
        this.mode = 2;
      }
      echarts.registerMap(areaName, mapList);
      let clickNum = 0;
      this.clickIndex = 100;
      this.clickName=""
      const geoCoordMap = {
        // 泽雅镇: [120.40736, 28.033248],
        // 郭溪街道: [120.54972, 28.00999],
        // 瞿溪街道: [120.514133, 27.981901],
        // 潘桥街道: [120.54872, 27.94169],
        // 娄桥街道: [120.59965, 27.96616],
        // 新桥街道: [120.628056, 27.986512],
        // 景山街道: [120.63003, 28.00579],
        // 梧田街道: [120.6629, 27.96546],
        // 三垟街道: [120.70576, 27.97009],
        // 南白象街道: [120.678597, 27.947815],
        // 丽岙街道: [120.638744, 27.910488],
        // 茶山街道: [120.70999, 27.92798],
        // 仙岩街道: [120.676827, 27.886949],
      };
      let data = areaData;
      const convertData = function (data) {
        const res = [];
        for (let i = 0; i < data.length; i++) {
          const geoCoord = geoCoordMap[data[i].name];
          if (geoCoord) {
            res.push({
              name: data[i].name,
              value: geoCoord.concat(data[i].value),
              itemStyle: {
                color: "rgb(33 81 255)", //标志颜色
              },
            });
          } else if (data[i].center && data[i].center.length != 0) {
            res.push({
              name: data[i].name,
              value: [data[i].center[0], data[i].center[1] + 0.03],
              itemStyle: {
                color: "rgb(33 81 255)", //标志颜色
              },
            });
          }
        }
        return res;
      };
      if (areaName == "温州市") {
        this.zoom = 1.2;
        this.geoTop = "middle";
      } 
      if (areaName == "瑞安市") {
        this.zoom = 0.8;
        this.geoTop = "middle";
      } 
      else {
        this.zoom = 1;
        this.geoTop = "middle";
      }
      const option = {
        title: {
          top: 20,
          text: this.title || "",
          subtext: "",
          x: "center",
          textStyle: {
            color: "#000",
          },
        },
        legend: {
          orient: "vertical",
          y: "bottom",
          x: "right",
          data: ["pm2.5"],
          textStyle: {
            color: "#000",
          },
        },
        tooltip: {
          show: true,
          formatter: "{b}：{c}人",
          padding: 5,
          position: "bottom",
        },
        //颜色配置
        visualMap: {
          min: 0,
          max: 100,
          left: 26,
          bottom: 10,
          showLabel: !0,
          text: ["人数"],
          textStyle: {
            color: "#fff",
          },
          pieces: [
            {
              gt: 5000,
              label: "＞5000",
              color: "#E69C4D",
            },
            {
              gte: 1000,
              lt: 5000,
              label: "1000 - 5000",
              color: "#E6C945",
            },
            {
              gte: 100,
              lt: 1000,
              label: "100 - 1000",
              color: "#424DEB",
            },
            {
              gt: 0,
              lt: 100,
              label: "＜100",
              color: "#53A1EB",
            },
            {
              value: 0,
              label: "未加入统计",
              color: "#d7d7d7",
            },
          ],
        },
        geo: {
          map: areaName,
          show: true,
          roam: false,
          zoom: this.zoom,
          top: this.geoTop,
          left:'center',
          label: {
            color:'white',
            shadowColor: "rgb(33 81 255)",
            textShadowBlur: 5,
            textShadowOffsetX: 10,
            textShadowOffsetY: 10,
            show: true,
          },
          itemStyle: {
              normal: {
                    // shadowBlur: 4,
                    // shadowOffsetX: 4,
                    // shadowOffsetY: 10,
                    // shadowColor:'#193A74'
              },
            },
          emphasis: {
            label: {
              //悬浮时样式
              color: "#000",
              show: true,
            },
            itemStyle: {
              areaColor: "#668eff", //悬浮区背景
            },
          },
        },
        // geo3D: {
        //     show: true,
        //     map: areaName,
        //     left: 'center',
        //     roam: false,
        //     regionHeight: 5,
        //     itemStyle: {
        //       // 三维地理坐标系组件 中三维图形的视觉属性，包括颜色，透明度，描边等。
        //       color: "#0a599f", // 地图板块的颜色
        //       opacity: 1, // 图形的不透明度 [ default: 1 ]
        //       borderWidth: 2, // (地图板块间的分隔线)图形描边的宽度。加上描边后可以更清晰的区分每个区域   [ default: 0 ]
        //       borderColor: "#377CC5", // 图形描边的颜色。[ default: #333 ]
        //       areaColor:"#2D5F9F",
        //     },
        //     emphasis: {
        //       label: {
        //           show: false,
        //           color: "#fff000",
        //       },
              
        //     },
        //     regions: [],
        // },
        select: {
          label: {
            // 鼠标点击后，标签文本的样式设置
            show: true,
            fontSize: 20,
            color: "black",
          },
          itemStyle: {
            // 鼠标点击后，地图区域的样式设置
            areaColor: "", //点击后的 地图区域的 颜色，可设置“transparent”
          },
        },
        series: [
          //地图
          {
            type: "map",
            map: areaName,
            geoIndex: 0,
            aspectScale: 5 / 9, //长宽比
            showLegendSymbol: false, // 存在legend时显示
            animation: false,
            data: data,
            // selectedMode: "single", //开启选中状态
          },
          //散点
          {
            name: "Top 5",
            type: "scatter",
            coordinateSystem: "geo",
            symbol: "pin",
            symbolSize: [20, 20],
            data: convertData(data),
            zlevel: 1,
            tooltip: {
              show: false,
            },
            emphasis: {
              itemStyle: {
                color: "#d9071e", //悬浮
              },
            },
            selectedMode: "single", //开启选中状态
            select: {
              label: {
                show: false,
              },
              itemStyle: {
                color: "#d9071e",
                borderColor: "#d9071e",
              },
            },
          },
        ],
      };
      myChart.setOption(option);
      const maxIndex = areaData.length - 1;
      // 初始化时高亮选中
      myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: this.activeIndex,
      });
      myChart.dispatchAction({
        type: "highlight",
        seriesIndex: 1,
        dataIndex: this.activeIndex,
      });

      // 定时轮播
      const shuffling = () => {
        if (this.timer) clearInterval(this.timer);
        this.timer = setInterval(() => {
          // 清除之前的高亮
          myChart.dispatchAction({
            type: "downplay",
            seriesIndex: 1,
            dataIndex: this.activeIndex,
          });
          this.activeIndex++;
          if (this.activeIndex > maxIndex) this.activeIndex = 0;
          myChart.dispatchAction({
            type: "showTip",
            seriesIndex: 0,
            dataIndex: this.activeIndex,
          });
          myChart.dispatchAction({
            type: "highlight",
            seriesIndex: 1,
            dataIndex: this.activeIndex,
          });
        }, 3000);
      };
      shuffling();
      // 鼠标移出重新轮播
      myChart.on("mouseout", () => {
        // shuffling();
      });
      // 鼠标移入停止轮播
      myChart.on("mouseover", () => {
        // if (this.timer) clearInterval(this.timer);
      });
      /************************************************************** */
      // 手动点击选中清除轮播效果
      myChart.on("click", (params) => {
        if (this.timer) clearInterval(this.timer);
        //逻辑控制
        if (params.componentSubType == "map") {
          option.select.itemStyle.areaColor = params.color; //设置地图点击后的高亮颜色
          myChart.setOption(option);
        }
        //清除散点图选中
        myChart.dispatchAction({
          type: "unselect",
          seriesIndex: 1,
        });
        //暂时-目前能下钻的不高亮
        myChart.dispatchAction({
          type: "unselect",
          seriesIndex: 0,
          dataIndex: 2,
        });
        myChart.dispatchAction({
          type: "unselect",
          seriesIndex: 1,
          dataIndex: 2,
        });
        // 清除散点图之前的高亮
        myChart.dispatchAction({
          type: "downplay",
          seriesIndex: 1,
        });
        // 散点图选中当前
        myChart.dispatchAction({
          type: "select",
          seriesIndex: 1,
          dataIndex: params.dataIndex,
        });
        //反复点击同一个地区的处理
        // if (this_.clickIndex == params.dataIndex&&this_.clickName==params.name) {
        //   clickNum++;
        //   if (clickNum != 0 && clickNum % 2 != 0) {
        //     myChart.dispatchAction({
        //       type: "unselect",
        //       seriesIndex: 1,
        //       dataIndex: params.dataIndex,
        //     });
        //   }
        // } else {
        //   clickNum = 0; //清空
        // }
        this_.activeIndex = params.dataIndex;
        
        this_.mapClick(params.data, this_.mode);

        this_.clickIndex = params.dataIndex;
        this_.clickName=params.name
      });
      // this.$forceUpdate();
    },
    //点击内容传到父组件
    mapClick(val, mode) {
      this.$emit("mapClick", val, mode);
    },
  },
  mounted() {
    // this.handleData(this.mapData);
    // this.selectAreaName = this.mapDistriction(this.selectArea);
    // this.handleMapJson(this.selectAreaName, this.mapData);
  },
};
</script>
<style lang="scss">
// .container {
//   width: 100%;
//   height: 100%;
// }
.map {
  transition: all 0.5s;
}
</style>
