<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.type">
          <a-radio-button value="0">城市内湖</a-radio-button>
          <a-radio-button value="1">专项湖区</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="pointData"></map-table-center>-->
    <map-table :rowData="pointData"></map-table>
    <a-modal @ok="updateCorrectLocation" :closable="false" :destroy-on-close="true" :width="1000" :body-style="{height:'700px'}"
             v-model:visible="visibleRoadMap" :title="roadMapTitle"
    >
      <div style="width: 100%;height: 100%;" ref="roadMap" id="roadMap"></div>
    </a-modal>
  </div>
</template>
<script>
import {
  getLakePlace,
  getLakePlaceInnerCity,
  getLakeYear,
  getInnerLakeYear,
  updateLakeCorrectLocation
} from "@/api/gis/gisApi";
// 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";

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

export default {
  components: {
    tipTool,
    mapNominal,
    mapTable,
    // mapTableCenter
  },
  data() {
    return {
      yearOptions: [],
      arriveCoor: [108.33, 22.84],//坐标点
      where: {
        type: "0",
        year: "",
        filter: ["ph", "transparency", "dissolvedOxygenSaturation", "dissolvedOxygen", "permanganateIndex", "fiveDayBod", "totalNitrogen", "ammonia", "volatilePhenol", "as", "hg", "cr6", "pb", "cd", "totalPhosphorus", "petro", "fecalColiforms", "cod", "chlA", "anSaa", "s", "oxidationReductionPotential"]
      },
      map: {},
      pointData: [],
      currentY: 0,
      currentX: 30000,
      tipFlag: false,
      tipData: [],
      zoom: 13,
      nominalList: [{
        "text": "I类",
        "color": "#80BC1C",
        "common": "I"
      }, {
        "text": "II类",
        "color": "#BBD769",
        "common": "II"
      }, {
        "text": "III类",
        "color": "#F7E020",
        "common": "III"
      }, {
        "text": "IV类",
        "color": "#DF9913",
        "common": "IV"
      }, {
        "text": "V类",
        "color": "#E57813",
        "common": "V"
      }, {
        "text": "劣V类",
        "color": "#DA251C",
        "common": "劣V"
      }],
      points: [],//数据准备
      dataSource: [],
      value: '',
      result: [],
      searchKey: "",
      searchId: -1,
      // 字典表单
      visibleRoadMap: false,
      roadMapTitle: "选择坐标",
      form: {},
    };
  },
  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();

      if (that.where.type == 1) {
        getLakeYear().then((res) => {
          if (res.data.code == 0) {
            this.yearOptions = res.data.data.years.map((item) => {
              return {
                label: item,
                value: item,
              };
            });
            this.where.year = res.data.data.years[0];
            this.whereChange();
          }
        })
      } else {
        getInnerLakeYear().then((res) => {
          if (res.data.code == 0) {
            this.yearOptions = res.data.data.years.map((item) => {
              return {
                label: item,
                value: item,
              };
            });
            this.where.year = res.data.data.years[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 = ""
        that.nominalList.forEach((it, ins) => {
          if (item.waterType >= it.common) {
            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)
        myCompOverlay.addEventListener('contextmenu',function (e){
          let currentId = e.target.getAttribute("id")
          const {longitude, latitude, correctLng, correctLat,placeDictId} = that.pointData[currentId.substring(2, currentId.length)]
          that.form = {longitude, latitude, correctLng, correctLat,placeDictId}
          that.showRoadMap(that.form);
        })
      })
    },
    whereChange(e) {
      if (typeof (e) == "object") {
        if (e.target.name == "area") {
          that.where.type = e.target.value
          if (that.where.type == "1") {
            that.zoom = 9
          } else {
            that.zoom = 13
          }
        }
      } 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)
      }


      if (that.where.type == 1) {
        getLakePlace(this.where).then((res) => {
          that.pointData = []
          that.dataSource = []
          if (res.data.code == 0 && res.data.data.length > 0) {
            that.pointData = res.data.data
            let tem_arr = []
            if (that.pointData.length > 0) {
              that.pointData.forEach(item => {
                that.dataSource.push(`${item.lakeLibraryName}`)
                tem_arr.push({ // 整合字段
                  'placeName': item.sectionName,
                  'attributes': item.controlAttributes,
                  'ph': item.ph,
                  'regionLevel': item.regionLevel,
                  'longitude': item.longitude,
                  'latitude': item.latitude,
                  'waterType' : item.waterType,
                  placeDictId: item.placeDictId,
                  correctLng: item.correctLng,
                  correctLat:item.correctLat
                })
              })
            }
            that.pointData = tem_arr
            that.addMarker()
          }
        })
      } else {
        getLakePlaceInnerCity(this.where).then((res) => {
          that.pointData = []
          that.dataSource = []
          if (res.data.code == 0 && res.data.data.length > 0) {
            that.pointData = res.data.data
            let tem_arr = []
            if (that.pointData.length > 0) {
              that.pointData.forEach(item => {
                that.dataSource.push(`${item.pointName}`)
                tem_arr.push({
                  'placeName': item.pointName,
                  'attributes': item.controlAttributes,
                  'ph': item.ph,
                  'regionLevel': item.regionLevel,
                  'longitude': item.longitude,
                  'latitude': item.latitude,
                  'waterType' : item.waterType,
                  placeDictId: item.placeDictId,
                  correctLng: item.correctLng,
                  correctLat:item.correctLat
                })
              })
            }
            that.pointData = tem_arr
            that.addMarker()
          }
        })
      }

    },
    showRoadMap(form) {
      const {longitude, latitude, correctLng, correctLat} = form
      this.visibleRoadMap = true
      // this.roadMapTitle = "选择修正后的道路坐标"
      this.$nextTick(() => {
        console.log(this.$refs.roadMap)
        // eslint-disable-next-line no-undef
        var map = new BMap.Map(this.$refs.roadMap);    // 创建Map实例
        // eslint-disable-next-line no-undef
        map.addControl(new BMap.NavigationControl());  //初始化地图控件
        // eslint-disable-next-line no-undef
        map.addControl(new BMap.ScaleControl());
        // eslint-disable-next-line no-undef
        map.addControl(new BMap.OverviewMapControl());
        // eslint-disable-next-line no-undef
        var point = new BMap.Point(correctLng ? correctLng : longitude ? longitude : 108.33, correctLat ? correctLat : latitude ? latitude : 22.84);
        // var point = new BBMap.Point(form.longitude ? form.longitude : 108.33, form.latitude ? form.latitude : 22.84);
        map.centerAndZoom(point, 13);//初始化地图中心点
        // eslint-disable-next-line no-undef
        var marker = new BMap.Marker(point); //初始化地图标记
        marker.enableDragging(); //标记开启拖拽
        // eslint-disable-next-line no-undef
        var gc = new BMap.Geocoder();//地址解析类
        //添加标记拖拽监听
        marker.addEventListener("dragend", (e) => {
          //获取地址信息
          this.form['correctLng'] = e.point.lng
          this.form['correctLat'] = e.point.lat

          gc.getLocation(e.point, function (rs) {
            showLocationInfo(e.point, rs);
          });
        });

        //添加标记点击监听
        marker.addEventListener("click", function (e) {
          gc.getLocation(e.point, function (rs) {
            showLocationInfo(e.point, rs);
          });
        });

        map.centerAndZoom(point, 15); //设置中心点坐标和地图级别
        map.addOverlay(marker); //将标记添加到地图中
        //显示地址信息窗口
        function showLocationInfo(pt, rs) {
          var opts = {
            width: 250,     //信息窗口宽度
            height: 100,     //信息窗口高度
            title: ""  //信息窗口标题
          }
          var addComp = rs.addressComponents;
          var addr = "当前位置：" + addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber + "<br/>";
          addr += "纬度: " + pt.lat + ", " + "经度：" + pt.lng;
          // eslint-disable-next-line no-undef
          var infoWindow = new BMap.InfoWindow(addr, opts);  //创建信息窗口对象
          marker.openInfoWindow(infoWindow);
        }
      })

    },
    updateCorrectLocation(){
      const {correctLng, correctLat,placeDictId} =  that.form;
      const reqData = {correctLng, correctLat,id:placeDictId};
      console.log(that.form)
      if(this.where.type == "0"){
        reqData.type = "city"
      }else{
        reqData.type = "special"
      }
      updateLakeCorrectLocation(reqData).then(res=>{
        if(res.data.code == 0){
          this.visibleRoadMap = false
          this.whereChange();
        }
      })

    }
  }
}
</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);
}


.radar-box {
  position: absolute;

  .radar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: red;
    position: relative;
  }

  .radar .ripple {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid red;
    animation: ripple 2s linear infinite;
  }

  .radar :nth-child(1) {
    animation-delay: 0.666s;
  }

  .radar :nth-child(2) {
    animation-delay: 1.322s;
  }

  @keyframes ripple {
    to {
      width: 150px;
      height: 150px;
      opacity: 0;
    }
  }
}

.animation_check {
  animation: myfirst 1s infinite;
}

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