<!--  -->
<template>
  <div class="mapShow_box" :style="'height:' + fullHeight + 'px'">
    <!-- 地图加载动画 -->
    <div v-if="loadinAShow" class="loading_boxA" :style="'height:' + fullHeight + 'px'">
      <div class="loading_boxA_div">
        <img src="../../../static/dongh.gif" alt class="loading_gif" />
        <div class="loadingA_text">地图加载中，请稍后...</div>
      </div>
    </div>

    <!-- 百度地图 -->
    <div class="mapbox">
      <baidu-map
        :style="'height:' + fullHeight + 'px'"
        locationIcon
        class="map"
        :double-click-zoom="true"
        @ready="handler"
        :center="center"
        :zoom="150"
        :map-click="false"
        :mapStyle="mapStyle"
        @touchmove="move()"
        @touchend="end()"
      >
        <bm-geolocation
          :locationIcon="{url: require('../../../static/dingwei.png'), size: {width: 25, height: 40}}"
          @locationSuccess="getLoctionSuccess"
          @locationError="getLoctionError"
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="false"
          :autoLocation="true"
        ></bm-geolocation>
        <bml-marker-clusterer :averageCenter="true">
          <div v-for="(marker, i) of markers" :key="i">
            <bm-marker
              class="dian"
              :icon="{url: marker.url, size: { width: 30, height: 40 }}"
              :dragging="true"
              animation="BMAP_ANIMATION_BOUNCE"
              :position="{lng: marker.lng, lat: marker.lat}"
              @click="infoWindowOpen(marker, i)"
            >
              <bm-label
                @click="details(marker.id, marker.ret)"
                v-if="nameShow"
                :content="marker.name"
                :labelStyle="{color: 'DarkSeaGreen', fontSize : '22px', border: 0}"
                :offset="{width: -35, height: 30}"
              />
              <!-- <bm-label
                @click="details(marker.id, marker.ret)"
                :content="marker.name"
                :labelStyle="{color: 'DarkSeaGreen', fontSize : '22px', border: 0}"
                :offset="{width: -35, height: 30}"
                :show="marker.showFlag"
              />-->
            </bm-marker>
          </div>
        </bml-marker-clusterer>
        <!--地图类型-->
        <bm-map-type
          :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
          anchor="BMAP_ANCHOR_TOP_LEFT"
        ></bm-map-type>
        <!--地图缩放-->
        <!-- <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation> -->
      </baidu-map>
    </div>

    <!-- 底部导航 -->
    <bottomNav v-show="botNav"></bottomNav>
    <!-- 底部导航 -->
  </div>
</template>

<script>
// 按需引入点聚合
import { BmlMarkerClusterer } from "vue-baidu-map";
// 引入marker
import BmMarker from "vue-baidu-map/components/overlays/Marker";
import { BmGeolocation, BmNavigation, BmMapType } from "vue-baidu-map";
import bottomNav from "../bottomNav/bottomNav"; //底部导航栏

const markers = [];
const carList = [{}];
export default {
  // name: "mapShow",
  name: "Bmaptrace",
  //import引入的组件需要注入到对象中才能使用
  components: {
    BmlMarkerClusterer,
    BmMarker,
    // 手动定位控件
    BmGeolocation,
    // 地图放大缩小控件
    BmNavigation,
    // marker控件
    BmMarker,
    bottomNav,
    BmNavigation,
    BmMapType,
  },
  data() {
    //这里存放数据
    const self = this;
    return {
      show: false,
      botNav: true, //底部导航
      isShow: true, // 判断账号详情是否有数据或是账号类型是否为游客登录
      loadinAShow: true, //地图加载动画
      fullHeight: document.documentElement.clientHeight,
      drawer: false, //抽屉弹出显示
      direction: "ltr", //抽屉弹框方向
      dialogVisible: false, //选择昆虫还是病害识别
      result: "", //用户点击选中的图片
      loadingShow: false, //请求等待动画
      sHow: false, //预览对象
      redata: [], //用户详情数据
      dengLV: true, //判断账号类型是游客还是用户；如果是游客那就将更多和搜索框隐藏
      numData: "", //游客账号的识别体验次数
      aaa: "1111",
      //百度地图
      // 初始化地图中心点
      center: null,
      BMap: "",
      map: "",
      markers,
      carList,
      show: false,
      redata: [], //后端传来的数据
      active: false,
      latA: "",
      lngA: "",
      nameShow: false,
      mapStyle: {
        styleJson: [
          {
            featureType: "all",
            elementType: "geometry",
            stylers: {
              // hue: "#007fff",
              // hue: "#eb8f16",
              hue: "#68f8bc",
              saturation: 89
            }
          },
          {
            featureType: "water",
            elementType: "all",
            stylers: {
              color: "#ffffff"
            }
          }
        ]
      },
      //设置地图详细信息
      address: "", //位置详细信息
      jgNameDialog: false,
      show: false,
      postionMap: {
        //地图坐标
        lng: 120.211486,
        lat: 30.256576
      },
      location: "",
      keyword: "", //搜索框关键词
      // zoom: 12.8, //放大比例
      address: "", //位置详细信息
      add: {
        siteName: "",
        site: "",
        jd: "",
        wd: "",
        desce: "",
        type: "",
        jgName: "",
        jgNum: ""
      },
      organizationData: [],
      jgName: "",
      jgNum: ""
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    }
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    //百度地图事件
    //地图初始化
    handler({ BMap, map }) {
      const _this = this;
      // 获取自动定位方法
      var geolocation = new BMap.Geolocation();
      // 获取逆解析方法实例
      this.myGeo = new BMap.Geocoder();
      // 获取自动定位获取的坐标信息
      geolocation.getCurrentPosition(
        function(r) {
          _this.center = {
            lng: r.point.lng,
            lat: r.point.lat
          };
          _this.point = {
            lng: r.point.lng,
            lat: r.point.lat
          };
          localStorage.setItem("jingdu", _this.point.lng); //存经纬度
          localStorage.setItem("weidu", _this.point.lat);
          _this.ceshi(r);
        },

        { enableHighAccuracy: true }
      );
      map.enableScrollWheelZoom(true);
      _this.BMap = BMap;
      _this.map = map;
    },

    //点聚合
    addr() {
      let bb = this.redata;
      for (let i = 0; i < bb.length; i++) {
        const position = {
          lng: this.redata[i].lng,
          lat: this.redata[i].lat,
          // url: this.redata[i].img,
          // url: '../../../static/insect.png',
          url: "./static/insect.png",
          name: this.redata[i].name,
          id: this.redata[i].id,
          ret: this.redata[i].ret,
          showFlag: false
        };
        const position1 = {
          lng: this.redata[i].lng,
          lat: this.redata[i].lat,
          // url: this.redata[i].img,
          // url: '../../../static/insect.png',
          url: "./static/insect.png",
          name: this.redata[i].name,
          id: this.redata[i].id,
          ret: this.redata[i].ret,
          showFlag: false
        };
        if (i % 2 === 0) {
          markers.push(position);
        } else {
          markers.push(position1);
        }
      }
      const carList = [{}];
    },

    //手动定位成功回调
    getLoctionSuccess(e) {
      this.lngA = e.point.lng;
      this.latA = e.point.lat;
      localStorage.setItem("jingdu", this.lngA); //存经纬度
      localStorage.setItem("weidu", this.latA);

      this.show = true;
      this.postionMap.lng = e.point.lng; //通过  e.point.lng获取经度
      this.postionMap.lat = e.point.lat; //通过  e.point.lat获取纬度
      this.add.jd = e.point.lng;
      this.add.wd = e.point.lat;

      let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
      geocoder.getLocation(e.point, rs => {
        this.add.site = rs.address;
        //地址描述(string)=
        // console.log(rs.address);    //这里打印可以看到里面的详细地址信息，可以根据需求选择想要的
        // console.log(rs.addressComponents);//结构化的地址描述(object)
        // console.log(rs.addressComponents.province); //省
        // console.log(rs.addressComponents.city); //城市
        // console.log(rs.addressComponents.district); //区县
        // console.log(rs.addressComponents.street); //街道
        // console.log(rs.addressComponents.streetNumber); //门牌号
        // console.log(rs.surroundingPois); //附近的POI点(array)
        // console.log(rs.business); //商圈字段，代表此点所属的商圈(string)

        let a = rs.addressComponents.province;
        let b = rs.addressComponents.city;
        let c = rs.addressComponents.district;
        let d = rs.addressComponents.street;
        let e = rs.addressComponents.streetNumber;
        localStorage.setItem("dizhi", a + b + c + d + e); //存地址
      });
      this.loadinAShow = false; //关闭地图加载动画
    },
    //手动定位失败回调
    getLoctionError() {
      alert("定位失败");
    },

    // 关闭信息窗口 @close 自带的方法
    infoWindowClose(marker) {
      // marker.showFlag = false;
      this.nameShow = false;
    },

    infoWindowOpen(marker, i) {
      this.nameShow = true;
      // marker.showFlag = true;
    },

    details(id, r) {
      localStorage.setItem("memoryID", id); //存id
      localStorage.setItem("memoryDistinction", r); //存ret
      localStorage.setItem("Point", "2"); //存标识，是从mapShow页面的点聚合效果中进入的详情
      this.$router.push("/record");
    },

    //自动定位
    ceshi(r) {
      let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
      geocoder.getLocation(r.point, rs => {
        this.add.site = rs.address;
        let a = rs.addressComponents.province;
        let b = rs.addressComponents.city;
        let c = rs.addressComponents.district;
        let d = rs.addressComponents.street;
        let e = rs.addressComponents.streetNumber;
        localStorage.setItem("dizhi", a + b + c + d + e); //存地址
      });
      this.loadinAShow = false; //关闭地图加载动画
    },

    //触摸移动时触发的事件
    move() {
      this.nameShow = false;
      this.botNav = false;
    },

    end() {
      this.botNav = true;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.$axios({
      method: "get",
      url: "bigservers/insect_map?page=1"
    })
      .then(res => {
        this.redata = res.data;
        this.addr();
      })
      .catch(error => {
        console.log(error);
      });
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.get_boderHeight();
    let _this = this;
    //判断登录账号类型是用户还是游客
    if (localStorage.getItem("ret") === "tourist") {
      _this.dengLV = false;
      _this.isShow = false;
    } else if (localStorage.getItem("ret") === "user") {
      _this.dengLV = true;
      _this.ret = true;
    }
    _this
      .$axios({
        method: "get",
        url: "bigservers/see_user"
      })
      .then(res => {
        _this.redata = res.data[0];
      })
      .catch(error => {
        this.$message({
          message: "获取用户信息失败",
          type: "error",
          duration: 1000
        });
      });
  }
};
</script>
<style lang="scss">
@import "../../assets/scss/bus.scss";
@import "../../assets/scss/mapShow.scss";
</style>