<template>
  <div class="container">
    <!-- 实时路径 -->
    <div class="btnx">
      <el-button type="primary" class="" @click="openInfo"
        >打开信息窗体</el-button
      >
      <el-button type="primary" class="" @click="closeinfo"
        >关闭信息窗口</el-button
      >
    </div>
    <div id="amap-container"></div>
    <div class="controller">
      <div class="in_transit_information">
        <span class="item_details">车牌号:</span>
        <el-input
          style="width: 120px;"
          class="inputStyle"
          v-model.trim="carNumber"
        >
        </el-input>
        <el-button
          type="primary"
          class="searchstyle"
          @click="
            initData();
            initTimer();
          "
          >查询</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import { shallowRef } from "@vue/reactivity";
import { lazyAMapApiLoaderInstance } from "vue-amap";
import { sjTime, stringToDate } from "@/utils/sharedJsFile";
import Slider from "./slider.vue";
Vue.use(Slider);
import Vue from "vue";
var infoWindow;
export default {
  name: "PathView",
  setup() {
    const map = shallowRef(null);
    return {
      map
    };
  },
  watch: {
    speedVal: {
      deep: true,
      handler(val, oldVal) {
        let that = this;
        if (that.pathNavigator != null) {
          that.pathNavigator.setSpeed(100 * val);
        }
      }
    }
  },
  data() {
    return {
      //查询车牌号
      carNumber: "",
      //开始时间和结束时间
      startTime:"",
      endTime:"",
      //地图组件
      map: null,
      path:[],
      pointmarker:null,
      //定时器
      timer: null,
      //是否关闭信息窗体
      infoClose:false
    };
  },
  created() {
    let that = this;
    that.initMap(105.602725, 37.076636);
  },
  mounted() {},
  methods: {
    //校验车牌号
    isVehicleNumber(vehicleNumber) {
      // console.log(vehicleNumber);
      var result = false;
      if (vehicleNumber.length == 7) {
        var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使场领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
        result = express.test(vehicleNumber);
      }else if(vehicleNumber.length == 8){
        var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[A-HJ-NP-Z]{1}(([A-HJ-NP-Z0-9]{5})|([0-9]{6}|[A-HJ-NP-Z]{1}[0-9]{5}|[0-9]{5}[A-HJ-NP-Z]{1}|[A-HJ-NP-Z]{2}[0-9]{4}))$/;
        result = express.test(vehicleNumber);
      }
      return result;
    },
    //初始化数据
    initData() {
      let that = this;
      if (that.carNumber == "") {
        this.$message.error("车牌号不能为空！");
        //清除旧的定时器
        clearTimeout(this.timer);
        return;
      } else if (!that.isVehicleNumber(that.carNumber)) {
        this.$message.error("请输入正确的车牌号！");
        //清除旧的定时器
        clearTimeout(this.timer);
        return;
      }
      that.axios
        .get("/api/v1/otms/getCurrentLocation?capcityNumber=" + that.carNumber)
        .then(res => {
          console.log(res.data.data);
          if (res.data.data == "-1") {
            this.$message.error("运输订单未关闭,自提车辆无权查看!");
          } else if (res.data.data.status == "1001") {
            that.map.setCenter([
              res.data.data.result.lon,
              res.data.data.result.lat
            ]);
            //画车
            that.initMarkes(
              45,
              60,
              require("@/assets/img/car1.png"),
              res.data.data.result.lon,
              res.data.data.result.lat,
              "现在所在位置"
            );
            //给路径加点
            let point=new AMap.LngLat(res.data.data.result.lon, res.data.data.result.lat);
            if(that.path.length<=0 || !that.path[that.path.length-1].equals(point)){
              that.path.push(point);
            }
            console.log(that.path);
            //初始化轨迹
            that.initPolyline();
            //显示窗体
            if( this.infoClose==false){
              that.initCustomMarkes(
                that.carNumber,
                res.data.data.result.adr,
                res.data.data.result.lon,
                res.data.data.result.lat
              );
            }
            this.lon = res.data.data.result.lon;
            this.lat = res.data.data.result.lat;
          } else{
             this.$message.error(res.data.data.statusStr);
            //清除定时器
            clearTimeout(this.timer);
          }
        });
    },

    //初始化地图
    initMap(lon, lat) {
      lazyAMapApiLoaderInstance.load().then(() => {
        let that = this;
        that.map = new AMap.Map("amap-container", {
          //设置地图容器id
          viewMode: "2D", //是否为2D地图模式
          zoom: 18, //初始化地图级别
          center: [lon, lat] //初始化地图中心点位置105.602725,37.076636
        });
      });
    },

    //创建简单的标记
    initMarkes(weight, height, image, lon, lat, title) {
      let that = this;
      //图标标记点
      let pointicon = new AMap.Icon({
        size: new AMap.Size(weight, height), // 图标尺寸
        image: image, // Icon的图像
        imageOffset: new AMap.Pixel(2, 10), // 图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(weight, height) // 根据所设置的大小拉伸或压缩图片
      });
      // 创建一个 Marker 实例：
      var pointmarker = new AMap.Marker({
        position: new AMap.LngLat(lon, lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: pointicon,
        title: title,
      });
      // 将创建的点标记添加到已有的地图实例：
      that.pointmarker = pointmarker;
      that.map.add(pointmarker);
    },
    initPoint(weight, height, image, lon, lat, title) {
      let that = this;
      //图标标记点
      let pointicon = new AMap.Icon({
        //size: new AMap.Size(weight, height), // 图标尺寸
        image: image, // Icon的图像
        imageOffset: new AMap.Pixel(0, 10), // 图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(weight, height) // 根据所设置的大小拉伸或压缩图片
      });
      // 创建一个 Marker 实例：
      var pointmarker = new AMap.Marker({
        position: new AMap.LngLat(lon, lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: pointicon,
        title: title,
        label: {
            direction: 'top',
            content: title,
            offset: new AMap.Pixel(-2,10),
        }
      });
      // 将创建的点标记添加到已有的地图实例：
      that.pointmarker = pointmarker;
      that.map.add(pointmarker);
    },
    //初始化轨迹
    initPolyline() {
      let that = this;
      // 创建一个 Polyline 实例：
      var polyline = new AMap.BezierCurve({
            path: that.path,  
            borderWeight: 2, // 线条宽度，默认为 1
            strokeColor: '#18BFA6', // 线条颜色
            lineJoin: 'round' ,// 折线拐点连接处样式
      });
      // 将创建的线路添加到已有的线路中去：
      that.map.add(polyline);
    },
    //时间格式转换
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      let o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + "";
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length)
          );
        }
      }
      return fmt;
    },
    //定时取得当前位置并加入轨迹中去，点击查询时触发，同时清除path和旧的定时器
    initTimer(){
      let that=this;
      //清除旧的定时器
      clearTimeout(this.timer);
      that.startTime=that.formatDate(new Date(),"yyyy年MM月dd日 hh:mm:ss");
      that.endTime=that.formatDate(new Date(),"yyyy年MM月dd日 hh:mm:ss");
      console.log(that.startTime+"至"+that.endTime);
      //清除path
      that.path=[];
      //清除所有覆盖物
      that.map.clearMap();
      //设置所有的门岗和汽车衡
      that.setPoints();
      //设置定时器
      that.timer=setInterval(()=>{
          //清除之前车的图标
          that.map.remove(that.pointmarker);
          that.initData();
          that.endTime=that.formatDate(new Date(),"yyyy年MM月dd日 hh:mm:ss");
      },5000);
    },
    //初始化厂内标记点
    setPoints(){
      //请求所有汽车衡和门岗
      let that=this;
      that.axios.get("/api/v1/otms/mapvertexs/findSelections").then((res)=>{
        console.log(res.data.data);
        if(res.data.data){
          res.data.data.forEach(vertex => {
             that.initPoint(
              20,
              25,
              require("@/assets/img/map_site.png"),
              vertex.longitude,
              vertex.latitude,
              vertex.addressName
            );
          });
        }
      });
    },
    //初始化窗体
    initCustomMarkes(title, details, lon, lat) {
      let that = this;
      //自定义窗体内容
      var content = [
        "<div  style='top:1px;width: 180px; background-color:rgba(22, 160, 133, 1);' ><font color='white'>" +
          title +
          "</font>",
        "<div style='background-color:rgba(22, 160, 133, 1);'><font color='white'>" +
          details + "<br>"+
        "时间范围："+that.startTime+"至"+that.endTime+"<br>"+
          "</font></div></div>"
      ];
      // 创建 infoWindow 实例
      infoWindow = new AMap.InfoWindow({
        content: content.join("<br>"), //传入 dom 对象，或者 html 字符串
        offset: new AMap.Pixel(0, -20) //修改信息差窗体偏移
      });
      // 打开信息窗体
      infoWindow.open(that.map, [lon, lat]);
    },
    // 关闭信息窗口
    closeinfo() {
      this.infoClose=true;
      infoWindow.close();
    },
    openInfo() {
      console.log(this.lon);
      console.log(this.lat);
      this.infoClose=false;
      infoWindow.open(this.map, [this.lon, this.lat]);
    }
  }
};
</script>
<style>
.inputStyle {
  position: absolute;
  width: 200px;
  left: 50px;
}

.controller {
  width: 100%;
  height: 70px;
  background: white;
  position: absolute;
  z-index: 99;
  top: 0;
  left: 0;
}
.in_transit_information {
  width: 320px;
  float: left;
  height: 40px;
}

.container {
  width: 100%;
  height: 100%;
}
span.item_details2 {
  position: relative;
  top: 20px;
}
.date_picker_style {
  position: relative;
  left: 50px;
}
.item_details {
  position: relative;
  top: 5px;
  height: 0px;
  left: 0px;
}
#amap-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0;
  font-family: "微软雅黑";
}

/* 进度条 */
.mySlider {
  width: 150px;
  height: 20px;
  display: inline-block;
  position: relative;
  left: 32px;
}
/* 进度条 */
.mySlider2 {
  width: 400px;
  height: 20px;
  display: inline-block;
  position: relative;
  left: 32px;
}
.play {
  position: relative;
  left: 28px;
}
.quickly {
  float: right;
  position: relative;
  left: -20px;
  top: 10px;
}
.pause {
  position: relative;
  left: 28px;
}
.passed-time {
  position: relative;
  left: 5px;
}
.end-time {
  position: relative;
  left: 5px;
}
.map-times {
  position: relative;
  width: 40px;
}
.searchstyle {
  position: relative;
  left: 45px;
}
.map-control {
  float: left;
  width: 270px;
}
.driving_information {
  height: 40px;
  width: 240px;
  float: left;
}
</style>
<style lang="scss" scoped>
.btnx {
  z-index: 1000;
  position: fixed;
  bottom: 10px;
  right: 10px;
}
</style>
