<template>
  <div class="map">
    <div class="legend">
      <div class="item selected" v-if="data && data.showzhd">
        <img src="../assets/images/map-icon-fire.png" />火灾扑救
      </div>
      <div
        class="item"
        v-if="data && !data.showzhd"
        :class="showType.indexOf('currentJzKey') >= 0 ? 'selected' : ''"
        @click="changeType('currentJzKey')"
      >
        <img src="../assets/images/map-icon-current-build.png" />当前建筑
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('xfscKey') >= 0 ? 'selected' : ''"
        @click="changeType('xfscKey')"
      >
        <img src="../assets/images/map-icon-xfsc.png" />消防水池
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('trsyKey') >= 0 ? 'selected' : ''"
        @click="changeType('trsyKey')"
      >
        <img src="../assets/images/map-icon-trsy.png" />天然水源
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('xhsKey') >= 0 ? 'selected' : ''"
        @click="changeType('xhsKey')"
      >
        <img src="../assets/images/map-icon-pressure.png" />室外消火栓
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('szxhsKey') >= 0 ? 'selected' : ''"
        @click="changeType('szxhsKey')"
      >
        <img src="../assets/images/map-icon-szxhs.png" />市政消火栓
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('jzKey') >= 0 ? 'selected' : ''"
        @click="changeType('jzKey')"
      >
        <img src="../assets/images/map-icon-build.png" />高层建筑
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('xfzKey') >= 0 ? 'selected' : ''"
        @click="changeType('xfzKey')"
      >
        <img src="../assets/images/map-icon-119.png" />微型消防站
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('jgKey') >= 0 ? 'selected' : ''"
        @click="changeType('jgKey')"
      >
        <img src="../assets/images/map-icon-micstation.png" />消防站
      </div>
      <div
        class="item"
        v-if="data"
        :class="showType.indexOf('xfcKey') >= 0 ? 'selected' : ''"
        @click="changeType('xfcKey')"
      >
        <img
          src="../assets/images/map-icon-car.png"
          style="height: 15px"
        />消防车
      </div>
    </div>
    <div id="map-container"></div>
    <!-- 信息弹窗 -->
    <div class="info-window" ref="infoWindow" v-if="firePoint">
      <div class="info-content">
        <div class="title">
          <div class="txt">重点部位提醒</div>
          <div class="close" @click="closeInfoWindow"></div>
        </div>
        <div class="content">
          <div class="row blue">
            {{ firePoint.buildName }}存在{{ firePoint.depts.length }}个重点部位
          </div>
          <div class="row" v-for="(item, i) in firePoint.depts" :key="i">
            {{ item }}
          </div>
        </div>
        <div class="l-t"></div>
        <div class="r-t"></div>
        <div class="l-b"></div>
        <div class="r-b"></div>
        <div class="c-b"></div>
      </div>
      <div class="info-bottom"></div>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import mapIconBuild from "../assets/images/map-icon-build.png"; // 高层建筑
import mapIconCurrentBuild from "../assets/images/map-icon-current-build.png"; // 高层建筑
import mapIconSwxhs from "../assets/images/map-icon-pressure.png"; // 室外消火栓
import mapIconCar from "../assets/images/map-icon-car.png"; // 消防车
import mapIconCamera from "../assets/images/map-icon-camera.png"; // 摄像头
import mapIconMicstation from "../assets/images/map-icon-119.png"; // 微型站
import mapIconStation from "../assets/images/map-icon-micstation.png"; // 消防站
import mapIconFire from "../assets/images/map-icon-fire.png"; // 着火点
import mapIconSzxhs from "../assets/images/map-icon-szxhs.png"; // 市政消火栓
import mapIconTrsy from "../assets/images/map-icon-trsy.png"; // 天然水源
import mapIconSfsc from "../assets/images/map-icon-xfsc.png"; // 消防水池

import { getZy } from "@/api/map.js";
export default {
  name: "MapContainer",
  components: {},
  data() {
    return {
      radius: 300,
      center: [],
      markers: [],
      originMarkers: [],
      firePoint: null,
      icons: {
        currentJzKey: {
          image: mapIconCurrentBuild,
          size: [70, 70],
          imageSize: [70, 70],
        },
        jzKey: {
          image: mapIconBuild,
          size: [21, 30],
          imageSize: [21, 30],
        },
        xhsKey: {
          image: mapIconSwxhs,
          size: [21, 30],
          imageSize: [21, 30],
        },
        szxhsKey: {
          image: mapIconSzxhs,
          size: [21, 30],
          imageSize: [21, 30],
        },
        trsyKey: {
          image: mapIconTrsy,
          size: [21, 30],
          imageSize: [21, 30],
        },
        xfscKey: {
          image: mapIconSfsc,
          size: [21, 30],
          imageSize: [21, 30],
        },
        xfcKey: {
          image: mapIconCar,
          size: [35, 23],
          imageSize: [35, 23],
        },
        lldKey: {
          image: mapIconCamera,
          size: [24, 24],
          imageSize: [24, 24],
        },
        xfzKey: {
          image: mapIconMicstation,
          size: [49, 53],
          imageSize: [49, 53],
        },
        jgKey: {
          image: mapIconStation,
          size: [49, 53],
          imageSize: [49, 53],
        },
      },
      showType: ["currentJzKey"],
      loading: false,
      markerCache: {
        "currentJzKey": [],
        "xfscKey": [],
        "trsyKey": [],
        "xhsKey": [],
        "szxhsKey": [],
        "jzKey": [],
        "xfzKey": [],
        "jgKey": [],
        "xfcKey": []
      }
    };
  },
  props: {
    id: {
      type: Number,
      default: 1,
    },
    data: {
      type: Object,
      default: null,
    },
  },
  mounted() {
    if (this.data.showzhd) {
      this.showType = [
        "currentJzKey",
        "xfscKey",
        "trsyKey",
        "xhsKey",
        "szxhsKey",
        "jzKey",
        "xfzKey",
        "jgKey",
        "xfcKey",
      ];
    } else {
      this.showType = ["currentJzKey"];
    }
    this.getData();
  },
  methods: {
    changeType(type) {
      if (this.loading) {
        return;
      }
      let showType = JSON.parse(JSON.stringify(this.showType));
      console.log(this.markerCache)
      if (showType.indexOf(type) >= 0) {
        showType = showType.filter((p) => p !== type);
        this.markerCache[type].forEach(marker => {
          this.map.remove(marker)
        })
      } else {
        showType.push(type);
        this.markerCache[type].forEach(marker => {
          this.map.add(marker)
        })
      }
      this.showType = showType;
    },
    async getData() {
      if (this.loading) {
        return;
      }
      this.center = [this.data.jd, this.data.wd];

      // 标志物
      this.loading = true;
      const res = await getZy({
        lon: this.data.jd,
        lat: this.data.wd,
        mi: this.radius,
      });
      const markers = [];
      if (this.data.showzhd) {
        // 着火点
        this.firePoint = {
          position: [this.data.jd, this.data.wd],
          buildName: this.data.jzmc,
          depts: this.data.zl ? this.data.zl.split(",") : [],
        };
      } else {
        // 标识当前建筑
        for (let i = 0; i < res.data.length; i++) {
          const p = res.data[i];
          if (p.type === "jzKey") {
            try {
              const d = JSON.parse(p.data);
              if (d.jd === this.data.jd && d.wd === this.data.wd) {
                p.type = "currentJzKey";
                break;
              }
            } catch (e) {
              console.log(p);
            }
          }
        }
      }

      // console.log(res.data);
      if (res.data) {
        res.data.forEach((p, i) => {
          if (this.showType.indexOf(p.type) >= 0 && p.lon && p.lat) {
            markers.push({
              icon: p.type,
              position: [p.lon, p.lat],
              anchor: "bottom-center",
              data: JSON.parse(p.data),
            });
          }
        });
      }
      this.markers = markers;
      this.initMap().then(() => {
        if (this.showType.length === 1 && this.showType[0] === "currentJzKey") {
          // 缓存所有的节点数据
          console.log(res.data.filter(p => p.type !== 'currentJzKey' || p.type !== 'jzKey'))
          this.cacheAllMarkers(res.data.filter(p => p.type !== 'currentJzKey' || p.type !== 'jzKey').map(p => ({
            icon: p.type,
            position: [p.lon, p.lat],
            anchor: "bottom-center",
            data: JSON.parse(p.data),
          })))
        }
      });
    },
    async initMap() {
      await AMapLoader.load({
        key: "4776c927b5ebe35e9e33e5b14ec78b8f", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [""], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("map-container", {
            //设置地图容器id
            // viewMode: "3D", //是否为3D地图模式
            zoom: 17, //初始化地图级别
            center: this.center, //初始化地图中心点位置
            mapStyle: "amap://styles/grey",
          });

          // console.log(this.markers);

          // 设置覆盖物
          if (this.markers && this.markers.length > 0) {
            const markers = [];
            this.markers.forEach((p, i) => {
              const type = p.icon;
              let infoContent = [];
              if (type === "jzKey" || type === "currentJzKey") {
                infoContent.push(p.data.gcjzmc);
                infoContent.push(p.data.xxdz);
                infoContent.push(p.data.jzdx);
                infoContent.push("建筑高度：" + p.data.gd + "m");
                infoContent.push("建成年代：" + p.data.jcnd + "年");
              } else if (type === "xhsKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "szxhsKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "trsyKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "xfscKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "xfcKey") {
                infoContent.push(p.data.cph);
                infoContent.push(p.data.speed + "公里/小时");
              } else if (type === "lldKey") {
                infoContent.push(p.data.deviceName);
                infoContent.push(p.data.cameraType);
              } else if (type === "xfzKey") {
                infoContent.push(p.data.mc);
                infoContent.push("消防站（队站）");
                infoContent.push(p.data.fzr + " " + p.data.fzrLxdh);
              } else if (type === "jgKey") {
                infoContent.push(p.data.dwmc);
                infoContent.push("微型消防站");
                infoContent.push(p.data.lxr + " " + p.data.lxdh);
              }

              const icon = JSON.parse(JSON.stringify(this.icons[p.icon]));
              icon.size = new AMap.Size(icon.size[0], icon.size[1]);
              icon.imageSize = new AMap.Size(
                icon.imageSize[0],
                icon.imageSize[1]
              );
              p.icon = new AMap.Icon(icon);
              var marker = new AMap.Marker(p);
              // // this.map.add(marker);
              let content = [
                "<div class='info_box_contant' style=\"line-height: 30px;min-width: 250px; padding: 20px; font-size: 20px; color: #7ea2ff; font-family: 'Abel';  background: rgba(0, 0, 0, 0.82);\">" +
                  infoContent.join("<br />") +
                  " </div>",
              ];
              const infoWindow = new AMap.InfoWindow({
                isCustom: true, //使用自定义窗体
                content: content.join("<br>"),
                offset: new AMap.Pixel(0, -70),
              });



              marker.on("mouseover", (e) => {
                infoWindow.open(this.map, p.position); //后面的参数指的是经纬度，在此显示窗口
              });

              marker.on("mouseout", (e) => {
                infoWindow.close();
              });
              this.markerCache[type].push(marker)
              markers.push(marker);
            });
            this.map.add(markers);
          }

          // 设置着火点
          if (this.firePoint) {
            this.addFirePoint();
          }

          this.map.setFitView();
          this.loading = false;
        })
        .catch((e) => {
          console.log(e);
        });
    },
    addFirePoint() {
      if (!this.firePoint) {
        return;
      }
      const self = this;
      // 着火点
      var markerFire = new AMap.Marker({
        icon: mapIconFire,
        position: this.firePoint.position,
        anchor: "center",
      });
      markerFire.on("click", function () {
        self.addInfoWindow();
      });
      this.map.add(markerFire);

      // 范围
      var circle = new AMap.Circle({
        center: new AMap.LngLat(
          this.firePoint.position[0],
          this.firePoint.position[1]
        ), // 圆心位置
        radius: this.radius, // 半径
        strokeColor: "rgba(255, 0, 61)", // 线颜色
        strokeOpacity: 0.6, // 线透明度
        strokeWeight: 1, // 线粗细度
        fillColor: "rgba(255, 0, 61)", // 填充颜色
        fillOpacity: 0.08, // 填充透明度
      });
      this.map.add(circle);

      // 信息窗口
      this.addInfoWindow();
    },
    addInfoWindow() {
      if (!this.firePoint) {
        return;
      }
      // 弹窗
      var infoWindow = new AMap.InfoWindow({
        isCustom: true,
        content: this.$refs.infoWindow,
        offset: new AMap.Pixel(0, -45),
        position: this.center,
      });
      infoWindow.open(
        this.map,
        new AMap.LngLat(this.firePoint.position[0], this.firePoint.position[1])
      );
    },
    cacheAllMarkers(markerInfos) {
      if (markerInfos && markerInfos.length > 0) {
            const markers = [];
            markerInfos.forEach((p, i) => {
              const type = p.icon;
              let infoContent = [];
              if (type === "jzKey" || type === "currentJzKey") {
                infoContent.push(p.data.gcjzmc);
                infoContent.push(p.data.xxdz);
                infoContent.push(p.data.jzdx);
                infoContent.push("建筑高度：" + p.data.gd + "m");
                infoContent.push("建成年代：" + p.data.jcnd + "年");
              } else if (type === "xhsKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "szxhsKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "trsyKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "xfscKey") {
                infoContent.push(p.data.code);
                infoContent.push(p.data.sylx);
                infoContent.push(p.data.address);
              } else if (type === "xfcKey") {
                infoContent.push(p.data.cph);
                infoContent.push(p.data.speed + "公里/小时");
              } else if (type === "lldKey") {
                infoContent.push(p.data.deviceName);
                infoContent.push(p.data.cameraType);
              } else if (type === "xfzKey") {
                infoContent.push(p.data.mc);
                infoContent.push("消防站（队站）");
                infoContent.push(p.data.fzr + " " + p.data.fzrLxdh);
              } else if (type === "jgKey") {
                infoContent.push(p.data.dwmc);
                infoContent.push("微型消防站");
                infoContent.push(p.data.lxr + " " + p.data.lxdh);
              }

              const icon = JSON.parse(JSON.stringify(this.icons[p.icon]));
              icon.size = new AMap.Size(icon.size[0], icon.size[1]);
              icon.imageSize = new AMap.Size(
                icon.imageSize[0],
                icon.imageSize[1]
              );
              p.icon = new AMap.Icon(icon);
              var marker = new AMap.Marker(p);
              // // this.map.add(marker);
              let content = [
                "<div class='info_box_contant' style=\"line-height: 30px;min-width: 250px; padding: 20px; font-size: 20px; color: #7ea2ff; font-family: 'Abel';  background: rgba(0, 0, 0, 0.82);\">" +
                  infoContent.join("<br />") +
                  " </div>",
              ];
              const infoWindow = new AMap.InfoWindow({
                isCustom: true, //使用自定义窗体
                content: content.join("<br>"),
                offset: new AMap.Pixel(0, -70),
              });

              marker.on("mouseover", (e) => {
                infoWindow.open(this.map, p.position); //后面的参数指的是经纬度，在此显示窗口
              });

              marker.on("mouseout", (e) => {
                infoWindow.close();
              });
              this.markerCache[type].push(marker)
              markers.push(marker);
            });
            return markers;
          }
    },
    closeInfoWindow() {
      this.map.clearInfoWindow();
    },
  },
  watch: {
    data: {
      handler() {
        if (this.map) {
          this.map.clearInfoWindow();
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style scoped lang="less">
.map {
  width: 100%;
  height: 100%;
  position: relative;

  .legend {
    width: 152px;
    height: 339px;
    box-sizing: border-box;
    background: url("../assets/images/map-legend-bg.png") center center
      no-repeat rgba(0, 80, 153, 0.25);
    background-size: 152px 339px;
    position: absolute;
    left: 10px;
    bottom: 0;
    border-radius: 3px;
    z-index: 8;
    padding: 10px 22px;
    .item {
      width: 100%;
      height: 26px;
      display: flex;
      font-family: "PingFang SC";
      font-style: normal;
      font-weight: 500;
      font-size: 14px;
      line-height: 20px;
      margin-bottom: 10px;
      color: #848484;
      &.selected {
        color: #ffffff;
      }
      img {
        width: 20px;
        height: 25px;
        margin-right: 10px;
      }
      align-items: center;
      align-content: center;
      cursor: pointer;
    }
  }

  #map-container {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    background-color: #070b13 !important;
    background-image: none;
  }
  .info-window {
    width: 434px;
    height: auto;

    .info-content {
      width: 100%;
      height: auto;
      background: rgba(0, 0, 0, 0.82);
      border: 1px solid rgba(61, 115, 255, 0.72);
      box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.5);
      position: relative;

      .title {
        width: 100%;
        height: 56px;
        background: url("../assets/images/map-infowindow-title-bg.png") center
          center no-repeat;
        background-size: cover;
        border-bottom: 1px solid rgba(61, 115, 255, 0.5);
        padding: 16px 16px 16px 32px;
        display: flex;
        box-sizing: border-box;

        .txt {
          flex-grow: 1;
          font-family: "Abel";
          font-style: normal;
          font-weight: 400;
          font-size: 24px;
          line-height: 24px;
          color: #ffb800;
        }

        .close {
          width: 24px;
          height: 24px;
          background: url(../assets/images/map-icon-close.png) center center
            no-repeat;
          background-size: 24px 24px;
          cursor: pointer;
        }
      }

      .content {
        width: 100%;
        height: auto;
        min-height: 50px;
        padding: 14px 32px;
        box-sizing: border-box;
        margin-bottom: 10px;

        .row {
          width: 100%;
          height: 24px;
          margin-bottom: 8px;
          font-family: "Abel";
          font-style: normal;
          font-weight: 400;
          font-size: 16px;
          line-height: 24px;

          &.blue {
            color: #7ea2ff;
          }
        }
      }

      .border-bottom {
        width: 100%;
        height: 2px;
        display: flex;
        background: linear-gradient(
          90deg,
          #2d53dd 0.62%,
          #5c80ff 47.56%,
          #355ce9 94.62%
        );
        position: relative;
      }

      .l-t {
        width: 16px;
        height: 2px;
        left: 0;
        top: 0;
        background: #7b90ff;
        position: absolute;
      }

      .r-t {
        width: 16px;
        height: 2px;
        right: 0;
        top: 0;
        background: #7b90ff;
        position: absolute;
      }

      .l-b {
        width: 16px;
        height: 2px;
        left: 0;
        bottom: 0;
        background: #7b90ff;
        position: absolute;
      }

      .r-b {
        width: 16px;
        height: 2px;
        right: 0;
        bottom: 0;
        background: #7b90ff;
        position: absolute;
      }

      .c-b {
        width: calc(100% - 32px);
        height: 2px;
        left: 16px;
        bottom: 0;
        background: linear-gradient(
          90deg,
          #2d53dd 0.62%,
          #5c80ff 47.56%,
          #355ce9 94.62%
        );
        position: absolute;
      }
    }

    .info-bottom {
      width: 100%;
      height: 24px;
      margin-top: -2px;
      background: url(../assets/images/map-infowindow-arrow.png) center center
        no-repeat;
      background-size: 39px 23px;
    }
  }
}
</style>
