<template>
  <div>
    <div class="info">
      <BaiDuMap ref="baidu" v-show="false"> </BaiDuMap>
      <baidu-map :center="center" :min-zoom="3" :max-zoom="19" :zoom="zoom" @ready="handler" class="map"
        scroll-wheel-zoom>
        <bm-map-type :map-types="mapTypes"></bm-map-type>
        <div v-for="(item, index) in queryMapList" :key="index">
          <bm-marker class="tb" v-if="item.icon" :position="{ lng: item.longitude, lat: item.latitude }"
            :icon="{ url: item.url, size: { width: 33, height: 33 } }"></bm-marker>
          <bm-marker :position="{ lng: item.longitude, lat: item.latitude }" animation="BMAP_ANIMATION_BOUNCE" v-else>
            <bm-label v-if="item.content" :content="item.name" :labelStyle="{
              color: '#000',
              fontSize: '0.8rem',
              border: 0,
              padding: '10px',
              opacity: 0.8,
            }" :offset="{ width: -35, height: 30 }" />
          </bm-marker>
        </div>
      </baidu-map>
      <div class="text">
        <van-popover v-model="showPopover" theme="dark" trigger="click" size="small" :actions="actions" @select="onPover"
          placement="bottom-start">
          <template #reference>
            <van-button plain type="danger" size="small">附近网点</van-button>
          </template>
        </van-popover>
        <van-button plain type="danger" @click="jumpIntroduce" size="small">AED介绍</van-button>
        <van-button plain type="danger" @click="jumpExplain" size="small">免责说明</van-button>
      </div>
      <div class="map_content">
        <div class="group" v-for="(item, index) in queryMapListtwo
          .slice(1, queryMapListtwo.length)
          .filter((item) => item.spacing * 1 <= beishu)" :key="index" @click="goPoints(item)">
          <div class="group_left">
            <div class="title">
              {{ item.name }}
            </div>
            <div class="detalis">
              {{ item.address }}
            </div>
            <div class="distance">{{ item.spacing }}km</div>
          </div>
          <div class="group_right" @click="goMap(item)">
            <img src="../../assets/navigation.png" alt="" class="right_img" />
            <span>到这里去</span>
          </div>
        </div>
        <div class="text-bottom" v-if="queryMapListtwo.length > 0">
          我是有底线的...
        </div>
        <div v-else class="text-none">此范围未查询到网点</div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Button, Popover } from "vant";
import { queryListNetwork } from "@/api/aedmap";
import BaiDuMap from "@/components/baidumap/Main.vue";
import { config } from '@/utils/request'
import { jsBridge } from '../../utils/jsbridge'

Vue.use(Button).use(Popover);
export default {
  components: {
    BaiDuMap,
  },
  data() {
    return {
      queryMapList: [],
      current: 1,
      center: { lng: "", lat: "" },
      tagging: { lng: "", lat: "" },
      zoom: 14,
      mapTypes: ["BMAP_NORMAL_MAP", "BMAP_SATELLITE_MAP"],
      show: true,
      showPopover: false,
      actions: [
        { text: "< 1km", content: 1 },
        { text: "< 5km", content: 5 },
        { text: "< 10km", content: 10 },
        { text: "全部", content: 10000 },
      ],
      distance: null,
      queryMapListtwo: [],
      beishu: 10000,
    };
  },
  mounted() {
    window.getUserInfo = this.getUserInfo;
    window.receiveLocation(
      JSON.stringify({ code: 0, data: { lat: 39.983744, lng: 116.276063 } })
    );
    this.initPoint()
    // this.$nextTick(() => {
    //   this.getDistance();
    // });
  },
  created() {
    this.JSBgetUserInfo();
    // this.center = this.$route.query;
    // console.log("this.center", this.$route.query.lng, this.$route.query.lat);
  },
  methods: {
    initPoint() {
      const _that = this
      jsBridge.getPoint().then((res) => {
        _that.center.lat = res.lat
        _that.center.lng = res.lng
        // _that.center.lat = 32.203272
        // _that.center.lng = 119.43897
        _that.queryMapList.unshift({
          longitude: _that.center.lng,
          latitude: _that.center.lat,
          icon: true,
          url: require("../../assets/common/localdw.png"),
          name: "我的位置",
        });
        queryListNetwork({}).then((res) => {
          _that.queryMapList = res.data;
          // this.queryMapList.unshift({
          //   longitude: this.center.lng,
          //   latitude: this.center.lat,
          //   icon: true,
          //   url: require("../../assets/common/localdw.png"),
          //   name: "我的位置",
          // });
          _that.position(10000);
        });
      })
      // if (!this.map) {
      //   this.map = _that.$refs.TengXunMap.map
      // }
    },
    JSBgetUserInfo() {
      if (window.android !== undefined) {
        const res = window.android.getUserInfo(); // 这是一个json字符串
        // sessionStorage.setItem("ZJCD-UserInfo", res);
        this.userInfo = JSON.parse(res);
      } else if (window.webkit) {
        window.webkit &&
          window.webkit.messageHandlers.getUserInfo.postMessage("getUserInfo");
      }
    },
    getUserInfo(res) {
      this.verify(res);
    },
    verify(res) {
      let userInfo = JSON.parse(res);
      sessionStorage.setItem("ZJCD-UserInfo", res);
      sessionStorage.setItem('token', JSON.parse(res).token);
      this.userInfo = userInfo;
      console.log('123', 111);
    },
    position(distance) {
      let obj = this.getMaxMinLongitudeLatitude(
        this.center.lng,
        this.center.lat,
        distance
      );
      let arr = this.queryMapList
        .filter((element) => {
          return (
            element.longitude <= Number(obj.lng[1]) &&
            element.longitude >= Number(obj.lng[0])
          );
        })
        .filter((element) => {
          return (
            element.latitude <= Number(obj.lat[1]) &&
            element.latitude >= Number(obj.lat[0])
          );
        });
      // console.log('arr---->',arr);
      this.queryMapListtwo = arr;
      this.queryMapListtwo.filter((element) => {
        element.spacing = this.getDistance(
          this.center.lat,
          this.center.lng,
          element.latitude,
          element.longitude
        ).toFixed(2);
      });
      // 排序
      for (var i = 0; i < this.queryMapListtwo.length; i++) {
        for (var j = 0; j < this.queryMapListtwo.length - 1; j++) {
          if (Number(arr[j].spacing) > Number(arr[j + 1].spacing)) {
            var temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
          }
        }
      }
      console.log("距离-------", this.queryMapListtwo);
    },
    goPoints(val) {
      // console.log("val---", val);
      this.center.lng = val.longitude;
      this.center.lat = val.latitude;
      this.$set(val, "content", true);
    },
    // longitude 经度  latitude 维度  distince 距离
    getMaxMinLongitudeLatitude(longitude, latitude, distince) {
      let r = 6370.99681; // 地球半径千米
      let lng = longitude;
      let lat = latitude;
      let dlng =
        2 *
        Math.asin(
          Math.sin(distince / (2 * r)) / Math.cos((lat * Math.PI) / 180)
        );
      dlng = (dlng * 180) / Math.PI; // 角度转为弧度
      let dlat = distince / r;
      dlat = (dlat * 180) / Math.PI;
      let minlat = lat - dlat;
      let maxlat = Number(lat) + Number(dlat);
      let minlng = lng - dlng;
      let maxlng = Number(lng) + Number(dlng);
      return {
        lng: [minlng, maxlng],
        lat: [minlat, maxlat],
      };
    },
    // 获取地图两个点距离
    getDistance(lat1, lng1, lat2, lng2) {
      var s = this.$refs.baidu.getDistance([lng1, lat1], [lng2, lat2]) / 1000;
      return s;
    },
    handler({ BMap, map }) {
      console.log(BMap);
      map.enableScrollWheelZoom(true); //开启滚轮缩放
      this.zoom = 15;
    },
    jumpIntroduce() {
      window.location.href =
        `${config.baseH5}aedmap/introduce?showType=1&noTitle=1`
      // "http://81.69.44.115/zjh/html/pages/#/aedmap/introduce?showType=1&noTitle=1";
      // "http://www.smart-zj.cn:55902/zjh/html/pages/#/aedmap/introduce?showType=1&noTitle=1"
    },
    jumpExplain() {
      window.location.href =
        `${config.baseH5}aedmap/explain?showType=1&noTitle=1`
      // "http://81.69.44.115/zjh/html/pages/#/aedmap/explain?showType=1&noTitle=1";
      // "http://www.smart-zj.cn:55902/zjh/html/pages/#/aedmap/explain?showType=1&noTitle=1"
    },
    onShowMarker() {
      this.show = true;
    },
    onPover(val) {
      this.distance = val.content * 1000;
      console.log(this.distance);
      this.beishu = val.content;
      this.position(val.content);
    },
    goMap(val) {
      console.log("val---", val);
      if (window.android !== undefined) {
        window.android.doNavitagion(val.name, val.latitude, val.longitude);
      } else if (window.webkit) {
        const data = {
          poiName: val.name,
          lat: val.latitude,
          lng: val.longitude,
        };
        window.webkit &&
          window.webkit.messageHandlers.doNavitagion.postMessage(data);
      } else {
        this.$toast("无法支持该功能");
      }
    },
    // 覆盖窗口
    updateCirclePath(e) {
      this.center = e.target.getCenter();
      this.radius = e.target.getRadius();
    },
  },
};
</script>

<style lang="stylus" scoped>
.tb
  text-align: center
.text-bottom
  font-size: 32px
  text-align: center
  padding: 10px 0
  color: #999
.text-none
  height: 100%
  font-size: 46px
  display: flex
  color: #999
  justify-content: center
  align-items: center
  background-color: #fff
.info
  width: 100%
  height: 100vh
  position: relative
.map
  width: 100%
  height: 50vh
.fa-nanxing
  background-color: #EB4E3F
  color: #fff
.van-popover__wrapper
  font-size: 0
.text
  position: absolute
  top: 32px
  display: flex
  left: 10px
  z-index: 999
  .van-button
    font-size: 24px
    margin-left: 20px
  .introduce
    border: 1px solid #EB4E3F
    border-radius: 50px
    overflow: hidden
    text-align: center
    box-sizing: border-box
    margin-left: 30px
    background-color: #fff
    font-size: 24px
    .van-button
      width: 120px
      border: 0
      padding: 0
      margin: 0
.map_content
  background-color: #fff
  width: 100%
  height: 50vh
  bottom: 0
  overflow: auto
  .group
    box-sizing: border-box
    padding: 37px 32px
    width: 100%
    height: 200px
    font-size: 32px
    font-weight: bold
    display: flex
    justify-content: space-between
    border-bottom: 1px solid #ccc
    .group_left
      display: flex
      flex-direction: column
      .detalis
        font-size: 24px
        font-weight: 400
        font-family: PingFangSC-Regular, PingFang SC
        color: #333333
        margin-top: 16px
      .distance
        color: #999
        font-size: 22px
        margin-top: 32px
    .group_right
      display: flex
      flex-direction: column
      align-items: center
      .right_img
        width: 88px
        height: 88px
      span
        font-size: 24px
        color: #333
        margin-top: 16px
</style>
