<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)));
      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 indexKey = this.config.indexParamList[this.indexParamIndex].columnTitle;
      let textcolor = this.option.tooltipTextcolor;
      let bgcolor = this.option.tooltipBgcolor;
      return {
        type: "map",
        map: this.mapLinks[this.level].split("-")[1],
        data: this.clearData,
        label: {
          show: true,
          offset: [0, -7],
          color: this.option.labelColor,
          fontSize: this.option.labelSize || 12,
        },
        emphasis: {
          itemStyle: {
            areaColor: this.option.hoverColor,
          },
          label: {
            color: this.option.labelColor,
          },
        },
        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;
          },
        },
        itemStyle: {
          normal: {
            borderWidth: 1,
            borderColor: this.option.borderColor,
          },
        },
      };
    },
    // 获取地图geo配置
    getGeo() {
      return {
        map: this.mapLinks[this.level].split("-")[1],
        roam: false,
        itemStyle: {
          normal: {
            borderWidth: this.option.outlineWeight,
            borderColor: this.option.outlineColor,
          },
        },
        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>
