<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 }} kg/m3</span>
        </p>
        <p>
          <span>总额定容量</span
          ><span
            >{{
              hoverInfo?.ratedCapacityNumber
                ? hoverInfo.ratedCapacityNumber
                : 0
            }}/KW</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> {{ $formatDateTWO(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 ? hoverfengji?.ratedCapacity : 0
            }}
            /KW</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.ratedWindSpeed }} m/s</span>
        </p>
        <p>
          <span>切入风速</span
          ><span>{{ hoverfengji.ratedCutInWindspeed }} m/s</span>
        </p>
        <p>
          <span>切出风速</span
          ><span>{{ hoverfengji.ratedCutOutWindspeed }} m/s</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.latitude }}</span>
        </p>
        <!-- <p>
          <span>状态</span><span>{{  }}</span>
        </p> -->
        <p>
          <span>测风塔高度</span
          ><span>{{ hoverta.anemometerHeightStrings }}/米</span>
        </p>
      </div>
    </div>

    <el-dialog title="异常描述" :visible.sync="dialogVisible" width="50%">
      <el-table :data="tableData" max-height="500" style="width: 100%">
        <el-table-column prop="analysisTypeName" label="类型" width="300">
        </el-table-column>
        <el-table-column prop="errDesc" label="描述"> </el-table-column>
      </el-table>
    </el-dialog>
  </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 icon06 from "../../assets/img/icon06.png";
import defaultIcon from "../../assets/img/icon01.png";
import { queryErrDescByEngine } from "@/api/ledger.js";

export default {
  props: {
    windEngineGroupByFieldCodeDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  name: "T-map",
  data() {
    return {
      dialogVisible: false,
      tableData: [],
      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: 15, //最大缩放级别
        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", //内网
            // url: "http://106.120.102.238:18000/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" }) {
      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 "10":
        case 10:
          return icon01;
        case 0:
        case "0":
          return icon02;
        case 20:
        case "20":
          return icon02;
        case 1:
        case "1":
          return icon03;
        case 30:
        case "30":
          return icon03;
        case "4":
          return icon04;
        case "5":
          return icon05;
        case "6":
          return icon06;
        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] - 150}px`;
          } else if (val == "4") {
            this.hoverfengji = feature.get("data");
            this.hoverfengjiStyle.left = `${evt.pixel[0] + 10}px`;
            this.hoverfengjiStyle.top = `${evt.pixel[1] - 150}px`;
            this.currentFeatureData = feature.get("data");
          } else if (val == "5") {
            this.hoverta = feature.get("data");
            this.hovertaStyle.left = `${evt.pixel[0] + 10}px`;
            this.hovertaStyle.top = `${evt.pixel[1] - 150}px`;
            this.currentFeatureData = feature.get("data");
          } else if (val == "6") {
            this.currentFeatureData = feature.get("data");
          } else {
            this.hoverInfo = null;
            this.hoverfengji = false;
            this.hoverta = false;
            this.currentFeatureData = null;
          }
        } else {
          this.hoverInfo = null;
          this.hoverfengji = false;
          this.hoverta = false;
          this.currentFeatureData = null;
        }
      });

      this.map.on("click", (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 === "6") {
            this.handleFeatureClick(feature.get("data"));
          } else {
            this.$emit("feature-click", feature.get("data"));
          }
        } else if (
          this.currentFeatureData &&
          this.currentFeatureData.val === "6"
        ) {
          this.handleFeatureClick(this.currentFeatureData);
        }
      });
    },
    handleFeatureClick(featureData) {
      let dateArr = {
        batchCode: this.$route.query.batchCode,
        engineCode: featureData.engineCode,
      };
      queryErrDescByEngine(dateArr).then((res) => {
        this.dialogVisible = true;
        this.tableData = res.data;
      });
    },

    /**
     * 平移缩放
     * @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>
