<template>
  <div class="i-comp-mapnew">
    <div :id="index" class="mapnew-chart">地图</div>
    <i
      class="el-icon-setting mapnew-icon"
      @click="showPanel = !showPanel"
      :style="{ color: option.textcolor }"
    ></i>
    <div
      class="mapnew-panel"
      v-show="showPanel"
      :style="{ color: option.textcolor }"
    >
      <div>选择指标</div>
      <el-radio-group v-model="indexParamIndex" @change="handleClearData">
        <el-radio
          v-for="(item, i) of config.indexParamList"
          :key="i"
          :label="i"
          style="display: block;margin:10px 0"
        >
          {{ item.columnTitle }}
        </el-radio>
      </el-radio-group>
    </div>
    <div
      class="mapnew-back"
      v-show="level > 0"
      @click="onLevelBack"
      :style="{ color: option.textcolor }"
    >
      回到上一级
    </div>
  </div>
</template>
<script>
import {legend, title, grid} from "../../newStyles/styleCommon";

export default {
  name: "new-map",
  props: ["option", "config", "modalSet", "index", "site"],
  data() {
    return {
      originData: [],
      myChart: {},
      mapRegisted: {}, // 已注册过的地图区域
      level: 0, // 下钻等级
      indexParamIndex: 0,
      clearData: [], // 处理后数据
      showPanel: false,
      playIndex: 0,
      playTimer: null,
      mapLinks: {0: "china-china"},
    };
  },
  watch: {
    site: {
      handler() {
        if (this.myChart) {
          this.myChart.resize();
        }
      },
      deep: true,
    },
    option: {
      handler() {
        if (this.originData.length) {
          this.init();
        }
      },
      deep: true,
    },
  },
  mounted() {
  },
  created() {
  },
  methods: {
    // 回到上一级
    onLevelBack() {
      this.level--;
      this.init();
    },
    // 悬浮层轮播函数
    play() {
      this.myChart.dispatchAction({
        type: "downplay",
        seriesIndex: 0,
      });
      this.myChart.dispatchAction({
        type: "highlight",
        seriesIndex: 0,
        dataIndex: this.playIndex,
      });
      this.myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: this.playIndex,
      });
      this.playIndex++;
      if (this.playIndex >= this.clearData.length) {
        this.playIndex = 0;
      }
    },
    init() {
      let {indexParamList, columnParamList} = this.config;
      if (!indexParamList || !indexParamList.length) return;
      if (!columnParamList || !columnParamList.length) return;
      let nowLink = this.mapLinks[this.level];
      this.$request
        .get(
          `/json/chinaGeoJson/${
            nowLink == "china-china" ? "china-全国" : nowLink
          }.json`
        )
        .then(async (res) => {
          this.myChart = echarts.init(document.getElementById(this.index));
          let mapData = res.data;
          let mapName = nowLink.split("-")[1];
          echarts.registerMap(mapName, mapData);
          this.mapRegisted[this.level] = {name: mapName, data: mapData};
          this.handleClearData();
          this.handlePlayEvents();
          this.handleClickEvent();
        });
    },
    update(data) {
      this.originData = data;
      this.init()
    },
    // 整理数据
    handleClearData() {
      let regionKey = this.config.columnParamList[this.level].columnTitle;
      let indexKey = this.config.indexParamList[this.indexParamIndex].columnTitle;
      let data = this.originData.reduce((r, item) => {
        let nowRegion = r.find((j) => j.name == item[regionKey]);
        if (!nowRegion) {
          nowRegion = {name: item[regionKey], data: {}};
          r.push(nowRegion);
        }
        if (!this.config.rowParamList.length) {
          nowRegion.value = parseFloat(item[indexKey]);
        } else {
          let rowKey = this.config.rowParamList[0].columnTitle;
          if (!nowRegion.data[item[rowKey]]) {
            nowRegion.data[item[rowKey]] = parseFloat(item[indexKey]);
          } else {
            nowRegion.data[item[rowKey]] += parseFloat(item[indexKey]);
          }
        }
        return r;
      }, []);
      if (this.config.rowParamList.length) {
        data.forEach((item) => {
          item.data = Object.entries(item.data).map(([label, value]) => ({
            label,
            value,
          }));
          item.value = parseFloat(item.data.reduce((r, i) => r + i.value, 0));
        });
      }
      // 当前地图中包含的区域列表
      let nameList = this.mapRegisted[this.level].data.features.map(
        (i) => i.properties.name
      );
      // console.log(nameList);
      // 名称处理，过滤出当前地图区域的数据
      let tooltipNumber = this.option.tooltipNumber || 5;
      this.clearData = data
        .map((i) => {
          let name = i.name
            .replace("省", "")
            .replace("回族自治区", "")
            .replace("壮族自治区", "")
            .replace("维吾尔自治区", "")
            .replace("自治区", "")
            .replace("特别行政区", "");
          if (["北京市", "天津市", "上海市", "重庆市"].includes(name)) {
            name = name.replace("市", "");
          }
          return {
            name,
            value: new Number(i.value).toFixed(this.option.numberLength || 0),
            data: this.config.rowParamList.length
              ? i.data
                .sort((a, b) => b.value - a.value)
                .slice(0, tooltipNumber)
                .map((i) => ({
                  ...i,
                  value: new Number(i.value).toFixed(
                    this.option.numberLength || 0
                  ),
                }))
              : [],
          };
        })
        .filter((i) => nameList.includes(i.name));
      // console.log(JSON.parse(JSON.stringify(this.clearData)));
      console.log(this.getMapSeries())
      let option = {
        geo: this.getGeo(),
        series: this.getMapSeries(),
        tooltip: {},
        visualMap: this.getVisualMap(),
      };
      // console.log(JSON.parse(JSON.stringify(option)));
      this.myChart.setOption(option, true);
    },
    // 处理轮播相关事件
    handlePlayEvents() {
      clearInterval(this.playTimer);
      this.myChart.off("mouseover");
      this.myChart.off("mouseout");
      if (!this.option.tooltipPlay) return;
      this.playTimer = setInterval(
        this.play,
        this.option.tooltipPlayTime || 1500
      );
      this.myChart.on("mouseover", (e) => {
        clearInterval(this.playTimer);
        this.myChart.dispatchAction({
          type: "downplay",
          seriesIndex: 0,
        });
        this.myChart.dispatchAction({
          type: "highlight",
          seriesIndex: 0,
          dataIndex: e.dataIndex,
        });
      });
      this.myChart.on("mouseout", () => {
        clearInterval(this.playTimer);
        this.playTimer = setInterval(
          this.play,
          this.option.tooltipPlayTime || 1500
        );
      });
    },
    // 处理点击事件
    handleClickEvent() {
      this.myChart.off("click");
      if (!this.option.checkLevel) return;
      this.myChart.on("click", (e) => {
        if (this.level + 1 >= this.config.columnParamList.length) {
          return console.log("已到最大层级");
        }
        let nextMap = this.mapRegisted[this.level].data.features.find(
          (i) => i.properties.name == e.name
        );
        if (!nextMap) return;
        this.level++;
        this.mapLinks[this.level] =
          nextMap.properties.adcode + "-" + nextMap.properties.name;
        this.init();
      });
    },
    // 配置左下渐变图例
    getVisualMap() {
      let {min, max} = this.clearData.reduce(
        (r, i) => {
          return {
            min: Math.min(r.min, i.value),
            max: Math.max(r.max, i.value),
          };
        },
        {min: 0, max: 0}
      );
      let {
        mapBaseColor,
        mapColor,
        visualLeft,
        visualBottom,
        visualTextColor,
      } = this.option;
      let indexKey = this.config.indexParamList[this.indexParamIndex].columnTitle;
      return {
        min,
        max,
        text: [indexKey, " "],
        textStyle: {color: visualTextColor || "#ffffff"},
        left: visualLeft || 30,
        bottom: visualBottom || 30,
        realtime: false,
        calculable: true,
        inRange: {
          color: [mapBaseColor || "#ffffff", mapColor],
        },
      };
    },
    // 配置地图系列
    getMapSeries() {
      let that = this
      let option = this.option
      let chinaGeoCoordMap = {
        '黑龙江': [127.9688, 45.368],
        '内蒙古': [110.3467, 41.4899],
        "吉林": [125.8154, 44.2584],
        '北京市': [116.4551, 40.2539],
        "辽宁": [123.1238, 42.1216],
        "河北": [114.4995, 38.1006],
        "天津": [117.4219, 39.4189],
        "山西": [112.3352, 37.9413],
        "陕西": [109.1162, 34.2004],
        "甘肃": [103.5901, 36.3043],
        "宁夏": [106.3586, 38.1775],
        "青海": [101.4038, 36.8207],
        "新疆": [87.9236, 43.5883],
        "西藏": [91.11, 29.97],
        "四川": [103.9526, 30.7617],
        "重庆": [108.384366, 30.439702],
        "山东": [117.1582, 36.8701],
        "河南": [113.4668, 34.6234],
        "江苏": [118.8062, 31.9208],
        "安徽": [117.29, 32.0581],
        "湖北": [114.3896, 30.6628],
        "浙江": [119.5313, 29.8773],
        "福建": [119.4543, 25.9222],
        "江西": [116.0046, 28.6633],
        "湖南": [113.0823, 28.2568],
        "贵州": [106.6992, 26.7682],
        "云南": [102.9199, 25.4663],
        "广东": [113.12244, 23.009505],
        "广西": [108.479, 23.1152],
        "海南": [110.3893, 19.8516],
        '上海': [121.4648, 31.2891]
      };

      let chinaDatas = [];
      this.clearData.forEach(item=>{
        chinaDatas.push({
          name: item.name,
          value:1
        })
      })
      let convertData = function (data) {
        let res = [];
        data.forEach(dataItem => {
          let fromCoord = chinaGeoCoordMap[dataItem.name];
          let toCoord = [116.4551, 40.2539];
          if (fromCoord && toCoord) {
            res.push([{
              coord: fromCoord,
              value: dataItem.value
            }, {
              coord: toCoord,
            }]);
          }
        })
        return res;
      };
      let series = [];
      let indexKey = this.config.indexParamList[this.indexParamIndex].columnTitle;
      let textcolor = this.option.tooltipTextcolor;
      let bgcolor = this.option.tooltipBgcolor;
      [['北京市', chinaDatas]].forEach(function (item) {
        series.push({
            type: 'lines',
            zlevel: 2,
            effect: {
              show: true,
              period: 4, //箭头指向速度，值越小速度越快
              trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
              symbol: 'arrow', //箭头图标
              symbolSize: 5, //图标大小
            },
            lineStyle: {
              normal: {
                width: 1, //尾迹线条宽度
                opacity: 1, //尾迹线条透明度
                curveness: .3 //尾迹线条曲直度
              }
            },
            tooltip: { show: false },
            data: convertData(item[1])
          }, {
            type: 'effectScatter',
            coordinateSystem: 'geo',
            zlevel: 2,
            color: option.centerColor,
            rippleEffect: {
              period: 4, //动画时间，值越小速度越快
              brushType: "fill", //波纹绘制方式 stroke, fill
              scale: option.centerSize, //波纹圆环最大限制，值越大波纹越大
            },
            label: {
              normal: {
                show: true,
                position: 'right', //显示位置
                offset: [5, 0], //偏移设置
                formatter: function (params) {//圆环显示文字
                  return params.data.name;
                },
                fontSize: 13
              },
              emphasis: {
                show: true
              }
            },
            symbol: 'circle',
            symbolSize: function (val) {
              return 5 + val[2] * 5; //圆环大小
            },
            itemStyle: {
              normal: {
                show: false,
                color: '#f00'
              }
            },
            data: item[1].map(function (dataItem) {
              return {
                name: dataItem.name,
                value: chinaGeoCoordMap[dataItem.name].concat([dataItem.value])
              };
            }),
          },
          //被攻击点
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            zlevel: 2,
            rippleEffect: {
              period: 4,
              brushType: 'stroke',
              scale: 4
            },
            label: {
              normal: {
                show: true,
                position: 'right',
                //offset:[5, 0],
                color: '#a60d0d',
                formatter: '{b}',
                textStyle: {
                  color: "#ffffff"
                }
              },
              emphasis: {
                show: true,
                color: "#f60"
              }
            },
            symbol: 'pin',
            symbolSize: 50,
            data: [{
              name: item[0],
              value: chinaGeoCoordMap[item[0]].concat([10]),
            }],
          }
        );
      });
      return series
      // let indexKey = this.config.indexParamList[this.indexParamIndex].columnTitle;
      // let textcolor = this.option.tooltipTextcolor;
      // let bgcolor = this.option.tooltipBgcolor;
      // return {
      //   type: "lines",
      //   coordinateSystem: "geo",
      //   map: this.mapLinks[this.level].split("-")[1],
      //   data: this.clearData,
      //   // 飞点样式
      //   effect: {
      //     show: true,
      //     period: 6,
      //     trailLength: 0,
      //     // symbol: planePath, 自定义图片
      //     symbolSize: 5,
      //   },
      //   // 飞线样式
      //   itemStyle: {
      //     borderColor: this.option.borderColor,
      //     normal: {
      //       lineStyle: {
      //         // color: "", 线颜色
      //         width:10,
      //         opacity: 0.9,
      //         curveness: 0.2,
      //       },
      //     },
      //   },
      //   select: {
      //     itemStyle: {
      //       areaColor: this.option.hoverColor,
      //     },
      //     label: {
      //       color: this.option.labelColor,
      //     },
      //   },
      //   tooltip: {
      //     backgroundColor: bgcolor,
      //     formatter(param) {
      //       let content = `<div style="color:${textcolor}">`;
      //       content += `<div class="i-comp-mapnew-tooltip-header" style="border-bottom:1px solid ${textcolor};">区域：${param.name}</div>`;
      //       if (!param.data) return content + `</div>`;
      //       content += `<div>${indexKey}：${param.data.value}</div>`;
      //       param.data.data.forEach((item) => {
      //         content += `<div>${item.label}：${item.value}</div>`;
      //       });
      //       content += `</div>`;
      //       return content;
      //     },
      //   }
      // };
    },
    // 获取地图geo配置
    getGeo() {
      let that = this
      return {
        map: this.mapLinks[this.level].split("-")[1],
        zoom: 1.2,
        roam: true, //是否允许缩放
        label: {
          show: true,
          color: that.option.labelColor, // 标签颜色
          offset: [0, -7],
        },
        emphasis: {
          itemStyle: {
            areaColor: that.option.mapHighColor, // 地图高亮颜色
          },
          label: {
            color: that.option.labelHighColor, // 标签高亮颜色
          },
        },
        tooltip: {
          formatter({ name }) {
            let now = that.clearData.find((i) => i.name == name);
            if (now) {
              let content = `<div style="color:#000">`;
              content += `<div class="i-comp-mapnew-tooltip-header">区域：${now.name}</div>`;
              content += `<div>${now.value}</div>`;
              now.data.forEach((item) => {
                content += `<div>${item.label}：${item.value}</div>`;
              });
              content += `</div>`;
              return content;
            }
          },
        },
        itemStyle: {
          normal: {
            areaColor: that.option.mapColor, // 地图颜色
            borderWidth: 1,
            borderColor: that.option.borderColor,
          },
        },
        regions: [
          {
            name: "南海诸岛",
            itemStyle: {
              borderWidth: 1,
              borderColor: this.option.borderColor,
            },
          },
        ],
      };
    },
    onZuanBack() {

    },
    initRender() {
      let option = {};
      this.myChart = echarts.init(document.getElementById(this.index));
      this.myChart.setOption(option, true);
      this.$nextTick(this.myChart.resize);
    },
  },
};
</script>
<style lang="scss">
.i-comp-mapnew {
  .mapnew-chart {
    width: 100%;
    height: 100%;
    z-index: 998;
    top: 0;
    left: 0;
    position: absolute;
  }

  .mapnew-icon {
    position: absolute;
    right: 20px;
    top: 20px;
    z-index: 999;
    cursor: pointer;
  }

  .mapnew-panel {
    position: absolute;
    right: 45px;
    top: 20px;
    z-index: 999;
    background-color: #fff;
    padding: 10px;
    border-radius: 5px;
  }

  .mapnew-back {
    position: absolute;
    left: 20px;
    top: 20px;
    z-index: 999;
    cursor: pointer;
  }
}

.i-comp-mapnew-tooltip-header {
  font-size: 16px;
  line-height: 32px;
  margin-bottom: 6px;
}
</style>
