<template>
  <div class="ele-body">
    <a-card class="ele-card" :bordered="false">
      <a-space>

        <a-auto-complete :filterOption="true" :backfill="false" @select="autoInput" :dataSource="dataSource"
                         placeholder="请输入需要搜索的点位">
        </a-auto-complete>

        <a-select @change="whereChange" v-model:value="where.year">
          <a-select-option v-for="item in yearOptions" :key="item.value">{{
              item.label
            }}
          </a-select-option>
        </a-select>
        <a-radio-group @change="whereChange" name="area" v-model:value="where.regionLevel">
          <a-radio-button value="市级">市级</a-radio-button>
          <a-radio-button value="县级">县级</a-radio-button>
        </a-radio-group>
      </a-space>
    </a-card>

    <div id="map" ref="map" style="overflow: hidden"></div>
    <tip-tool :flag="tipFlag" :x="currentX" :y="currentY" :data="tipData"></tip-tool>
    <!--    <mapNominal :param="nominalList"></mapNominal>-->
    <map-table-center :rowData="statisticData"></map-table-center>
    <map-table :rowData="pointData"></map-table>
  </div>
</template>
<script>
import {
  getPlaceGis, statisticCity, statisticCounty
} from "@/api/ecology/atmosphere/acid";
import {
  getColumnOptions,
} from "@/api/ecology/atmosphere/acid-rain-plcae";

import tipTool from "./components/tipTool";
// import mapNominal from "./components/mapNominal";
import mapTable from "./components/mapTable";
import mapTableCenter from "./components/mapTableCenter";
import axios from 'axios';

let scene = null;
let pointLayer = null;
var that

export default {
  components: {
    tipTool,
    // mapNominal,
    mapTable,
    mapTableCenter
  },
  data() {
    return {
      yearOptions: [],
      arriveCoor: [108.33, 22.84],//坐标点
      where: {
        regionLevel: "市级",
        year: "",
      },
      map: {},
      pointData: [],
      currentY: 0,
      currentX: 30000,
      tipFlag: false,
      tipData: [],
      zoom: 13,
      nominalList: [],
      points: [],//数据准备
      dataSource: [],
      statisticData:[],
      value: '',
      result: [],
      searchKey: "",
      searchId: -1
    };
  },
  mounted() {
    that = this
    this.newInitMap();
  },
  methods: {
    autoInput(e) {
      that.dataSource.forEach((item, index) => {
        if (item == e) {
          if (that.searchId > 0) {
            document.getElementById("id" + that.searchId).className = ""
          }
          that.searchId = index
          // eslint-disable-next-line no-undef
          that.map.centerAndZoom(new BMap.Point(that.pointData[that.searchId]['longitude'], that.pointData[that.searchId]['latitude']), that.zoom); // 初始化地图,设置中心点坐标和地图级别
          document.getElementById("id" + that.searchId).className += "animation_check"
        }
      })
    },
    newInitMap() {
      // eslint-disable-next-line no-undef
      that.map = new BMap.Map(this.$refs.map); // 创建Map实例
      // eslint-disable-next-line no-undef
      that.map.centerAndZoom(new BMap.Point(that.arriveCoor[0], that.arriveCoor[1]), that.zoom); // 初始化地图,设置中心点坐标和地图级别
      that.map.addControl(
        // eslint-disable-next-line no-undef
        new BMap.MapTypeControl({
          // eslint-disable-next-line no-undef
          mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
        })
      )
      that.map.enableDragging();
      that.map.enableScrollWheelZoom();
      that.map.enableDoubleClickZoom();
      that.map.enableKeyboard();

      getColumnOptions("year").then((res) => {
        if (res.data.code == 0) {
          this.yearOptions = res.data.data.map((item) => {
            return {
              label: item,
              value: item,
            };
          });
          this.where.year = res.data.data[0];
          this.whereChange();
        }
      })
    },
    addMarker: function () {  // 创建图标对象
      //定义自定义覆盖物的构造函数
      function ComplexCustomOverlay(point, index, color) {
        this._point = point
        this._index = index
        this._color = color
      }

      // eslint-disable-next-line no-undef
      ComplexCustomOverlay.prototype = new BMap.Overlay();

      ComplexCustomOverlay.prototype.initialize = function (map) {
        this._map = map;
        var div = this._div = document.createElement("div");
        div.style.position = "absolute";
        div.style.float = "left"
        div.style.cursor = "pointer"
        // eslint-disable-next-line no-undef
        div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
        div.style.height = "20px";
        div.style.width = "10px";

        var arrow = this._arrow = document.createElement("div");
        arrow.style.width = "0px";
        arrow.style.height = "0px";
        arrow.style.borderLeftWidth = "10px"
        arrow.style.borderLeftColor = "transparent"
        arrow.style.borderStyle = "solid"
        arrow.style.borderRightWidth = "10px"
        arrow.style.borderRightColor = "transparent"
        arrow.style.borderBottomWidth = "20px"
        arrow.style.borderTopWidth = "0"
        arrow.style.position = "absolute"
        arrow.style.borderBottomColor = `${this._color}`
        arrow.setAttribute("id", "id" + this._index)
        arrow.style.top = "22px";
        arrow.style.left = "10px";
        div.appendChild(arrow);
        that.map.getPanes().labelPane.appendChild(div);
        return div;
      }
      ComplexCustomOverlay.prototype.draw = function () {
        var map = this._map;
        var pixel = map.pointToOverlayPixel(this._point);
        this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
        this._div.style.top = pixel.y - 30 + "px";
      }
      ComplexCustomOverlay.prototype.addEventListener = function (event, fun) {
        this._arrow['on' + event] = fun;
      }
      that.pointData.forEach(async (item, index) => {
        let color = "#fc4304"
        // that.nominalList.forEach((it, ins) => {
        //   if (item.leq >= it.min && item.leq <= it.max) {
        //     color = that.nominalList[ins]['color']
        //     return false
        //   }
        // })
        // eslint-disable-next-line no-undef
        var myCompOverlay = new ComplexCustomOverlay(new BMap.Point(item.longitude, item.latitude), index, color);
        that.map.addOverlay(myCompOverlay);//将标注添加到地图中
        myCompOverlay.addEventListener('mouseover', function (e) {
          let currentId = e.target.getAttribute("id")

          setTimeout(() => {
          }, 300)
          let bodyInfo = document.getElementsByTagName("body")[0]
          let screenWidth = bodyInfo.offsetWidth
          // let screenHeight = bodyInfo.offsetHeight

          let mapInfo = document.getElementById("map")
          let mapWidth = mapInfo.offsetWidth;    // 返回元素的总宽度
          // let mapHeight = mapInfo.offsetHeight;    // 返回元素的总高度

          let calcWidth = screenWidth - mapWidth
          // let calcHeight = screenHeight - mapHeight
          that.tipFlag = true
          that.tipData = that.pointData[currentId.substring(2, currentId.length)]
          that.currentX = e.pageX - calcWidth
          that.currentY = e.pageY - 80
        }, true)

        myCompOverlay.addEventListener('mouseout', function () {
          setTimeout(() => {
          }, 300)
          that.currentX = 30000
          that.currentY = 0
          that.tipFlag = false
        }, true)
      })
    },
    whereChange(e) {
      if (typeof (e) == "object") {
        if (e.target.name == "area") {
          that.where.regionLevel = e.target.value
          if (that.where.regionLevel == "county") {
            that.zoom = 8
          } else {
            that.zoom = 13
          }
        }
        // if (e.target.name == "day") {
        //   that.where.timeSlot = e.target.value
        // }
      } else {
        if (e > 0) {
          that.where.year = e
        }
      }
      that.map.clearOverlays();
      // eslint-disable-next-line no-undef
      that.map.centerAndZoom(new BMap.Point(108.33, 22.84), that.zoom);

      if (scene && pointLayer) {
        scene.removeLayer(pointLayer)
      }

      this.statisticData = [];
      let req;
      const params = {
        timeStart: this.where.year + "-01-01 00:00:00",
        timeEnd: this.where.year + "-12-31 59:59:59"
      };
      if (this.where.regionLevel == "市级") {
        req = axios.post(statisticCity, params)

      } else {
        req = axios.post(statisticCounty, params)
      }
      req.then(res => {
        if (res.data.code == 0 && res.data.data.length > 0) {
          const list = [];
          res.data.data.forEach(item => {
            const key = Object.keys(item)[0]
            const fData = item[key].filter(i=>i.periodType === "本年度")
            list.push(...fData)
          })
          this.statisticData = list;
        }
      })
      getPlaceGis(this.where).then((res) => {
        that.pointData = []
        that.dataSource = []
        if (res.data.code == 0 && res.data.data.length > 0) {
          that.pointData = res.data.data
          that.pointData.forEach(item => {
            that.dataSource.push(`${item.place}`)
          })
          that.addMarker()
        }
      })
    },
    exportMap() {
      console.log("exportMap");
      scene.exportMap("png");
    }
  }
}
</script>
<style>
::-webkit-scrollbar {
  display: none;
}

html,
body {
  overflow: hidden;
  margin: 0;
  width: 100vw;
  height: 100vh;
}

.ele-body {
  position: relative;
  padding: 16px 0;
  height: 100%;
}

.ele-card {
  z-index: 10;
  margin: 0 16px;
  display: inline-block;
}

#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}

.anchorBL {
  display: none;
}

::v-deep .amap-logo {
  right: 0 !important;
  left: auto !important;
  display: none !important;
}

::v-deep .amap-copyright {
  right: 70px !important;
  left: auto !important;
  opacity: 0 !important;
}

::v-deep .amap-info-content {
  background-color: rgba(0, 0, 0, .4);
  border-radius: 5px;
  color: #fff;
  padding: 0;
}

::v-deep .bottom-center .amap-info-sharp {
  border-top-color: rgba(0, 0, 0, .6);
}

::v-deep .amap-info-close {
  display: none;
}

::v-deep #map-mark {
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 20px solid rgba(0, 0, 255, 0.6);
}

.animation_check {
  animation: myfirst 1s infinite;
}

@keyframes myfirst {
  0% {
    top: 0px
  }
  25% {
    top: 5px;
  }
  50% {
    top: 0px;
  }
  75% {
    top: -5px;
  }
  100% {
    top: 0px;
  }
}
</style>
