<template>
  <div>
    <div id="containerr" style="height: auto" tabindex="0">
      <div class="input-card" v-if="outerlinedata&&outerlinedata.points">
        <h4>轨迹回放</h4>
        <div class="input-item">
          <input type="button" class="btn btn-info" value="开始动画" id="start" @click="startAnimation()"/>
          <input v-show="!ispause" type="button" class="btn btn-info" value="暂停动画" id="pause" @click="pauseAnimation()"/>
          <input v-if="ispause" type="button" class="btn btn-info" value="继续动画" id="resume" @click="resumeAnimation()"/>
        </div>
        <div class="input-item">
          <input type="button" class="btn btn-info" value="加速动画" id="add" @click="speedUp()"/>
          <input type="button" class="btn btn-info" value="减速动画" id="des" @click="speedDown()"/>
        </div>
      </div>
    </div>

    <div id="panel" v-show="showPanel"></div>
  </div>
</template>
<script>
  import * as maptool from '../../plugins/transformer'
  export default {
    title: "地图",
    props: {
      //轨迹
      //示例

      outerlinedata: {
        type: Object,
        default: {}
      },
      //单点
      //示例 {"name2":"终点","f_longitude":108.9592663294896,"f_latitude":34.163040719830576,"iconurl":"https://webapi.amap.com/theme/v1.3/markers/n/end.png","zIndex":10}
      singlepoint: {
        type: Object,
        default: {}
      },
      //点集
      points: {
        type: Object,
        default: {
          url: 'api/af-revenue/sql/getDapingStationMap',
          data: {subcompany:'%'}
        }
      },
      //当前用户
      curuser: {
        type: Object,
        default: {}
      },
      ispause: false,
      //最大高度
      maxheight: '',
      //最大宽度
      maxwidth: '',
      showBox: {
        type: Boolean,
        default: false
      },
      showPanel: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // model: new PagedList('rs/sql/singleTable_OrderBy', 10, {
        //   items: '"*"',
        //   tablename: '"t_repairman"',
        //   orderitem: '"ID desc"'
        // }),
        path: "rs/WX/searchMarker", // 获取标记点数组请求路径
        rate: 1, // 控制速度比率
        postData: [], // 获取后台数据的参数
        map: null, // 显示地图实例
        position: null, // 定位对象
        startmaker: null,
        stmarker: {}, // 开始标记
        endmarker: {}, // 结束标记
        repairmanData: [], // 维修员信息
        placeSearch: null, // 地点查询对象
        driving: null,   // 驾车线路规划对象
        parameters: [],  // 西安银行ATM接口需求，将参数放在数组中
        R: 1, // 半径 (单位:千米) 围栏显示范围
        searchNearByData: "西安银行", // searchNearBy中要查的名称
        markerType: [], // 界面上分类显示按钮菜单
        markerData: [], // 要标记的点——本地数据库和西安银行ATM位置提取数据的集合
        localRows: [], // 本地数据库获取的数据初始化
        rows: [], // 西安银行ATM位置后台数据初始化
        lineData: this.outerlinedata,// 绘制轨迹路线的数据（坐标点）
        stopstart: true,
        // timeoutHandle: window.setInterval(this.timemet, 120000),
        modalshow: false
      };
    },
    methods: {
      // 开始回放
      startAnimation() {
        this.startmarker.moveAlong(this.lineData, 2000)
      },
      // 暂停
      pauseAnimation() {
        this.startmarker.pauseMove();
        this.ispause = true
      },
      // 继续
      resumeAnimation() {
        this.ispause = false
        this.startmarker.resumeMove();
      },
      //加速
      speedUp() {
        this.rate = this.rate / 2
        this.startmarker.moveAlong(this.lineData, 2000 / this.rate)
      },
      //减速
      speedDown() {
        this.rate = this.rate * 2
        this.startmarker.moveAlong(this.lineData, 2000 / this.rate)
      },
      close() {
        this.modalshow = false
      },
      //定时刷新位置
      timemet() {
        this.map.clearMap()
        this.getnewposit(this.map)
      },
      setPoint(data) {
        this.map.clearMap()
        console.log('当前点' + data)
        this.outerlinedata= {}
        this.markerData = []
        this.markerData.push(data)
        this.markerDataToMap()
        let position = []
        position = [data.f_longitude, data.f_latitude]
        this.map.setCenter(position)
        this.map.setFitView()
      },
      getnewposit(map) {
        //如果有点集在地图上显示所有的点
        console.log('开始获取散点集')
        if (this.points) {
          let url = this.points.url
          let data = this.points.data
          this.$resetpost(url, {data: data}, {
            rejectMsg: null,
            resolveMsg: null,
            silent: true
          }).then((row) => {
            this.markerData = row.data
          this.markerDataToMap()
          console.log(this.map.getZoom())
          this.map.setZoom(9.2)
        })
        }
      },
      // json对象去重-下拉菜单
      unique: function (arr) {
        var ret = [];
        for (var i = 0, j = arr.length; i < j; i++) {
          if (ret.indexOf(arr[i]) === -1) {
            ret.push(arr[i]);
          }
        }
        return ret;
      },
      searchNearByAPI: function () {
        // POI搜索插件
        this.placeSearch = new AMap.PlaceSearch({
          pageSize: 5,
          pageIndex: 1,
          city: "029",
          map: this.map,
          panel: "panel"
        });
      },
      markerClick(e){
        var infoWindow = new AMap.InfoWindow({});
        console.log(e.target)
        console.log(e.value)
        let content = `<div style="height: auto">1111</div>`
        infoWindow.setContent(content);
        infoWindow.open(this.map, e.target.getPosition());
        // this.map.setCenter(e.target.getPosition());
      },
      markerDataToMap: function () {
        // start—  if 数据库有坐标信息则使用数据库标记点
        // start-  else 数据库没有坐标信息，使用高德地图API SearchNearBy方法去获取高德标记库中的标记点。
        // this.markerData=null

        if (!(this.markerData == undefined || this.markerData == null || this.markerData.length == 0)) {
          this.markerData.map((item)=>{
            if (item.f_longitude != 0) {
            var lnglat = item.f_geo_coordinates.split(',');
            console.log('坐标.......'+lnglat)
            if (!item.iconurl) {
              item.iconurl = "static/newStyle/position.png";
            } else {
            }

            this.marker = new AMap.Marker({
              title: item.f_name,
              position: lnglat,
              // animation: "AMAP_ANIMATION_DROP",
              draggable: false,  //是否可拖动
              // content: '<img  src="' +
              // this.markerData[i].iconurl +
              // '" />'   //自定义点标记覆盖物内容
              content: '<img style="text-align: center;margin-left:10px;" src="' +
              item.iconurl +
              '" /><span style="text-align: center;max-height:14px;width:60px;padding:0px;margin-top:0px;margin-bottom:0px;color:#00A7D2;font-size:14px; font-weight:bold;display: inline-block;text-align: left;">' +
              item.f_name +
              "</span>"
            }); //自定义点标记覆盖物内容
            var that = this
            var infoWindow = new AMap.InfoWindow({
              offset: new AMap.Pixel(40, 10)
            })

            this.marker.on("mouseover", function (e) {
            let content =
              `<div class="row tooltip" style="height: auto;">
                <div style="font-size: 16px">
                  <span style="color:#13FDFD;font-weight: bolder">${item.f_name}</span>
                </div>
                <div style="margin-top: 3px">
                  <span class="t2">累计流量（NM3）：</span>
                  <span class="t3">${item.f_cumulative_flow}</span>
                </div>
                <div style="margin-top: 3px">
                  <span class="t2">瞬时流量（NM3）：</span>
                  <span class="t3">${item.f_instantaneous_flow}</span>
                </div>
                <div style="margin-top: 3px">
                  <span class="t2">进站压力（NPA）：</span>
                  <span class="t3">${item.f_input_pressure}</span>
                </div>
                <div>
                  <span class="t2">出站压力（NPA）：</span>
                  <span class="t3">${item.f_output_pressure}</span>
                </div>
              </div>`
              infoWindow.setContent(content)
              that.map.setZoomAndCenter(that.map.getZoom(),e.target.getPosition())
              // that.marker.setLabel({
              //   // offset: new AMap.Pixel(20, 20),  //设置文本标注偏移量
              //   content: `<div class="info" style="height: auto">${item.f_name}</div>`, //设置文本标注内容
              //   direction: 'bottom' //设置文本标注方位
              // });
              // that.map.setZoomAndCenter(that.map.getZoom(),e.target.getPosition())

                infoWindow.open(that.map, e.target.getPosition());
            });
            this.marker.on("mouseout", function (e) {
              // that.marker.setLabel(null);
              infoWindow.close(that.map, e.target.getPosition());
            });
            this.marker.setMap(this.map)
            console.log(this.map.getZoom())
            // this.map.setZoom(15)
          }

          })



        }
        this.map.setFitView();


      }, // end- if else,
      // select选中
      changeType(val) {
        document.getElementById("panel").innerHTML = "";
        if (this.maxheight) {
          document.getElementById("containerr").style.height = `${this.maxheight}px`
          document.getElementById("containerr").style.width = `${this.maxwidth}px`
        } else {
          console.log('设置高度')
          document.getElementById("containerr").style.height = '100%'
          document.getElementById("containerr").style.width = '100%'

        }
        console.log("选中" + val);
        var optionVal = val;
        // 如果为空不去清空地图标记
        if (optionVal) {
          this.map.clearMap();
        }
        // 定位和范围
        // this.makeCircle();
        // 按条件标记
        for (var i = 0; i < this.markerData.length; i++) {
          if (optionVal == this.markerData[i].type) {
            var lnglat = [this.markerData[i].x, this.markerData[i].y];
            if (this.markerData[i].iconurl == null || this.markerData[i].iconurl == undefined) {
              this.markerData[i].iconurl = "static/newStyle/clear.png";
            }
            ;
            this.marker = new AMap.Marker({
              position: lnglat,
              animation: "AMAP_ANIMATION_DROP",
              content: '<img style="text-align: center;margin-left:10px;" src="' +
              this.markerData[i].iconurl +
              '" /><span style="text-align: center;height:14px;width:60px;padding:0px;margin-top:0px;margin-bottom:0px;margin-right:60px;color:#ff0000;font-size:14px;display: inline-block;text-align: left;">' +
              this.markerData[i].type +
              "</span>" //自定义点标记覆盖物内容
            });
          //   this.marker.setMap(this.map);
          //   AMap.event.addListener(this.marker, "click", e => {
          //     this.changeType()
          //   //构造路线导航类
          //   this.driving = new AMap.Driving({
          //     map: this.map,
          //     panel: "panel"
          //   });
          //   this.driving.search(this.position, e.lnglat);
          // });
          }
        }
      },
      onComplete(data) {
        console.log('定位成功')
      },
      //解析定位错误信息
      onError(data) {
        console.log('失败原因排查信息:' + data.message)
      },
      //绘制轨迹路线
      startPointTrack() {
        console.log("绘制轨迹路线start");
        var thisa = this;
        this.startmarker = new AMap.Marker({
          map: thisa.map,
          position: [thisa.stmarker.f_longitude, thisa.stmarker.f_latitude],
          icon: "https://webapi.amap.com/images/car.png",
          offset: new AMap.Pixel(-26, -13),
          autoRotation: true,
          angle: -90,
        });
        this.startmarker.on('moving', function (e) {
          passedPolyline.setPath(e.passedPath);
        });
        var polyline = new AMap.Polyline({
          map: thisa.map,
          path: thisa.lineData,
          showDir: true,
          strokeColor: "#28F",  //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6,      //线宽
          // strokeStyle: "solid"  //线样式
        });
        var passedPolyline = new AMap.Polyline({
          map: thisa.map,
          // path: lineArr,
          strokeColor: "#AF5",  //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6,      //线宽
          // strokeStyle: "solid"  //线样式
        });
      }
    },
    //当外部传给这个组件的props的outerlinedata参数发生变化，就重新绘制轨迹路线
    watch: {
      'singlepoint'(val) {
        if (this.singlepoint.f_longitude && this.singlepoint.f_latitude) {
          this.setPoint(this.singlepoint)
        }
      },
      'outerlinedata'(llval) {
        this.lineData = []
        if (llval && llval.points.length > 0) {
          for (let i = 0; i < llval.points.length; i++) {
            if (llval.points[i].lnglat[0] && llval.points[i].lnglat[1]) {
              let data = [llval.points[i].lnglat[0], llval.points[i].lnglat[1]]
              let json = maptool.wgs84togcj02(Number(data[0]), Number(data[1]))
              this.lineData.push(json)
            }
          }
        }
        this.map.clearMap()
        if (llval == null || llval.points.length < 1) {
          console.log('开始清空')
          if (window.pathSimplifierIns) {
            //通过该方法清空上次传入的轨迹
            window.pathSimplifierIns.setData([]);
          }
          this.getnewposit(this.map)
          // clearInterval(this.timeoutHandle);
          // this.timeoutHandle = setInterval(this.timemet, 120000); //重新启动即可
        } else {
          // clearInterval(this.timeoutHandle);
          var startPot = this.lineData[0];
          var endPot = this.lineData[this.lineData.length - 1];
          this.stmarker = {
            name2: '起点',
            f_longitude: startPot[0], //基点位置
            f_latitude: startPot[1], //基点位置
            iconurl: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
            zIndex: 10
          };
          this.endmarker = {
            name2: '终点',
            f_longitude: endPot[0], //基点位置
            f_latitude: endPot[1],
            iconurl: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
            zIndex: 10
          };
          this.markerData = [],
            console.log('起点' + this.stmarker.position)
          this.markerData.push(this.stmarker)
          this.markerData.push(this.endmarker)
          this.markerDataToMap()
          this.startPointTrack()
          this.map.setFitView();
        }
      }
    },
    ready() {

      //  初始化地图
      this.map = new AMap.Map("containerr", {
        resizeEnable: true,
        scrollWheel: false,
        mapStyle: 'amap://styles/darkblue',
        zoom: 15
      });
      this.changeType()
      console.log("地图加载正常");
      var thisp = this;
      // 异步加载插件
      AMap.plugin(
        [
          "AMap.ToolBar",
          "AMap.PlaceSearch",
          "AMap.Driving",
          "AMap.Geolocation"
        ],
        () => {
        // 工具条，控制地图的缩放、平移等
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          showbutton: true,
          //控制按钮的显示
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(10, 20),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表示右下
          buttonPosition: 'LB'
        })
        // this.map.addControl(geolocation);
      // geolocation.getCurrentPosition(function (status, result) {
      //   if (status == 'complete') {
      //     thisp.onComplete(result)
      //   } else {
      //     thisp.onError(result)
      //   }
      // });
      // this.map.addControl(new AMap.ToolBar());
    }
    );
      console.log("执行代码开始前");
      if (!/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
      }
      else {
        AMapUI.loadUI(["misc/PoiPicker"], function (PoiPicker) {
          let poiPicker = new PoiPicker({
            input: "pickerInput"
          });
          var marker = new AMap.Marker();
          this.map.setMapStyle('amap://styles/darkblue')
          poiPicker.on("poiPicked", poiResult => {
            let source = poiResult.source;
          var poi = poiResult.item;
          console.log(poi.location.lng, poi.location.lat);
          thisp.position = new AMap.LngLat(poi.location.lng, poi.location.lat);
          thisp.map.setCenter(thisp.position);

          console.log("this.position" + thisp.position);
          thisp.startPost();
        });
          marker.setMap(thisp.map);
          // marker.setPosition(thisp.position);
        });
      }
      thisp.getnewposit(this.map)
    }
  }
</script>
<style scoped>
/*div{*/
  /*height: fit-content !important;*/
/*}*/
  #containerr {
    height: 100%;
  }

  /*地图上已经有获取当前位置的控制器按钮，因此隐藏*/
  .input-card .btn {
    margin-right: 1.2rem;
    width: 9rem;
  }

  .input-card .btn:last-child {
    margin-right: 0;
  }

  #pickerBox {
    position: relative;
    z-index: 10;
    top: 20px;
    left: 70px;
    width: 245px;
    height: 200px;
  }

  #pickerInput {
    width: 60%;
    padding: 0px 0px;
  }

  #fight {
    height: 5%;
    float: right;
  }

  .input-item {
    position: relative;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    -ms-flex-align: center;
    align-items: center;
    width: 100%;
    height: 3rem;
  }

  .input-item:last-child {
    margin-bottom: 0;
  }

  .input-item > select, .input-item > input[type=text], .input-item > input[type=date] {
    position: relative;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    width: 1%;
    margin-bottom: 0;
  }

  .input-item > select:not(:last-child), .input-item > input[type=text]:not(:last-child), .input-item > input[type=date]:not(:last-child) {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0
  }

  .input-item > select:not(:first-child), .input-item > input[type=text]:not(:first-child), .input-item > input[type=date]:not(:first-child) {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0
  }

  .input-item-prepend {
    margin-right: -1px;
  }

  .input-item-text, input[type=text], input[type=date], select {
    height: calc(2.2rem + 2px);
  }
  .info{
    height: auto;
  }
  .input-item-text {
    width: 6rem;
    text-align: justify;
    padding: 0.4rem 0.7rem;
    display: inline-block;
    text-justify: distribute-all-lines;
    /*ie6-8*/
    text-align-last: justify;
    /* ie9*/
    -moz-text-align-last: justify;
    /*ff*/
    -webkit-text-align-last: justify;
    /*chrome 20+*/
    -ms-flex-align: center;
    align-items: center;
    margin-bottom: 0;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    text-align: center;
    white-space: nowrap;
    background-color: #e9ecef;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    border-bottom-right-radius: 0;
    border-top-right-radius: 0;
  }

  .input-item-text input[type=checkbox], .input-item-text input[type=radio] {
    margin-top: 0
  }
  .amap-info-content{
    height: auto !important;
  }
.amap-info-outer{
  height: auto !important;
}
  .input-card {
    /*margin-right: 25%;*/
    z-index: 999;
    float: right;
    position:absolute;
    margin: 0px;
    height: auto;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border-radius: .25rem;
    width: 22rem;
    border-width: 0;
    border-radius: 0.4rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
    bottom: 1rem;
    padding: 0.75rem 1.25rem;
  }

</style>
