<template>
  <div style=" position: relative;width: 100%;height: 632px;">
    <div class="map-box" ref="map"></div>
    <div class="legend" :style="{
      right: `${right}px`
    }">
      <div  v-for="(item, index) in legend" :key="index"
      class="legend-item">
      <div class="name">{{item.name}}</div>
      <div :class="`color color-${index}`">
      </div>
      <div class="count">{{item.count}}个区县</div>
    </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import jsonCq from "@/assets/json/cq.json";
import toolUtils from "@/utils/echartsTooltip";
import { toInt } from '@/utils'


export default {
  name: "MapCharts",
  props: {
    qx: String,
    mapHeatData: {
      type: Array,
      default: () => []
    },
    formatter: {
      type: Function,
      default: function (params) {
        let res = params.name + "<br/>";
        res += `隐患<span style="font-size: 24px;color:red;font-weight:bold;">${params.value}</span>个`;
        return res;
      }
    },
    right: {
      type: Number,
      default: 50
    },
    legend: {
      type: Array,
      default: () => [
        {name: '高风险', count: 0 },
        {name: '较高风险', count: 0 },
        {name: '中风险', count: 0 },
        {name: '较低风险', count: 0 },
        {name: '低风险', count: 0 },
      ]
    }
  },
  data() {
    return {
      timed: null,
      mapName: "chongqing",
      mapData: {
        北碚: [106.5, 29.81],
        城口: [108.6520475, 31.90676506],
        大足: [105.7692868, 29.65392091],
        垫江: [107.4004904, 30.24903189],
        丰都: [107.7461781, 29.91492542],
        奉节: [109.3758974, 30.98202119],
        合川: [106.2833096, 30.09766756],
        江北: [106.6214893, 29.64821182],
        江津: [106.2647885, 28.98483627],
        开州: [108.1818518, 31.29466521],
        南岸: [106.6379653, 29.47704825],
        南川: [107.1406799, 29.12047319],
        彭水: [108.2573507, 29.36444557],
        綦南: [106.8036647, 28.96872774],
        黔江: [108.7559876, 29.44290625],
        石柱: [108.2438988, 30.07512144],
        市区: [106.4377397, 29.52648606],
        市辖区: [106.4377397, 29.52648606],
        铜梁: [106.0616035, 29.81036286],
        潼南: [105.811692, 30.13795513],
        万州: [108.0828876, 30.73353669],
        巫山: [109.8779184, 31.09568937],
        巫溪: [109.2970739, 31.48090521],
        武隆: [107.6831317, 29.36831708],
        秀山: [108.9997005, 28.49462861],
        永川: [105.8347961, 29.41042605],
        酉阳: [108.7911679, 28.88330557],
        云阳: [108.7533957, 30.96025875],
        长寿: [107.24, 29.95],
        忠县: [107.9279014, 30.33522658],
        川东: [107.3488646, 29.68233099],
      },
      activeMap: jsonCq,
      activeArea: "",
      activeName: "重庆市",
      activeMapData: [],
      // 区块图
      heatData: [
        {
          name: "万州区",
          value: 0
        },
        {
          name: "涪陵区",
          value: 0,
        },
        {
          name: "渝中区",
          value: 0,
        },
        {
          name: "大渡口区",
          value: 0,
        },
        {
          name: "江北区",
          value: 0,
        },
        {
          name: "沙坪坝区",
          value: 0,
        },
        {
          name: "九龙坡区",
          value: 0,
        },
        {
          name: "南岸区",
          value: 0,
        },
        {
          name: "北碚区",
          value: 0,
        },
        {
          name: "綦江区",
          value: 0,
        },
        {
          name: "大足区",
          value: 0,
        },
        {
          name: "渝北区",
          value: 0,
        },
        {
          name: "巴南区",
          value: 0,
        },
        {
          name: "黔江区",
          value: 0,
        },
        {
          name: "长寿区",
          value: 0,
        },
        {
          name: "江津区",
          value: 0,
        },
        {
          name: "合川区",
          value: 0,
        },
        {
          name: "永川区",
          value: 0,
        },
        {
          name: "南川区",
          value: 0,
        },
        {
          name: "璧山区",
          value: 0,
        },
        {
          name: "铜梁区",
          value: 0,
        },
        {
          name: "潼南区",
          value: 0,
        },
        {
          name: "荣昌区",
          value: 0,
        },
        {
          name: "开州区",
          value: 0,
        },
        {
          name: "梁平区",
          value: 0,
        },
        {
          name: "武隆区",
          value: 0,
        },
        {
          name: "城口县",
          value: 0,
        },
        {
          name: "丰都县",
          value: 0,
        },
        {
          name: "垫江县",
          value: 0,
        },
        {
          name: "忠县",
          value: 0,
        },
        {
          name: "云阳县",
          value: 0,
        },
        {
          name: "奉节县",
          value: 0,
        },
        {
          name: "巫山县",
          value: 0,
        },
        {
          name: "巫溪县",
          value: 0,
        },
        {
          name: "石柱土家族自治县",
          value: 0,
        },
        {
          name: "秀山土家族苗族自治县",
          value: 0,
        },
        {
          name: "酉阳土家族苗族自治县",
          value: 0,
        },
        {
          name: "彭水苗族土家族自治县",
          value: 0,
        },
      ],
      mapChart: null
    };
  },
  watch: {
    qx(val) {
      this.mapChart.dispatchAction({
        type: "select",
        name: val
      })
    },
    mapHeatData: {
      handler(val) {
      if (val.length > 0) {
          this.mapChart.setOption({
            series: [
              {
                data: this.convertMapData(val)
              }
            ],
            visualMap: {
              // max: this.calcMaxData(val),
              pieces: (() => {
                const maxData = this.calcMaxData(val)
                const intData = toInt(Math.ceil(maxData / 5))
                return [
                  {min: intData*4, max: intData * 5},
                  {min: intData*3, max: intData * 4},
                  {min: intData*2, max: intData * 3},
                  {min: intData , max: intData * 2},
                  {min: 0, max: intData},
                  // {min: intData*3, max: intData * 3},
                  // {min: intData*2, max: intData * 2},
                  // {min: intData, max: intData * 2},
                  // {min: 0 , max: intData},
                  // {min: 0, max: 0},
                ]
              })()
            }
          })
        }
      },
      deep: true
    }
  },
  created() {
    const array = [];
    const _data = this.mapData;
    for (const key in _data) {
      array.push({
        name: key,
        value: _data[key],
      });
    }
    this.activeMapData = array;
  },
  mounted() {
    this.drawMap();
  },
  methods: {
    convertMapData(data) {
      const maxValue = (this.calcMaxData(data) / 4)
      const intData = toInt(maxValue)
      return data.map(item => ({...item,
          label: {
            color: item.value < intData * 2 ? '#000' : '#fff'
          }
        }))
    },
    calcMaxData(data) {
      return Math.max(...data.map(item => item.value))
    },
    drawMap() {
      const mapChart = this.$refs.map;
      echarts.registerMap("chongqing", this.activeMap);
      let data = this.heatData

      const { mapName } = this;

      const zoom = 1.27;
      const aspectScale = 1.1;

      const option = {
        title: {
          top: 0,
          subtext: "",
          x: "center",
          textStyle: {
            color: "#ccc",
          },
        },
        geo: [
          {
            map: mapName,
            zlevel: -1,
            zoom,
            aspectScale,
            silent: true,
            layoutCenter: ["50%", "50%"],
            layoutSize: "100%",
            roam: false,
            itemStyle: {
              normal: {
                borderColor: "rgba(192,245,249,.8)",
                borderWidth: 3,
                shadowColor: "#6FFDFF",
                shadowOffsetY: 0,
                shadowBlur: 10,
              },
            },
          },
          {
            show: true,
            map: mapName,
            zoom,
            aspectScale,
            layoutCenter: ["50%", "50%"],
            layoutSize: "100%",

            blur: {
              label: { show: true, color: "#000" },
            },
            roam: false, // 是否开启鼠标滚轮缩放
            itemStyle: {
              normal: {
                label: {
                  show: false,
                },
                color: "#fff",
                borderColor: "#32CBE0",
                borderWidth: 1.5,
                areaColor: '#aaaaaa88'
              },
            },
          },
          {
            type: "map",
            map: mapName,
            zlevel: -2,
            zoom,
            aspectScale,
            layoutCenter: ["50%", "51.4%"],
            layoutSize: "100%",
            roam: false,
            silent: true,
            itemStyle: {
              normal: {
                borderColor: "rgba(35, 161, 184,0.5)",
                shadowColor: "rgba(35, 161, 184,0.8)",
                shadowOffsetY: 5,
                shadowBlur: 15,
                areaColor: "#257AB2",
              },
            },
          },
          {
            type: "map",
            map: mapName,
            zlevel: -3,
            zoom,
            aspectScale,
            layoutCenter: ["50%", "52.4%"],
            layoutSize: "100%",
            roam: false,
            silent: true,
            itemStyle: {
              normal: {
                borderColor: "rgba(7, 65, 117,0.5)",
                shadowColor: "rgba(7, 65, 117,0.8)",
                shadowOffsetY: 15,
                shadowBlur: 8,
                areaColor: "#0A2763",
              },
            },
          },
        ],
        tooltip: {
          trigger: "item",
          position: "top",
          backgroundColor: "rgba(0, 0, 0, 0.82)",
          formatter: this.formatter,
          textStyle: {
            color: "#fff",
          },
          extraCssText: `z-index: 1000;margin:0px;padding:0px;
  border: 1px solid rgba(61, 115, 255, 0.72);`,
          borderWidth: 0,
        },
        visualMap: {
          show: false,
          type: 'piecewise',
          bottom: 20,
          right: this.right,
          max: this.calcMaxData(data),
          inRange: {
            color: [
              '#ff0b0b',
              '#ff833d',
              '#fbff3d',
              '#35c2ff',
              '#5aed9f'
            ].reverse(),
            // symbolSize: [60, 200]
          },
          calculable: true,
          textStyle: {
            color: "#fff",
            fontSize: 12,
          },
          pieces: (() => {
            const maxData = this.calcMaxData(data)
            const intData = toInt(Math.ceil(maxData / 5))
            return [
              {min: intData*4, max: intData * 5},
              {min: intData*3, max: intData * 4},
              {min: intData*2, max: intData * 3},
              {min: intData , max: intData * 2},
              {min: 0, max: intData},
              // {min: intData*3, max: intData * 3},
              // {min: intData*2, max: intData * 2},
              // {min: intData, max: intData * 2},
              // {min: 0 , max: intData},
              // {min: 0, max: 0},
            ]
          })()
        },
        series: [
          {
            name: "总览",
            type: "map",
            label: {
              position: [0, 0],
              normal: {
                show: true,
                textStyle: {
                  color: "#fff",
                  fontSize: 12,
                },
              },
              emphasis: {
                textStyle: {
                  color: "#fff",
                },
              },
              color: "#fff",
            },
            select: {
              label: {
                // 选中区域的label(文字)样式
                color: "#fff",
              },
              itemStyle: {
                areaColor: "#75b9da",
                borderColor: "#0f417f",
                shadowColor: "#5a9cdd",
                shadowBlur: 0,
                shadowOffsetX: 0,
                shadowOffsetY: 10,
              },
            },
            itemStyle: {
              normal: {
                color: "#fff",
                borderColor: "#75b9da", // 地图边缘线颜色
                borderWidth: 2
              },

              emphasis: {
                label: {
                  fontSize: 24,
                  textBorderColor: "#393523",
                  textBorderWidth: 2,
                },
                borderColor: "#0f417f",
                shadowColor: "#5a9cdd",
                shadowBlur: 0,
                shadowOffsetX: 0,
                shadowOffsetY: 10,
                areaColor: {
                  type: "linear-gradient",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#06969d", // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#1daedc",
                    },
                  ],
                },
              },
            },
            aspectScale, // 长宽比
            zoom,
            layoutCenter: ["50%", "50%"],
            layoutSize: "100%",
            map: mapName, // 使用
            data: this.convertMapData(data),
          },
        ],
      };
      this.mapChart = echarts.init(mapChart, "light");
      this.mapChart.setOption(option);
    toolUtils.autoHover(this.mapChart, option, 24, 5000);
      // 图表对象响应式设置
      window.addEventListener("resize", () => {
        this.mapChart.resize();
      });
      //
      this.mapChart.on("click", (params) => {
        if(params.seriesType === 'map'){
          if (params.name !== this.activeArea) {
            this.activeArea = params.name
            this.$emit('selectArea', params.name)
          } else {
            if (this.activeArea === "") {
            this.activeArea = params.name
            this.$emit('selectArea', params.name)
            } else {
              this.activeArea = ""
              this.$emit('selectArea', "重庆市")
            }
          }
        }
      });
    },
  },
};
</script>
<style scoped>

.legend {
  position: absolute;
  bottom: 30px;
  right: 20px;
}
.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  .count {
    color: #fff;
  }
  .name {
    width: 60px;
    text-align: right;
  }
  .color {
    width: 10px;
    height: 40px;
    &.color-0 {
    background-color: #ff0b0b;
    }
    &.color-1 {
      background-color: #ff833d;
    }
    &.color-2 {
      background-color: #fbff3d;
    }
    &.color-3 {
      background-color: #35c2ff;
    }
    &.color-4 {
      background-color: #5aed9f;
    }
  }
}

.map-box {
  width: 100%;
  /* height: 98%; */
  height: 632px;
  /* background: blue; */
}
</style>
