<!--
 * @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">
      <div class="zuo"></div>
      <!-- <span class="titletextBefore">今年累计减碳<span class="titletext">{{ maptitle }}</span>kg</span> -->
      <span class="titletextBefore">今年累计减碳<span class="titletext">{{ maptitle }}</span>吨</span>
      <div class="you"></div>
    </div>
    <div class="mapwrap">
      <dv-border-box-13>
        <div class="quanguo2" @click="changeShow1()" :style="{ backgroundColor: currentBgColor2 }">
           <div >车辆信息</div>
        </div>
        <div class="quanguo3" @click="changeShow2()" :style="{ backgroundColor: currentBgColor3 }">
          <div >加氢站</div>
        </div>

        <div class="quanguo" @click="getData('china')" v-if="code !== 'china'">
          中国
        </div>

        <div  v-if="showType === 1" class="quanguo1" @click="goToPage()">
          车辆实况
        </div>
        
        <Echart id="CenterMap" :options="options" ref="CenterMap" />
        <!-- <dv-flyline-chart :config="config" style="width:100%;height:100%;" /> -->
      </dv-border-box-13>
    </div>
  </div>
</template>

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

  mounted() {
    console.log(this.xzqCode);
    this.getYearData();
    //this.getData("china");
    this.showType = 1;
    this.currentBgColor2 = '#158e8e';
    this.getData(this.code);
  },
  methods: {
    changeShow1(){

      this.showType = 1;
      this.currentBgColor2 = '#158e8e';
      this.currentBgColor3 = '';
      this.getData(this.code);
    },
    changeShow2(){
      this.currentBgColor2 = '';  
      this.currentBgColor3 = '#158e8e';          
      this.showType = 2;

      this.getData(this.code);
    },
    goToPage() {
      window.open("http://localhost:9528/vehicle-zpSituation?"+this.code, "_blank");

      //window.open("http://47.100.49.118:8090/vehicle-zpSituation?"+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);
          //单位kg
          // this.maptitle = res.data.yearCarbon;
          //单位吨
          this.maptitle = res.data.yearCarbonTon;
        });
    },
    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.vehicleTotal).concat(item.onLineCount).concat(item.dayMileage).concat(item.dayHydrogen).concat(item.dayCarbon),
          });
        }
      });
      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: [              
              // "#c3d7df",
              // "#5cb3cc",
              // "#8abcd1",
              // "#66a9c9",
              // "#2f90b9",
              // "#1781b5",
              "#6EC3F7",
              "#2196F3",
              "#1565C0",
              "#0D47A1",
            ],
          },
          textStyle: {
            color: "#fff",
          },
        },
        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,
            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.dayCarbon}kg<br>当日用氢量: ${params.data.dayHydrogen}kg<br>当日里程: ${params.data.dayMileage}km`;
                } else {
                  return params.name;
                }
              },
              backgroundColor: "rgba(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
            },
            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: "#389BB7",
                borderWidth: 1,
              },
            },
            itemStyle: {
              borderColor: "rgba(147, 235, 248, .8)",
              borderWidth: 1,
              areaColor: {
                type: "radial",
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(147, 235, 248, 0)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(147, 235, 248, .2)", // 100% 处的颜色
                  },
                ],
                globalCoord: false, // 缺为 false
              },
              shadowColor: "rgba(128, 217, 248, .3)",
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10,
            },
          },
          {
            data: data2,
            type: "effectScatter",
            coordinateSystem: "geo",
            symbolSize: function (val) {
              return 4;
              // return val[2] / 50;
            },
            legendHoverLink: true,
            showEffectOn: "render",
            rippleEffect: {
              // period: 4,
              scale: 6,
              color: "rgba(255,255,255, 1)",
              brushType: "fill",
            },
            tooltip: {
              show: false,
              //trigger: "item",
              formatter: function (params) {
                //console.log("series 2 formatter");
                //console.log(params);
                if (params.data) {
                  console.log("params.data");
                  console.log(params.data);
                  console.log(params.data.name + "\n 车辆总数："+params.data["value"][2] + "\n  GPS在线总数：" + params.data["value"][3]);
                  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";
                  //return '${params.name} <br />车辆总数：${params.data[value][2]} <br />  GPS在线总数：${ params.data.[value][3]}';
                } 
              },
              backgroundColor: "rgba(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
            },
            label: {              
              formatter: (param) => {
                //return param.name.slice(0, 2) + "\n 车辆总数："+param.data["value"][2] + "\n GPS在线数："+param.data["value"][3];   //2025.03.28

                return param.name.slice(0, 2) ;
              },
              fontSize: 11,
              offset: [0, 2],
              position: "bottom",
              textBorderColor: "#fff",
              textShadowColor: "#000",
              textShadowBlur: 10,
              textBorderWidth: 0,
              color: "#FFF",
              show: true,
            },
            // colorBy: "data",
            itemStyle: {
              color: "rgba(255,255,255,1)",
              borderColor: "rgba(2255,255,255,2)",
              borderWidth: 4,
              shadowColor: "#000",
              shadowBlur: 10,
            },
          },
        ],
         //动画效果
            // 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: [              
              // "#c3d7df",
              // "#5cb3cc",
              // "#8abcd1",
              // "#66a9c9",
              // "#2f90b9",
              // "#1781b5",
              "#6EC3F7",
              "#2196F3",
              "#1565C0",
              "#0D47A1",
            ],
          },
          textStyle: {
            color: "#fff",
          },
        },
        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,
            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(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
            },
            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: "#389BB7",
                borderWidth: 1,
              },
            },
            itemStyle: {
              borderColor: "rgba(147, 235, 248, .8)",
              borderWidth: 1,
              areaColor: {
                type: "radial",
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(147, 235, 248, 0)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(147, 235, 248, .2)", // 100% 处的颜色
                  },
                ],
                globalCoord: false, // 缺为 false
              },
              shadowColor: "rgba(128, 217, 248, .3)",
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10,
            },
          },
          {
            data: data2,
            type: "effectScatter",
            coordinateSystem: "geo",
            symbolSize: function (val) {
              return 4;
              // return val[2] / 50;
            },
            legendHoverLink: true,
            showEffectOn: "render",
            rippleEffect: {
              // period: 4,
              scale: 6,
              color: "rgba(255,255,255, 1)",
              brushType: "fill",
            },
            tooltip: {
              show: false,
              //trigger: "item",
              formatter: function (params) {
                //console.log("series 2 formatter");
                //console.log(params);
                if (params.data) {
                  console.log("params.data");
                  console.log(params.data);
                  console.log(params.data.name + "\n 车辆总数："+params.data["value"][2] + "\n  GPS在线总数：" + params.data["value"][3]);
                  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";
                  //return '${params.name} <br />车辆总数：${params.data[value][2]} <br />  GPS在线总数：${ params.data.[value][3]}';
                } 
              },
              backgroundColor: "rgba(0,0,0,.6)",
              borderColor: "rgba(147, 235, 248, .8)",
              textStyle: {
                color: "#FFF",
              },
            },
            label: {              
              formatter: (param) => {
                //return param.name.slice(0, 2) + "\n 车辆总数："+param.data["value"][2] + "\n GPS在线数："+param.data["value"][3];   //2025.03.28
                //return param.name.slice(0, 2) + "\n "+param.data["value"][2];       //2025.03.31
                return param.name.slice(0, 2) ;
              },
              fontSize: 11,
              offset: [0, 2],
              position: "bottom",
              textBorderColor: "#fff",
              textShadowColor: "#000",
              textShadowBlur: 10,
              textBorderWidth: 0,
              color: "#FFF",
              show: true,
            },
            // colorBy: "data",
            itemStyle: {
              color: "rgba(255,255,255,1)",
              borderColor: "rgba(2255,255,255,2)",
              borderWidth: 4,
              shadowColor: "#000",
              shadowBlur: 10,
            },
          },
        ],
         //动画效果
            // 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");
    if (this.charts) {
      this.echarts.dispose();
    }
  },
};
</script>
<style lang="scss" scoped>
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 32px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(
        92deg,
        #0072ff 0%,
        #00eaff 48.8525390625%,
        #01aaff 100%
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }
    .titletextBefore {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      color: white;
      margin: 0 10px;
    }
    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("../../assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("../../assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 548px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -25px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
        0 0 6px rgba(0, 237, 237, 0.4);
    }

    .quanguo1 {
      position: absolute;
    right: 20px;
    top: 24px;
    width: 100px;
    height: 28px;
    border: 1px solid #00eded;
    border-radius: 10px;
    color: white;
    text-align: center;
    line-height: 26px;
    letter-spacing: 6px;
    cursor: pointer;
    box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5), 0 0 6px rgba(0, 237, 237, 0.4);
    font-family: "微软雅黑", sans-serif;
    z-index: 9999;
    }
    .quanguo2 {
      position: absolute;
      left: 20px;
      top: 24px;
      width: 100px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: white;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5), 0 0 6px rgba(0, 237, 237, 0.4);
      font-family: "微软雅黑", sans-serif;
      z-index: 9999;
    }

    .quanguo3 {
      position: absolute;
      left: 20px;
      top: 60px;
      width: 100px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: white;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5), 0 0 6px rgba(0, 237, 237, 0.4);
      font-family: "微软雅黑", sans-serif;
      z-index: 9999;
    }
  }
}
</style>
