<template>
  <div class="map-container">
    <div id="map" class="map"></div>
    <div v-if="hoverInfo" :style="hoverStyle" class="hover-info">
      <h3>{{hoverInfo.fieldName}}</h3>
      <div>
        <p><span>风场编号</span><span>{{hoverInfo.codeNumber}}</span></p>
        <p><span>空气密度</span><span>{{hoverInfo.density}}</span></p>
        <p><span>总额定容量</span><span>{{hoverInfo.ratedCapacityNumber}}</span></p>
        <p><span>经度</span><span>{{hoverInfo.longitude}}</span></p>
        <p><span>纬度</span><span>{{hoverInfo.latitude}}</span></p>
        <p><span>海拔高度</span><span>{{hoverInfo.elevationHeight}}</span></p>
        <p><span>最新分析时间</span><span> {{ $formatDate(hoverInfo.wfbrCreateTime) }}</span></p>
      </div>
    </div>

    <div v-if="hoverfengji" :style="hoverfengjiStyle" class="hover-fengji">
      <h3>{{hoverfengji.engineName}}</h3>
      <div>
        <p><span>风机编号</span><span>{{hoverfengji.engineCode}}</span></p>
        <p><span>额定容量</span><span>{{hoverfengji.ratedCapacity}}</span></p>
        <p><span>海拔高度</span><span>{{hoverfengji.elevationHeight}}</span></p>
        <p><span>轮毂高度</span><span>{{hoverfengji.hubHeight}}</span></p>
        <p><span>经度</span><span>{{hoverfengji.longitude}}</span></p>
        <p><span>维度</span><span>{{hoverfengji.latitude}}</span></p>
        <p>是否标杆风机 <span>{{hoverfengji.sightcing == 1 ? '是' : '否'}}</span></p>
        <p><span>额定风速</span><span>{{hoverfengji.rated_wind_speed}}</span></p>
        <p><span>切入风速</span><span>{{hoverfengji.ratedCutInWindspeed}}</span></p>
        <p><span>切出风速</span><span>{{hoverfengji.ratedCutOutWindspeed}}</span></p>
      </div>
    </div>
    <div v-if="hoverta" :style="hovertaStyle" class="hover-ta">
      <h3>{{hoverta.anemometerName}}</h3>
      <div>
        <p><span>测风塔编号</span><span>{{hoverta.anemometerCode}}</span></p>

        <p><span>经度</span><span>{{hoverta.longitude}}</span></p>
        <p><span>维度</span><span>{{hoverta.anemometerName}}</span></p>
        <p><span>状态</span><span>{{hoverta.latitude}}</span></p>
        <p><span>测风塔高度</span><span>{{hoverta.anemometerHeightStrings}}</span></p>

      </div>
    </div>
  </div>
</template>


<script>
import "ol/ol.css";
import { Map, View, Feature } from "ol";
import TileLayer from "ol/layer/Tile.js";
import { XYZ } from "ol/source";
import { fromLonLat } from "ol/proj";
import { Vector } from "ol/source";
import { Vector as VectorLayer } from "ol/layer";
import { Point } from "ol/geom";
import { Icon, Style } from "ol/style";
import ZoomSlider from "ol/control/ZoomSlider.js";
import { defaults as defaultControls } from "ol/control.js";

import icon01 from "../../assets/img/icon01.png";
import icon02 from "../../assets/img/icon02.png";
import icon03 from "../../assets/img/icon03.png";
import icon04 from "../../assets/img/icon04.png";
import icon05 from "../../assets/img/icon05.png";
import defaultIcon from "../../assets/img/icon05.png";
export default {
  props: {
    windEngineGroupByFieldCodeDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  name: "T-map",
  data() {
    return {
      hoverInfo: null,
      hoverStyle: {
        position: "absolute",
        left: "0px", 
        top: "0px",
      },
      hoverfengji: null,
      hoverfengjiStyle: {
        position: "absolute",
        left: "0px",
        top: "0px",
      },
      hoverta: null,
      hovertaStyle: {
        position: "absolute",
        left: "0px",
        top: "0px",
      },
    };
  },
  watch: {
    windEngineGroupByFieldCodeDetail: {
      handler(data) {
        if (data) {
        }
      },
      deep: true, // 深度监听
    },
  },
  mounted() {
    this.map = new Map({
      target: "map",
      view: new View({
        projection: "EPSG:4326",
        center: fromLonLat([116.389, 39.903]), //地图中心
        zoom: 5, //默认缩放级别
        minZoom: 5, //最小缩放级别
        maxZoom: 12, //最大缩放级别
        extent: [
          70.3671875, 18.14576369243164, 134.92927612304688, 55.667146064662596,
        ],
      }),
      layers: [
        new TileLayer({
          source: new XYZ({
            // url: "http://127.0.0.1:8010/tiles/{z}/{x}/{y}.png", //本地
            url: "http://192.168.50.235/tiles/{z}/{x}/{y}.png", //内外
          }),
        }),
        new VectorLayer({
          id: "marker",
          source: new Vector(),
        }),
      ],
      controls: defaultControls().extend([new ZoomSlider()]),
    });
    // console.log(this.map.getView().calculateExtent());
    this.initEvent();
  },
  methods: {
    /**
     * 地图上打点
     * @param data
     */
    addMarker(data = { point: [120.2, 30.35], val: "1" }) {
      console.log(data);
      const layer = this.map
        .getLayers()
        .getArray()
        .find((element) => {
          return element.get("id") === "marker";
        });
      const source = layer.getSource();

      const iconSrc = this.getIconForValue(data.val);

      const feature = new Feature({
        geometry: new Point(fromLonLat(data.point, "EPSG:4326")),
        name: "marker",
        data,
      });
      feature.setStyle(
        new Style({
          image: new Icon({
            src: iconSrc,
            scale: [0.3, 0.3],
            anchor: [0.5, 1],
            opacity: 1,
          }),
        })
      );
      source.addFeature(feature);
    },
    /**
     * 地图上打点
     * @param data
     */
    clearMarkers() {
      const layer = this.map
        .getLayers()
        .getArray()
        .find((element) => {
          return element.get("id") === "marker";
        });
      if (layer) {
        const source = layer.getSource();
        source.clear(); // 清空所有特征
      }
    },
    getIconForValue(val) {

      switch (val) {
        case "-1":
        case -1:
          return icon01;
        case 0:
        case "0":
          return icon02;
        case 1:
        case "1":
          return icon03;
        case "4":
          return icon04;
        case "5":
          return icon05;
        default:
          return defaultIcon;
      }
    },

    /**
     * 初始化地图事件
     */
    initEvent() {
      this.map.on("pointermove", (evt) => {
        const features = this.map.getFeaturesAtPixel(evt.pixel, {
          hitTolerance: 1,
        });
        if (features && features.length > 0) {
          const feature = features.at(0);
          const val = feature.get("data").val;
          if (val == "1") {
            this.hoverInfo = feature.get("data");
            this.hoverStyle.left = `${evt.pixel[0] + 10}px`;
            this.hoverStyle.top = `${evt.pixel[1] + 10}px`;
          } else if (val == "4") {
            this.hoverfengji = feature.get("data");
            this.hoverfengjiStyle.left = `${evt.pixel[0] + 10}px`;
            this.hoverfengjiStyle.top = `${evt.pixel[1] + 10}px`;
            this.currentFeatureData = feature.get("data"); // Store the feature data for click event
          } else if (val == "5") {
            this.hoverta = feature.get("data");
            this.hovertaStyle.left = `${evt.pixel[0] + 10}px`;
            this.hovertaStyle.top = `${evt.pixel[1] + 10}px`;
            this.currentFeatureData = feature.get("data"); // Store the feature data for click event
          } else {
            this.hoverInfo = null;
            this.hoverfengji = false;
            this.hoverta = false;
            this.currentFeatureData = null; // Ensure no stored feature data if val is not 3 or 4
          }
        } else {
          this.hoverInfo = null;
          this.hoverfengji = false;
          this.hoverta = false;
          this.currentFeatureData = null; // Ensure no stored feature data if there are no features
        }
      });

      this.map.on("click", (evt) => {
        const features = this.map.getFeaturesAtPixel(evt.pixel, {
          hitTolerance: 1,
        });
        if (features && features.length > 0) {
          const feature = features.at(0);
          this.$emit("feature-click", feature.get("data"));
        }
        // Check if there's stored feature data and if it's a val === "4" feature
        if (this.currentFeatureData && this.currentFeatureData.val === "4") {
          // Handle click event for val === "4"
          this.handleFeatureClick(this.currentFeatureData);
        }
      });
    },

    handleFeatureClick(featureData) {
      // Implement your logic to handle the click event for val === "4"
      // For example, emit an event or perform some action
      console.log("Feature with val === '4' clicked:", featureData);
    },

    /**
     * 平移缩放
     * @param data
     */
    moveAndZoom(data = { point: [120.2, 30.35], zoom: 15 }) {
      this.map.getView().animate({
        center: fromLonLat(data.point, "EPSG:4326"),
        zoom: data.zoom,
        duration: 2000,
      });
    },
  },
};
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.map {
  width: 100%;
  height: 100%;
}

.hover-info {
  position: absolute;
  color: white;
  padding: 0px;
  z-index: 100;

  h3 {
    background-color: #008080cc;
    width: 240px;
    padding: 5px 10px;
    font-size: 16px;
  }

  div {
    background-color: #00808097;
    width: 240px;
    font-size: 12px;

    p {
      padding: 5px 10px;
      display: flex;
      justify-content: space-between;
    }
  }
}

.hover-fengji {
  position: absolute;
  color: white;
  padding: 0px;
  z-index: 100;

  h3 {
    background-color: #027cb4cc;
    width: 240px;
    padding: 5px 10px;
    font-size: 16px;
  }

  div {
    background-color: #027cb49e;
    width: 240px;
    font-size: 12px;

    p {
      padding: 5px 10px;
      display: flex;
      justify-content: space-between;
    }
  }
}

.hover-ta {
  position: absolute;
  color: white;
  padding: 0px;
  z-index: 100;

  h3 {
    background-color: #d90019b2;
    width: 240px;
    padding: 5px 10px;
    font-size: 16px;
  }

  div {
    background-color: #d9001994;
    width: 240px;
    font-size: 12px;

    p {
      padding: 5px 10px;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
