<template>
  <div class="container">
    <div id="map" 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 [{ firstScreeningCoverRate: 0 }];
      },
    },
    selectArea: String,
    title: {
      type: String,
    },
  },
  data() {
    return {
      activeIndex: 0,
      clickIndex: 100,
      clickName:"",
      chart: null,
      mapList: [], //地图json文件
      selectAreaName: "",
      noneArea: "",
      zoom: 20,
      geoTop: "middle",
      mode: 100,
      timer:{},
    };
  },
  watch: {
    //接口数据
    mapData: {
      deep: true,
      handler(val) {
        this.handleMapJson(this.selectAreaName, val);
      },
      // activeIndex: {
      //   handler(i) {
      //     this.$emit("handleChange", areaData[i]);
      //   },
      //   immediate: true,
      // },
    },
    selectArea(val) {
      this.selectAreaName = this.mapDistriction(val);
      // this.handleMapJson(this.selectAreaName, this.mapData);
    },
  },
  methods: {
    //选择json文件
    handleMapJson(areaName, mapData) {
      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);
        if (mapData && mapData.length > 0) {
          mapData.forEach((v) => {
            if (v && v.addressCode == distCode) {
              distValue = Number(v.firstScreeningCoverRate);
            }
          });
        }
        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("map"));
      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.3;
        this.geoTop = 50;
      } 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: [
            {
              gte: 80,
              label: "大于80%",
              color: "#ff5428",
            },
            {
              gte: 60,
              lt: 80,
              label: "60% - 80%",
              color: "#ec808d",
            },
            {
              gte: 40,
              lt: 60,
              label: "40% - 60%",
              color: "#facd91",
            },
            {
              gte: 20,
              lt: 40,
              label: "20% - 40%",
              color: "#ffff80",
            },
            {
              gt: 0,
              lt: 20,
              label: "0% - 20%",
              color: "#81d3f8",
            },
            {
              value: 0,
              label: "未加入统计",
              color: "#d7d7d7",
            },
          ],
        },
        geo: {
          map: areaName,
          show: true,
          roam: true,
          zoom: this.zoom,
          top: this.geoTop,
          left:'center',
          label: {
            color: "rgb(33 81 255)",
            show: true,
          },
          emphasis: {
            label: {
              //悬浮时样式
              color: "#000",
              show: true,
            },
            itemStyle: {
              areaColor: "#668eff", //悬浮区背景
            },
          },
        },
        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) => {
        // console.log("反复点击", clickNum, this_.clickIndex, params.dataIndex,this_.clickName,params.name);
        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>
