<template>
  <!-- 配送中轨迹查询 -->
  <div style="width: 100%;height: 100%;">
    <div id="container"></div>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
    props: {
      // 轨迹列表
      trackList: {
        type: Array,
        default: () => [],
      },
      waybillBasic: {
        type: Object,
        default: () => {},
      },
    },
    data() {
      return {
        map: null,
        arrCation: [],
      }
    },
    mounted() {},
    methods: {
      async keyUpSearch() {
        var that = this
        var positions = this.trackList;
        that.map = new AMap.Map("container", {
          resizeEnable: true,
          zoom: 14,
          center: positions[0],
        });
        AMap.service(["AMap.PlaceSearch"], function() {
          var placeSearch = new AMap.PlaceSearch({ //构造地点查询类
            map: that.map,
            panel: "result",
            autoFitView: true
          });
        })
        that.map.setFitView()

        // 创建一个 起点Icon
        var startIcon = new AMap.Icon({
          size: new AMap.Size(40, 40),
          image: require('../assets/images/destination.png'),
          imageSize: new AMap.Size(40, 40),
          imageOffset: new AMap.Pixel(0, 0)
        });
        // 创建一个 终点icon destination.png
        var endIcon = new AMap.Icon({
          size: new AMap.Size(40, 40),
          image: require('../assets/images/transport.png'),
          imageSize: new AMap.Size(40, 40),
          imageOffset: new AMap.Pixel(0, 0)
        });

        let arr = await that.longitudeLatitude(that.waybillBasic.consigneeAddressDetails)
        var propertyName = arr.location.split(",")

        if (positions.length > 0) {
          // 添加起点和终点
          const startMarker = new AMap.Marker({
            position: propertyName,
            icon: startIcon,
            offset: new AMap.Pixel(-13, -30)
          });
          const num = positions.length
          const endMarker = new AMap.Marker({
            position: positions[num - 1],
            icon: endIcon,
            offset: new AMap.Pixel(-13, -30),
            autoRotation: true,
          });
          var p1 = startMarker.getPosition();
          var p2 = endMarker.getPosition();
          var distance = Math.round(p1.distance(p2));
          // console.log(distance, 23)
          // 转换距离单位
          function setMorKm(m) {
            var n = ''
            if (m) {
              if (m >= 1000) {
                n = (m / 1000) + 'km'
                // n = (m / 1000).toFixed(2) + 'km'
              } else {
                n = m + 'm'
              }
            } else {
              n = '0m'
            }
            return n
          }
          let distanceNum = setMorKm(distance)

          function calculateTime(distance, speed) {
            // 将距离从米转换为公里
            let velocity = speed
            if(distance < 900){
              velocity = 10
            }
            const distanceInKm = distance / 1000;
            // 计算所需时间（单位：小时）
            const hours = distanceInKm / (velocity / 60); // 因为速度是每小时多少公里，所以除以60转换为小时
            // return hours.toFixed(2); // 保留两位小数
            return Math.round(hours); // 取整
          }
          const speed = 25; //骑行速度
          const timeMins = calculateTime(distance, speed);
          // console.log(`预计到达时间：约 ${timeMins} 分钟`);
          endMarker.setLabel({
            offset: new AMap.Pixel(0, -50),
            content: `<div class='info'><div class='headline_title'>药品正在路上</div><div class='card_tag'><div class='distance_title'>距您</div><div class='orange_title'>${distanceNum}</div><div class='line_card'>|</div><div class='orange_title'>${timeMins}分钟</div></div><div class='popper__arrow'></div></div>`,
            direction: 'center',
          });
          that.map.add(startMarker);
          that.map.add(endMarker);
        }
        // 绘制轨迹
        // var polyline = new AMap.Polyline({
        //   map: that.map,
        //   path: positions,
        //   showDir: true,
        //   strokeColor: "#28F", //线颜色
        //   strokeWeight: 10, //线宽
        //   strokeStyle: "solid",
        //   lineJoin: 'round',
        //   lineCap: 'round',
        // });
      },
      // 获取经纬度
      longitudeLatitude(value) {
        return new Promise((resolve, inject) => {
          axios.get('https://restapi.amap.com/v3/geocode/geo?key=b3bfb74d9dbac0c9b8049894b6f72adb' + '&address=' +
            value).then((res) => {
            resolve(res.data.geocodes[0])
          }).catch(() => {
            this.confirmLoading = false
          })
        })
      },
      destroyMap() {
        this.map && this.map.destroy();
      },
      close() {
        this.destroyMap()
        this.$emit('close')
      }
    }
  }
</script>

<style lang="scss" scoped>
  #container {
    position: relative;
    width: 100%;
    height: 100%;
  }

  #container ::v-deep .amap-logo {
    display: none !important;
    left: 0;
    height: 1.0625rem;
    margin: 0 1px;
  }

  #container ::v-deep .amap-copyright {
    display: none !important;
    left: 4.375rem;
    height: 1rem;
    font-size: 0.6875rem;
  }

  ::v-deep .amap-marker-label {
    border: 0;
    padding: 7px;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12);
    // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  ::v-deep .info {
    display: flex;
    flex-direction: column;
    position: relative;
    bottom: 0;
    min-width: 0;
  }

  ::v-deep .headline_title {
    display: flex;
    font-size: 15px;
    font-weight: 600;
    margin-bottom: 5px;
  }

  ::v-deep .card_tag {
    display: flex;
    align-items: center;
  }

  ::v-deep .distance_title {
    font-size: 13px;
    color: #909399;
    margin-right: 3px;
  }

  ::v-deep .orange_title {
    font-size: 13px;
    color: #E6A23C;
  }

  ::v-deep .line_card {
    margin: 0px 3px;
    color: #DCDFE6;
  }

  ::v-deep .popper__arrow {
    position: absolute;
    display: block;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
    bottom: -23px;
    left: calc(50% - 6px);
    margin-right: 3px;
    border-top-color: #fff;
    border-bottom-width: 0;
    border-width: 9px;
    filter: drop-shadow(0 2px 12px rgba(0, 0, 0, .13));
  }

  ::v-deep .popper__arrow:after {
    content: " ";
    border-width: 6px;
    bottom: 1px;
    margin-left: -6px;
    border-top-color: #fff;
    border-bottom-width: 0;
  }
</style>
