<template>
  <div :style="{'height':mapHeight,'width':mapwidth,'position':'relative'}">
    <div id="maps" :style="{'height':'100%'}">
    </div>
    <slot name="maptime"></slot>
    <slot name="mapbar"></slot>
    <slot name="mapindex"></slot>

    <showCamera ref="showCamera"></showCamera>
  </div>

</template>

<script>
  import {
    getCameraLive
  } from '@/utils/camera.js'
  import showCamera from '@/views/monitor/camera/components/showCamera.vue'
  export default {
    components: {
      showCamera
    },
    props: {
      // 轨迹点位数据
      pointsArr: {
        type: Array,
        default: () => []
      },

      mapwidth: {
        type: String,
        default: "100%"
      },
      datasArr: {
        type: Object,
        default: () => {}
      },
      // clickNumber:{
      //   type: String,
      //   default: ""
      // },
      boatInfo: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        mapHeight: "400px",
        map: null,
        mapcenter: [120.58328, 31.29665],
        start_icon: require("@/assets/imgs/map-start.png"),
        end_icon: require("@/assets/imgs/map-end.png"),
        play_back: require("@/assets/imgs/playback.png"),
        camera: require("@/assets/imgs/camera.png"),
        clickNumber: "",
        // marker:[],
        // markerInfoWin:[]
        // points:this.pointsArr,
      }
    },
    mounted() {
      this.initMap()
      window.showPlayBack = this.showPlayBack
      window.showCamera = this.showCamera
    },
    watch: {
      pointsArr(val, oldval) {
        if (oldval != val) {
          this.$nextTick(function() {
            this.pointsArr = val
            this.playMap()
          })
        }
      },
      datasArr(val, oldval) {
        if (oldval != val) {
          this.$nextTick(function() {
            this.datasArr = val
            this.nowLocationShow()
          })
        }
      }
      // clickNumber(val){
      //   if(val){
      //     this.clickNumber = val
      //     this.$nextTick(function(){
      //       this.panto()
      //     })
      //   }
      // }
    },
    created() {

    },
    methods: {
      initLoad() {
        var that = this;
        var clientHeight = document.documentElement.clientHeight
        var topHeight = 50; //页面 头部
        let tableHeight = clientHeight - topHeight;
        that.mapHeight = tableHeight + "px";
        this.$emit('mapHeight', that.mapHeight)
      },
      playMap() {
        this.$nextTick(function() {
          this.playBack()
        })
      },
      nowLocationShow() {
        this.$nextTick(function() {
          this.nowLocation()
        })
      },
      // 初始地图
      initMap() {
        this.initLoad()
        this.$nextTick(function() {
          this.loadTdt()
        })
      },
      loadTdt(elId) {
        console.log("开始执行")
        let that = this
        return new Promise((resolve, reject) => {
          console.log("开始执行2")
          let script = document.createElement('script');
          script.type = 'text/JavaScript';
          script.src = "http://api.tianditu.gov.cn/api?v=4.0&tk=2eecd3d615e01cf6dbe6d4b8b686d264"
          console.log("开始执行3")
          script.onload = function() {
            console.log("js加载完成")
            that.map = new T.Map('maps', {
              projection: 'EPSG:4490'
            });
            that.map.centerAndZoom(new T.LngLat(120.582031, 31.304329), 16);
            that.map.setMinZoom(1);
            that.map.setMaxZoom(18);
            that.map.enableDrag();
            // if(that.datasArr.length>0){
            //   that.nowLocationShow()
            // }
            if (that.pointsArr.length > 0) {
              that.playMap()
            }
            // that.nowLocationShow()

          }
          let head = document.head;
          head.appendChild(script);
        })
      },

      // 轨迹
      playBack() {
        // 清除轨迹 market
        if (this.map) {
          var a = this.map.getOverlays()
          for (var i = 0; i < a.length; i++) {
            this.map.removeOverLay(a[i])
          }
        }
        if (this.pointsArr.length == 0) {
          this.$message({
            message: '该时间段暂无点位信息',
            type: 'warning'
          });
          return
        }
        // 数据设置中心点
        this.map.centerAndZoom(new T.LngLat(this.pointsArr[0].longitude, this.pointsArr[0].latitude), 16);
        let gjPoints = []
        for (var m of this.pointsArr) {
          gjPoints.push(
            new T.LngLat(m.longitude, m.latitude)
          )
        }
        // 创建起始位置
        var startIcon = new T.Icon({
          iconUrl: this.start_icon,
          iconSize: new T.Point(65, 65),
          iconAnchor: new T.Point(32, 32)
        });
        var start_marker = new T.Marker(new T.LngLat(this.pointsArr[0].longitude, this.pointsArr[0].latitude), {
          icon: startIcon
        });
        var endIcon = new T.Icon({
          iconUrl: this.end_icon,
          iconSize: new T.Point(65, 65),
          iconAnchor: new T.Point(32, 32)
        });
        var end_marker = new T.Marker(new T.LngLat(this.pointsArr[this.pointsArr.length - 1].longitude, this.pointsArr[
          this.pointsArr.length - 1].latitude), {
          icon: endIcon
        });
        this.map.addOverLay(start_marker);
        this.map.addOverLay(end_marker);

        //创建轨迹线条
        var polygon = new T.Polyline(gjPoints, {
          color: "blue",
          weight: 3,
          opacity: 0.5,
          fillColor: "#FFFFFF",
          fillOpacity: 0.5
        });
        polygon.id = "lines"
        this.map.addOverLay(polygon);
      },
      // 实时定位
      nowLocation() {

        // 数据设置中心点
        this.panto(this.datasArr.location)
        this.map.centerAndZoom(new T.LngLat(this.datasArr.location.longitude, this.datasArr.location.latitude), 16);
        var that = this
        var marker = new T.Marker(new T.LngLat(this.datasArr.location.longitude, this.datasArr.location
          .latitude)); // 创建标注
        var eNum = this.datasArr.location.equipment_number
        var cStatus = this.datasArr.camera ? this.datasArr.camera.state : ""
        var cNo = this.datasArr.camera ? this.datasArr.camera.idno : "";

        var direction = this.toGetDirection(Number(this.datasArr.location.direction))
        var warning = this.toGetWarn(this.datasArr.location.alarm_message);
        var status = this.toGetStatus(this.datasArr.location.status);
        var content = "<div class='infowindow'>" +
          "<div class='infoheader'>" +
          "<span>" + this.datasArr.location.equipment_number + "</span></div>" +
          "<div class='infowrap'>" +
          "<table width='100%'>" +
          "<tr>" +
          "<td>定位时间</td>" +
          "<td>" + this.datasArr.location.created_at + "</td>" +
          "</tr>" +
          "<tr>" +
          "<td>行驶速度</td>" +
          "<td>" + this.datasArr.location.speed + " km/h</td>" +
          "</tr>" +
          "<tr>" +
          "<td>行驶方向</td>" +
          "<td>" + direction + " </td>" +
          "</tr>" +
          "<tr>" +
          "<td>当前告警</td>" +
          "<td>" + warning + "</td>" +
          "</tr>" +
          "<tr class='bm1'>" +
          "<td>设备状态</td>" +
          "<td>" + status + "</td>" +
          "</tr>" +
          "<tr class='bm1'>" +
          "<td>里程</td>" +
          "<td>" + (this.datasArr.location.mileage / 10) + "km</td>" +
          "</tr>" +
          "<tr>" +
          "<td>地理位置</td>" +
          "<td>" + this.isEmpty(this.datasArr.location.address) + "</td>" +
          "</tr>" +
          "</table>" +
          "<div class='playback'>" +
          "<li onClick=showPlayBack('" + eNum + "'," + this.datasArr.location.status + ")>" +
          "<img src='" + this.play_back + "'/>轨迹</li>" +

          "<li onClick=showCamera('" + cStatus + "','" + cNo + "')>" +
          "<img src='" + this.camera + "'/>摄像头</li>" +

          "</div>"
        // "<div class='infotop'></div>"+
        // "<div class='infocenter'></div>"+
        // "<div class='infobottom'></div>"+
        "</div>" +
        "</div>";
        // this.markerInfoWin[i] = new T.InfoWindow(content, {
        //   offset: new T.Point(0, -20)
        // });
        // that.openInfo(this.markerInfoWin[i], this.marker[i])
        that.map.addOverLay(marker); // 将标注添加到地图中
        this.addClickHandler(content, marker);
        // this.marker[i].click()
        that.autoOpen(content, marker)
      },
      toGetDirection(num) {
        let name = "未知";
        if (num >= 0 && num < 90) {
          name = num == 0 ? "正北" : "东北"
        } else if (num >= 90 && num < 180) {
          name = num == 90 ? "正东" : "东南"
        } else if (num >= 180 && num < 270) {
          name = num == 180 ? "正南" : "西南"
        } else if (num >= 270 && num < 360) {
          name = num == 270 ? "正北" : "西北"
        }
        return name;
      },
      toGetWarn(str) {
        if (str.indexOf(1) > -1) {
          return "有";
        } else {
          return "无";
        }
      },
      toGetStatus(str) {
        console.log("Number(str)", Number(str))
        if (Number(str) != 11) {
          return "异常信号";
        } else {
          return "正常信号";
        }
      },
      panto(pot) {
        let that = this
        var a = this.map.getPanes()
        console.log("pane", a)
        this.map.panTo(new T.LngLat(pot.longitude, pot.latitude));

      },
      removeLocation(data) {
        if (this.map) {
          var a = this.map.getOverlays()
          if (data.isSelect) {
            this.datasArr = data
            this.nowLocationShow()
          } else {
            for (var i = 0; i < a.length; i++) {
              a[i].closeInfoWindow()
              let point = a[i].getLngLat()
              if (point.lat == data.location.latitude) {
                this.map.removeOverLay(a[i])
              }
              // this.map.removeOverLay(a[i])
            }
          }

        }
      },
      addClickHandler(content, marker) {
        var that = this
        // that.openInfo(content, e)
        marker.addEventListener("click", function(e) {
          that.openInfo(content, e)
          that.$emit('showDataInfo')
        });
      },
      openInfo(content, e) {
        console.log("e", e)
        var point = e.lnglat;
        var marker = new T.Marker(point); // 创建标注
        var markerInfoWin = new T.InfoWindow(content, {
          offset: new T.Point(0, -20)
        }); // 创建信息窗口对象
        this.map.openInfoWindow(markerInfoWin, point); //开启信息窗口
      },
      autoOpen(content, marker) {
        var point = marker.getLngLat();
        var marker = new T.Marker(point); // 创建标注
        var markerInfoWin = new T.InfoWindow(content, {
          offset: new T.Point(0, -20)
        }); // 创建信息窗口对象
        this.map.openInfoWindow(markerInfoWin, point); //开启信息窗口
      },
      // 轨迹回放
      showPlayBack(gps, num) {
        this.$router.push({
          path: '/monitor/gps/playback',
          query: {
            boatEquipment: gps,
            boatNum: num
          }
        });

      },

      isEmpty(val) {
        if (val) {
          return val
        } else {
          return ''
        }

      },
      // 摄像头
      showCamera(deviceSerial) {
        let that = this
        let obj = {
          cStatus: 1,
          deviceSerial: deviceSerial
        }
        if (obj.cStatus == 1) {
          getCameraLive(obj.deviceSerial, function(res) {
            let url = res.data.url
            that.$refs.showCamera.cUrl = url
            that.$refs.showCamera.mountePlay()
            that.$refs.showCamera.isShow = true
          })
        } else if (obj.cStatus == 2) {
          this.$message({
            message: '当前未匹配到设备',
            type: 'warning'
          });
        } else {
          this.$message({
            message: '当前未匹配不在线',
            type: 'warning'
          });
        }
      },

    }
  }
</script>

<style scoped>
  #maps {
    width: 100%;
  }

  /deep/ .tdt-infowindow-content-wrapper {
    padding: 0
  }

  /deep/ .tdt-infowindow-content {
    margin: 0;
    width: 350px !important;
    /* height:200px */
  }

  /deep/ .tdt-container a.tdt-infowindow-close-button {
    color: #fff
  }

  .infowindow {}

  /deep/ .infoheader {
    color: rgb(255, 255, 255);
    width: 100%;
    padding: 5px;
    background-color: rgb(64, 150, 209);
  }

  /deep/ .infowrap {}

  /deep/ .infowrap table {
    font-size: 0;
    border: none;
    border-collapse: separate;
    border-spacing: 0 0px;
    border-bottom: 1px solid rgb(214, 214, 214);
  }

  /deep/ .infowrap table tr {
    background-color: #f1f1f1;
  }

  /deep/ .infowrap table tr td {
    padding: 3px 10px;
    font-size: 14px;
  }

  /deep/ .infowrap table tr td:first-child {
    width: 80px;
    display: inline-block;
    color: rgb(44, 120, 191);

  }

  /deep/ .infowrap table tr td:first-child+td {
    background-color: #fff;
  }

  /deep/ .bm1 td {
    border-bottom: 1px solid rgb(214, 214, 214);
    border-top: 1px solid rgb(214, 214, 214);
  }

  /deep/ .playback {
    padding: 10px;
    font-size: 16px;
  }

  /deep/ .playback li {
    display: inline-block;
    margin-right: 10px
  }

  /deep/ .playback li img {
    width: 20px;
    vertical-align: sub;
    margin-right: 5px
  }
</style>
