<!--
 * @Author: szy
 * @Date: 2022-03-01 11:17:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-09-29 15:50:18
 * @FilePath: \web-pc\src\pages\big-screen\view\indexs\center-map.vue
-->
<template>
  <div class="centermap">
    <!-- <div class="maptitle">
      <span class="titletextBefore"
        >今年累计碳减排<span class="titletext">{{ maptitle }}</span
        >{{ maptitle2 }}</span
      >
    </div> -->
    <div class="mapwrap">
      <div class="map-card">
        <div class="quanguo1" @click="goToPage()">实时监控</div>
        <div
          class="quanguo1 quanguo"
          @click="getData('china')"
          v-if="code !== 'china'"
        >
          中国
        </div>
        <div class="quanguo2">
          羚牛全国车辆信息
          <div class="btn" @click="changeShow1()" v-if="showType === 2">
            车辆
          </div>
          <div class="btn" @click="changeShow2()" v-else>加氢站</div>
        </div>
        <!-- <div
          class="quanguo3"
         
          :style="{ backgroundColor: currentBgColor3 }"
        >
          <div>加氢站</div>
        </div> -->

        <Echart id="CenterMap" :options="options" ref="CenterMap" />
        <!-- <dv-flyline-chart :config="config" style="width:100%;height:100%;" /> -->
      </div>
    </div>
  </div>
</template>

<script>
import xzqCode from "../../utils/map/xzqCode";
import { currentGET } from "api/modules";
import * as echarts from "echarts";
import { GETNOBASE } from "api";
import { currentPOST } from "@/api";
import truckIcon from "@/assets/img/new/truck.png";
import stationIcon from "@/assets/img/new/hydrogen.png";
export default {
  data() {
    return {
      truckIcon,
      stationIcon,
      maptitle: "2536238",
      maptitle2: "",
      options: {},
      code: "china", //china 代表中国 其他地市是行政编码
      //code:"440000",
      echartBindClick: false,
      isSouthChinaSea: false, //是否要展示南海群岛  修改此值请刷新页面
      currentMap: "china", // 当前显示的地图层级
      showType: 1, //显示内容类型： 1车辆信息，2加氢站信息
      currentBgColor2: "",
      currentBgColor3: "",
    };
  },
  created() {},

  mounted() {
    console.log(xzqCode);
    this.getYearData();

    this.showType = 1;
    this.currentBgColor2 = "#00D4AA";
    this.getData("china");
    //this.getData("440000");

    // 监听事件总线的刷新事件
    this.$eventBus.$on('refresh-all-data', () => {
      this.getYearData();
      this.getData(this.code);
    });
  },
  methods: {
    changeShow1() {
      this.showType = 1;
      this.currentBgColor2 = "#00D4AA";
      this.currentBgColor3 = "";
      this.getData(this.code);
    },
    changeShow2() {
      this.currentBgColor2 = "";
      this.currentBgColor3 = "#00D4AA";
      this.showType = 2;
      this.getData(this.code);
    },
    goToPage() {
      //window.open("http://localhost:9528/vehicle-management/vehicle-state?"+this.code, "_blank");

      window.open(
        "http://47.100.49.118:8090/vehicle-lnSituation?" + this.code,
        "_blank"
      );
      //window.open("http://127.0.0.1:9528/vehicle-lnSituation?"+this.code, "_blank");
      //window.open("http://192.168.0.219:9528/vehicle-lnSituation?"+this.code, "_blank");
    },
    parseAdcodeLevel(adcode) {
      const codeStr = String(adcode);
      if (codeStr.endsWith("0000")) return "province"; // 省级（如 440000）
      if (codeStr.endsWith("00")) return "city"; // 市级（如 440300）
      return "district"; // 区县级（如 440305）
    },
    getYearData() {
      currentGET("big3").then((res) => {
        console.log("年度碳减排量");
        console.log(res);
        //this.maptitle = res.data.yearCarbon ;    //单位kg
        this.maptitle = res.data.yearCarbonTon; //单位吨
        this.maptitle2 = "吨";
      });
    },
    getData(code) {
      console.log("code", code);
      this.currentMap = this.parseAdcodeLevel(code);
      //2025.9.10 szy 增加showType 分类处理，1时处理车辆信息，2时处理加氢站信息
      if (this.showType === 1) {
        currentGET("big9", {
          regionCode: code,
          adcodeLevel: this.currentMap,
        }).then((res) => {
          console.log("map车辆分布", res);
          //if (res.success)
          if (res.status) {
            this.getGeojson(res.data.regionCode, res.data.dataList);
            this.mapclick();
          } else {
            this.$Message.warning(
              "获取车辆信息失败：" + (res.msg || "未知错误")
            );
          }
        });
      } else if (this.showType === 2) {
        currentGET("big10", {
          regionCode: code,
          adcodeLevel: this.currentMap,
        }).then((res) => {
          console.log("加氢站_map分布", res);
          //if (res.success)
          if (res.status) {
            this.getGeojson2(res.data.regionCode, res.data.dataList);
            this.mapclick();
          } else {
            this.$Message.warning(
              "获取加氢站信息失败：" + (res.msg || "未知错误")
            );
          }
        });
      }
    },
    /**
     * @description: 获取geojson
     * @param {*} name china 表示中国 其他省份行政区编码
     * @param {*} mydata 接口返回列表数据
     * @return {*}
     */
    async getGeojson(name, mydata) {
      this.code = name;
      this.currentMap = name;
      console.log("当前地图层级");
      console.log(this.currentMap);
      //如果要展示南海群岛并且展示的是中国的话
      let geoname = name;
      if (this.isSouthChinaSea && name == "china") {
        geoname = "chinaNanhai";
      }
      //如果有注册地图的话就不用再注册 了
      let mapjson = echarts.getMap(name);
      console.log("已经是否已存在的地图数据");
      if (mapjson) {
        mapjson = mapjson.geoJson;
      } else {
        //console.log('当前未注册地图');
        mapjson = await GETNOBASE(`./map-geojson/${geoname}.json`).then(
          (res) => {
            return res;
          }
        );
        echarts.registerMap(name, mapjson);
      }
      console.log(mapjson);
      let cityCenter = {};
      let arr = mapjson.features;

      //根据geojson获取省份中心点
      arr.map((item) => {
        cityCenter[item.properties.name] =
          item.properties.centroid || item.properties.center;
      });
      let newData = [];
      mydata.map((item) => {
        if (cityCenter[item.name]) {
          if (item.vehicleTotal === undefined || item.vehicleTotal === null) {
            item.vehicleTotal = 0;
          }
          if (item.onLineCount === undefined || item.onLineCount === null) {
            item.onLineCount = 0;
          }
          if (item.dayMileage === undefined || item.dayMileage === null) {
            item.dayMileage = 0;
          }
          if (item.dayHydrogen === undefined || item.dayHydrogen === null) {
            item.dayHydrogen = 0;
          }
          if (item.dayCarbon === undefined || item.dayCarbon === null) {
            item.dayCarbon = 0;
          }
          newData.push({
            name: item.name,
            value: cityCenter[item.name]
              .concat(item.vehicleTotal)
              .concat(item.onLineCount)
              .concat(item.dayMileage)
              .concat(item.dayHydrogen)
              .concat(item.dayCarbon),
          });
        }
      });
      console.log("开始初始化地图");
      console.log(newData);
      this.init(name, mydata, newData);
    },
    /**
     * @description: 获取geojson
     * @param {*} name china 表示中国 其他省份行政区编码
     * @param {*} mydata 接口返回列表数据
     * @return {*}
     */
    async getGeojson2(name, mydata) {
      this.code = name;
      this.currentMap = name;
      console.log("加氢站_当前地图层级");
      console.log(this.currentMap);
      //如果要展示南海群岛并且展示的是中国的话
      let geoname = name;
      if (this.isSouthChinaSea && name == "china") {
        geoname = "chinaNanhai";
      }
      //如果有注册地图的话就不用再注册 了
      let mapjson = echarts.getMap(name);
      console.log("加氢站_已经是否已存在的地图数据");
      if (mapjson) {
        mapjson = mapjson.geoJson;
      } else {
        //console.log('当前未注册地图');
        mapjson = await GETNOBASE(`./map-geojson/${geoname}.json`).then(
          (res) => {
            return res;
          }
        );
        echarts.registerMap(name, mapjson);
      }
      console.log(mapjson);
      let cityCenter = {};
      let arr = mapjson.features;

      //根据geojson获取省份中心点
      arr.map((item) => {
        cityCenter[item.properties.name] =
          item.properties.centroid || item.properties.center;
      });
      let newData = [];
      mydata.map((item) => {
        if (cityCenter[item.name]) {
          if (
            item.siteTotalCount === undefined ||
            item.siteTotalCount === null
          ) {
            item.siteTotalCount = 0;
          }
          if (item.siteCount === undefined || item.siteCount === null) {
            item.siteCount = 0;
          }
          newData.push({
            name: item.name,
            value: cityCenter[item.name]
              .concat(item.siteTotalCount)
              .concat(item.siteCount),
          });
        }
      });
      console.log("加氢站_开始初始化地图");
      console.log(newData);
      this.init2(name, mydata, newData);
    },
    init(name, data, data2) {
      // console.log('init_data');
      // console.log(data);
      // console.log('init_data2');
      // console.log(data2);
      let top = 45;
      let zoom = 1.05;
      let option = {
        backgroundColor: "rgba(0,0,0,0)",
        tooltip: {
          show: false,
        },
        legend: {
          show: false,
        },
        visualMap: {
          left: 20,
          bottom: 20,
          pieces: [
            // { gte: 1000, label: "1000辆以上" }, // 不指定 max，表示 max 为无限大（Infinity）。
            // { gte: 600, lte: 999, label: "600-999辆" },
            // { gte: 200, lte: 599, label: "200-599辆" },
            // { gte: 50, lte: 199, label: "49-199辆" },
            // { gte: 10, lte: 49, label: "10-49辆" },
            // { lte: 9, label: "1-9辆" }, // 不指定 min，表示 min 为无限大（-Infinity）。

            { gte: 500, label: "500 辆以上" }, // 不指定 max，表示 max 为无限大（Infinity）。
            { gte: 100, lte: 500, label: "100-500 辆" },
            { gte: 50, lte: 100, label: "50-100 辆" },
            { lte: 50, label: "1-50 辆" }, // 不指定 min，表示 min 为无限大（-Infinity）。
          ],
          inRange: {
            // 渐变颜色，从小到大（绿色系）
            color: [
              "#E2F8F2",
              "#7BC69B",
              "#08703D",
              "#005E34",
              "#036437",
              "#10B981",
            ],
            // "#FEFEFE",
            //   "#F4FDFA",
            //   "#E2F8F2",
            //   "#BCE9D8",
            //   "#7BC69B",
            //   "#3C9864",
            //   "#08703D",
            //   "#005F35",
            //   "#005E34",
          },
          textStyle: {
            color: "#333333",
          },
        },
        geo: {
          map: name,
          roam: false,
          selectedMode: false, //是否允许选中多个区域
          zoom: zoom,
          top: top,
          // aspectScale: 0.78,
          show: false,
        },
        series: [
          {
            name: "MAP",
            type: "map",
            map: name,
            // zlevel: 2,
            // aspectScale: 0.78,
            data: data,
            //data: [1,100],
            selectedMode: false, //是否允许选中多个区域
            zoom: zoom,
            geoIndex: 1,
            top: top,
            showLegendSymbol: false, // 存在legend时显示
            tooltip: {
              show: true,
              formatter: function (params) {
                //console.log("series 1 formatter");
                //console.log(params);
                if (params.data) {
                  //return params.name + "：" + params.data["value"][2];
                  //return params.name + "：" + params.data.vehicleTotal + "辆";
                  return `${params.name}<br>车辆总数: ${params.data.vehicleTotal}<br>GPS在线数: ${params.data.onLineCount}<br>当日里程: ${params.data.dayMileage}km<br>当日用氢量: ${params.data.dayHydrogen}kg<br>当日减碳: ${params.data.dayCarbon}kg`;
                } else {
                  return params.name;
                }
              },
              backgroundColor: "rgba(255,255,255,0.8)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#333333",
              },
            },
            label: {
              show: false,
              color: "#000",
              // position: [-10, 0],
              formatter: function (val) {
                // console.log(val)
                if (val.data !== undefined) {
                  return val.name.slice(0, 2);
                } else {
                  return "";
                }
              },
              rich: {},
            },
            emphasis: {
              //高亮时显示
              label: {
                show: false,
              },
              itemStyle: {
                areaColor: "#e3f2fd",
                borderWidth: 1,
              },
            },
            itemStyle: {
              borderColor: "#475569", //地图边缘颜色
              borderWidth: 0.5,
              areaColor: "#ffffff",
              shadowColor: "rgba(0, 0, 0, .1)",
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10,
            },
          },
          // 车辆涟漪效果层
          {
            data: data2,
            type: "effectScatter",
            coordinateSystem: "geo",
            symbol: "circle",
            symbolSize: 20,
            itemStyle: {
              color: "#10B981",
              shadowBlur: 10,
              shadowColor: "#10B981",
            },
            showEffectOn: "render",
            rippleEffect: {
              period: 3,
              scale: 4,
              brushType: "stroke",
              color: "rgba(16, 185, 129, 0.6)",
            },
            zlevel: 1,
          },
          // 车辆图标层
          {
            data: data2,
            type: "scatter",
            coordinateSystem: "geo",
            symbol: "image://" + this.truckIcon,
            symbolSize: 24,
            itemStyle: {
              borderColor: "#10B981",
              borderWidth: 2,
              shadowBlur: 8,
              shadowColor: "rgba(16, 185, 129, 0.5)",
            },
            legendHoverLink: true,
            tooltip: {
              show: true,
              formatter: function (params) {
                if (params.data) {
                  return (
                    params.data.name +
                    "<br> 车辆总数：" +
                    params.data["value"][2] +
                    "<br> GPS在线总数：" +
                    params.data["value"][3] +
                    "<br>当日里程: " +
                    params.data["value"][4] +
                    "km<br>当日用量: " +
                    params.data["value"][5] +
                    "kg<br>当日减碳: " +
                    params.data["value"][6] +
                    "kg"
                  );
                }
              },
              backgroundColor: "rgba(255,255,255,0.8)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#333333",
              },
            },
            label: {
              formatter: (param) => param.name.slice(0, 2),
              fontSize: 11,
              offset: [0, 2],
              position: "bottom",
              textBorderColor: "#333333",
              textShadowColor: "#000",
              textShadowBlur: 10,
              textBorderWidth: 0,
              color: "#333333",
            },
            zlevel: 2,
          },
          // 车辆呼吸动画层
          {
            data: data2,
            type: "effectScatter",
            coordinateSystem: "geo",
            symbol: "image://" + this.truckIcon,
            symbolSize: 28,
            showEffectOn: "render",
            rippleEffect: {
              period: 2.5,
              scale: 1.2,
              brushType: "stroke",
              color: "rgba(16, 185, 129, 0.4)",
            },
            itemStyle: {
              opacity: 0.6,
            },
            zlevel: 0,
          },
        ],
        //动画效果
        // animationDuration: 1000,
        // animationEasing: 'linear',
        // animationDurationUpdate: 1000
      };
      this.options = option;
    },
    //加氢站信息
    init2(name, data, data2) {
      // console.log('加氢站init_data');
      // console.log(data);
      // console.log('加氢站init_data2');
      // console.log(data2);
      let top = 45;
      let zoom = 1.05;
      let option = {
        backgroundColor: "rgba(0,0,0,0)",
        tooltip: {
          show: false,
        },
        legend: {
          show: false,
        },
        visualMap: {
          left: 20,
          bottom: 20,
          pieces: [
            { gte: 100, label: "100 座以上" }, // 不指定 max，表示 max 为无限大（Infinity）。
            { gte: 30, lte: 100, label: "30-100 座" },
            { gte: 10, lte: 30, label: "10-30 座" },
            { lte: 10, label: "1-10 座" }, // 不指定 min，表示 min 为无限大（-Infinity）。
          ],
          inRange: {
            // 渐变颜色，从小到大（绿色系）
            color: [
              "#E2F8F2",
              "#7BC69B",
              "#08703D",
              "#005E34",
              "#036437",
              "#10B981",
            ],
            // color: [
            //   "#a7f3d0",
            //   "#6ee7b7",
            //   "#34d399",
            //   "#10b981",
            //   "#059669",
            //   "#047857",
            // ],
          },
          textStyle: {
            color: "#333333",
          },
        },
        geo: {
          map: name,
          roam: false,
          selectedMode: false, //是否允许选中多个区域
          zoom: zoom,
          top: top,
          // aspectScale: 0.78,
          show: false,
        },
        series: [
          {
            name: "MAP",
            type: "map",
            map: name,
            // zlevel: 2,
            // aspectScale: 0.78,
            data: data,
            //data: [1,100],
            selectedMode: false, //是否允许选中多个区域
            showLegendSymbol: false, // 存在legend时显示
            zoom: zoom,
            geoIndex: 1,
            top: top,
            tooltip: {
              show: true,
              formatter: function (params) {
                //console.log("series 1 formatter");
                //console.log(params);
                if (params.data) {
                  //return params.name + "：" + params.data["value"][2];
                  //return params.name + "：" + params.data.vehicleTotal + "辆";
                  return `${params.name}<br>加氢站总数: ${params.data.siteTotalCount}<br>当前运营总数: ${params.data.siteCount}`;
                } else {
                  return params.name;
                }
              },
              backgroundColor: "rgba(255,255,255,0.8)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#333333",
              },
            },
            label: {
              show: false,
              color: "#000",
              // position: [-10, 0],
              formatter: function (val) {
                // console.log(val)
                if (val.data !== undefined) {
                  return val.name.slice(0, 2);
                } else {
                  return "";
                }
              },
              rich: {},
            },
            emphasis: {
              //高亮时显示
              label: {
                show: false,
              },
              itemStyle: {
                areaColor: "#e3f2fd",
                borderWidth: 1,
              },
            },
            itemStyle: {
              borderColor: "#475569",
              borderWidth: 0.5,
              areaColor: "#ffffff",
              shadowColor: "rgba(0, 0, 0, .1)",
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10,
            },
          },
          // 加氢站涟漪效果层
          {
            data: data2,
            type: "effectScatter",
            coordinateSystem: "geo",
            symbol: "circle",
            symbolSize: 20,
            itemStyle: {
              color: "#7BC69B",
              shadowBlur: 10,
              shadowColor: "#7BC69B",
            },
            showEffectOn: "render",
            rippleEffect: {
              period: 3.5,
              scale: 4,
              brushType: "stroke",
              color: "rgba(123, 198, 155, 0.6)",
            },
            zlevel: 1,
          },
          // 加氢站图标层
          {
            data: data2,
            type: "scatter",
            coordinateSystem: "geo",
            symbol: "image://" + this.stationIcon,
            symbolSize: 24,
            itemStyle: {
              borderColor: "#7BC69B",
              borderWidth: 2,
              shadowBlur: 8,
              shadowColor: "rgba(123, 198, 155, 0.5)",
            },
            legendHoverLink: true,
            tooltip: {
              show: false,
              formatter: function (params) {
                if (params.data) {
                  return (
                    params.data.name +
                    "<br> 加氢站总数：" +
                    params.data["value"][2] +
                    "<br>  当前运营总数: " +
                    params.data["value"][3]
                  );
                }
              },
              backgroundColor: "rgba(255,255,255,0.8)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#333333",
              },
            },
            label: {
              formatter: (param) => param.name.slice(0, 2),
              fontSize: 11,
              offset: [0, 2],
              position: "bottom",
              textBorderColor: "#333333",
              textShadowColor: "#000",
              textShadowBlur: 10,
              textBorderWidth: 0,
              color: "#333333",
              show: false,
            },
            zlevel: 2,
          },
          // 加氢站呼吸动画层
          {
            data: data2,
            type: "effectScatter",
            coordinateSystem: "geo",
            symbol: "image://" + this.stationIcon,
            symbolSize: 28,
            showEffectOn: "render",
            rippleEffect: {
              period: 3,
              scale: 1.2,
              brushType: "stroke",
              color: "rgba(123, 198, 155, 0.4)",
            },
            itemStyle: {
              opacity: 0.6,
            },
            zlevel: 0,
          },
        ],
        //动画效果
        // animationDuration: 1000,
        // animationEasing: 'linear',
        // animationDurationUpdate: 1000
      };
      this.options = option;
    },
    message(text) {
      this.$Message({
        text: text,
        type: "warning",
      });
    },
    mapclick() {
      if (this.echartBindClick) return;
      //单击切换到级地图，当mapCode有值,说明可以切换到下级地图
      this.$refs.CenterMap.chart.on("click", (params) => {
        console.log(params);
        let xzqData = xzqCode[params.name];
        if (xzqData) {
          this.getData(xzqData.adcode);
        } else {
          this.message("暂无下级地市!");
        }
      });
      this.echartBindClick = true;
    },
  },
  destroyed() {
    // 销毁事件监听
    this.$refs.CenterMap.chart.off("click");

    // 移除事件总线的刷新事件监听
    this.$eventBus.$off('refresh-all-data');

    if (this.charts) {
      this.echarts.dispose();
    }
  },
};
</script>
<style lang="scss" scoped>
.centermap {
  height: 100%;
  display: flex;
  flex-direction: column;

  .maptitle {
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 8px;
    padding: 0 20px;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .titletext {
      font-size: 28px;
      font-weight: 700;
      letter-spacing: 2px;
      background: linear-gradient(
        92deg,
        #00d4aa 0%,
        #1de9b6 48.8525390625%,
        #00bfa5 100%
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 8px;
    }
    .titletextBefore {
      font-size: 16px;
      font-weight: 600;
      letter-spacing: 1px;
      color: #666666;
    }
  }

  .mapwrap {
    flex: 1;
    width: 100%;
    box-sizing: border-box;
    position: relative;

    .map-card {
      width: 100%;
      height: 100%;
      background: #ffffff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      padding: 16px;
      box-sizing: border-box;
      position: relative;
    }

    .quanguo1 {
      position: absolute;
      right: 20px;
      top: 16px;
      padding: 6px 16px;
      border-radius: 8px;
      border: 1px solid #a7f3d0;
      box-sizing: border-box;
      background: #d1fae5;
      cursor: pointer;
      z-index: 999;
      text-align: center;
      color: #047857;
      font-family: "PingFang SC";
      font-weight: 600;
      font-size: 14px;
      line-height: 15px;
    }
    .quanguo {
      position: absolute;
      right: 20px;
      top: 56px;
    }
    .quanguo2 {
      position: absolute;
      left: 20px;
      top: 16px;
      border-radius: 6px;
      color: #1e293b;
      display: flex;
      align-items: center;
      font-family: "PingFang SC";
      font-weight: 600;
      font-size: 20px;
      line-height: 24px;
      text-align: center;
      cursor: pointer;
      z-index: 999;
      .btn {
        width: 102px;
        height: 32px;
        color: #ffffff;
        font-family: "PingFang SC";
        font-weight: 400;
        font-size: 14px;
        padding-left: 10px;
        line-height: 32px;
        background-repeat: no-repeat;
        background-image: url("../../assets/img/new/btn.png");
      }
    }

    .quanguo3 {
      position: absolute;
      left: 20px;
      top: 52px;
      padding: 6px 16px;
      background: #ffffff;
      border: 1px solid #00d4aa;
      border-radius: 6px;
      color: #333333;
      font-size: 13px;
      font-weight: 500;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
      z-index: 999;

      &:hover {
        background: rgba(0, 212, 170, 0.1);
      }
    }
  }
}
</style>
