<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));
          // 转换距离单位
          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 calculateTravelTime(point1, point2, speedKmph) {
            // 计算两点之间的距离（使用Haversine公式）
            function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
              const R = 6371; // 地球半径，单位为公里
              const dLat = (lat2 - lat1) * (Math.PI / 180);
              const dLon = (lon2 - lon1) * (Math.PI / 180);
              const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2);
              const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
              const d = R * c;
              return d;
            }

            const distanceKm = getDistanceFromLatLonInKm(point1[0], point1[1], point2[0], point2[1]);
            const travelTimeHours = distanceKm / (speedKmph / 60); // 时间 = 距离 ÷ 速度
            const travelTimeMins = Math.round(travelTimeHours * 60); // 将小时转换为分钟
            return travelTimeMins;
          }

          // 使用示例：
          const point1 = propertyName; // 巴黎的一个坐标点
          const point2 = positions[num - 1]; // 离巴黎不远的另一个坐标点
          const speedKmph = 70; // 假设的速度（千米/小时）
          const timeMins = calculateTravelTime(point1, point2, speedKmph);
          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=fcddcc366fd5bd355e35f01b7cce82ef' + '&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>
