/*
 *@description:地图
 *@author: hudw
 *@date: 2022-09-16 09:17:47
*/
<template>
  <div class="webMap">
    <div class="input-card" v-if="seatList && myMarkerList2.length > 0">
      <a-timeline>
        <a-timeline-item v-for="(item, index) in seatList" :key="index" @click="()=>{myMap.clearInfoWindow(),showLabel(item.marker, 'seat'),myMap.setCenter(item.position, true)}">
          <div slot="dot" class="timeline-sort">{{ index + 1 }}</div>
          <div>
            <div
              :class="{
                'timeline-sort': true,
                ti: item.siteTypeName === '提货点',
                song: item.siteTypeName === '送货点',
              }"
            >
              {{ item.siteTypeName.split('')[0] }}
            </div>
            <b style="font-size: 14px"> {{ item.siteName }}</b>
          </div>

          <div>预计提货时间:{{ item.estimatedTime }}</div>

          <div>
            实际提货时间:{{ item.actualTime }}
            <div class="late" v-show="item.timeDescription">（{{ item.timeDescription }}）</div>
            <div class="accurate" v-show="!item.timeDescription">（准点）</div>
            <div>温度:{{ item.temperature }}</div>
          </div>
        </a-timeline-item>

      </a-timeline>
    </div>

    <div :id="'web-map-' + $route.meta.menuId" style="height: 600px; width: 100%"></div>
  </div>
</template>
<script>
import mock from './mock.json';

function iconConfig(obj = {}) {
  return {
    // 图标尺寸
    size: new AMap.Size(28, 36),
    // 图标的取图地址
    image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
    // 图标所用图片大小
    imageSize: new AMap.Size(135, 40),
    // 图标取图偏移量
    ...obj,
  };
}
const startIcon = new AMap.Icon(iconConfig({ imageOffset: new AMap.Pixel(-5, -3) }));

export default {
  props: {
    dataSource: {
      type: null,
    },
    type: {
      type: String,
      //location=定位，path=轨迹
    },
    queryType: {
      type: String,
      //wechat=小程序 device =设备
    },
    seatList: {
      type: null,
      //派车单站点
    },
  },
  data() {
    return {
      selectIndex: -1,
      SimpleMarker: '',
      SimpleInfoWindow: '',
      pathSimplifierIns: '',
      PathSimplifier: '',
      lineArr: [],
      myMarker: null,
      myMarkerList: [],
      geocoder: null,
      myMap: null,
      polyline: null,
      driving: null,
      loca: null,
      myMarkerList2: [],
    };
  },
  watch: {
    seatList(value) {
      this.myMarkerList2 && this.myMap.remove(this.myMarkerList2);
      this.myMarkerList2=[]
      this.myMap.clearInfoWindow();

      if (value) {
        this.myMarkerList2 = value.map((item, index) => {
          const { longitude, latitude } = item;
          item.position = [longitude, latitude];
          item.marker = new AMap.Marker({
            extData: item,
            map: this.myMap,
            position: item.position,
            anchor: 'center',
            content: `<i class='icon-marker-red'>${index + 1}<i/>`,
            //offset: new AMap.Pixel(-13, -26),
            zIndex: 14,
            cursor: 'pointer',
          });
          item.marker.on('click', () => {
            this.myMap.clearInfoWindow();
            this.showLabel(item.marker, 'seat');
            this.myMap.setCenter(item.position, true);

          });
          return item.position;
        });

        this.myMap.setFitView(null, true);

      }
    },
    dataSource(value) {
      this.myMarkerList2 && this.myMap.remove(this.myMarkerList2);
      this.myMarkerList2=[]
      this.myMarker && this.myMap.remove(this.myMarker);
      this.myMap.remove(this.myMarkerList);
      this.polyline && this.myMap.remove(this.polyline);
      this.myMarker = null;
      this.myMarkerList = [];
      this.lineArr = [];
      this.polyline = null;
      this.myMap.clearMap();
      this.myMap.clearInfoWindow();
      if (this.loca) {
        this.loca.layer.destroy();
        this.loca.destroy();
        this.loca = null;
      }

      if (value) {
        if (this.type == 'path') {
          // this.pathMap2(value);
          this.initPageLine(value);
        } else if (this.type == 'location') {
          this.locationMap(value);
        }
      } else {
      }
    },
  },

  mounted() {
    this.init();

    // this.myMap.on('complete', () => {
    //   this.$message.success('地图加载完成！');
    // });
  },
  destroyed() {
    this.myMap && this.myMap.destroy();
  },
  created() {
    this.useMap();
  },
  methods: {
    getLocationContent(value) {
      const {
        shipbillId,
        driverName,
        driverPhoneNumber,
        deviceName,
        gpsDate,
        vehicleDirection,
        formattedAddress,
        currentVelocity,
        longitude,
        latitude,
        shipbillNo,
        vehiclePlateNumber,
        consigneeAddress,
      } = value;
      let content = {
        wechat: `
                <div class="info">
                  <div class="info-item">
                    <label>运单号:</label>
                    <div class="wrapper">${shipbillNo}</div>
                  </div>
                  <div class="info-item">
                    <label>车牌号:</label>
                    <div class="wrapper">${vehiclePlateNumber}</div>
                  </div>
                  <div class="info-item">
                    <label>当前位置:</label>
                    <div class="wrapper"> ${formattedAddress}</div>
                  </div>
                  ${
                    consigneeAddress
                      ? `<div class="info-item">
                    <label>收货地址:</label>
                    <div class="wrapper">${consigneeAddress}</div>
                  </div>`
                      : ''
                  }
                 </div>
                `,
        device: `
                <div class="info">
                  <div class="info-item">
                    <label>运单号:</label>
                    <div class="wrapper">${deviceName}</div>
                  </div>
                  <div class="info-item">
                    <label>时间:</label>
                    <div class="wrapper">${gpsDate}</div>
                  </div>
                  <div class="info-item">
                    <label>坐标:</label>
                    <div class="wrapper">${[longitude, latitude].join(',')}</div>
                  </div>
                  <div class="info-item">
                    <label>道路信息:</label>
                    <div class="wrapper"> ${formattedAddress}</div>
                  </div>
                 </div>
                `,
        //wechat=小程序 device =设备 deviceLink
        deviceLink: `<div class="info">
                  <div class="info-item">
                    <label>运单号:</label>
                    <div class="wrapper">${shipbillId}</div>
                    </div>
                    <div class="info-item">
                    <label>车牌号:</label>
                    <div class="wrapper">${vehiclePlateNumber}</div>
                  </div>
                   <div class="info-item">
                    <label>司机:</label>
                    <div class="wrapper">${driverName}</div>
                  </div>
                  <div class="info-item">
                    <label>手机号:</label>
                    <div class="wrapper">${driverPhoneNumber}</div>
                  </div>
                  <div class="info-item">
                    <label>当前位置:</label>
                    <div class="wrapper">${formattedAddress}</div>
                  </div>
                  </div>`,
      };
      return content[this.queryType];
    },
    getPathContent(value, name) {
      const {siteTypeName, driverPhoneNumber,driverName,shipbillId, loadingBillNo, deviceName, gpsDate, vehicleDirection, formattedAddress, currentVelocity, longitude, latitude, shipbillNo, vehiclePlateNumber, consigneeAddress } = value;

      if (name == 'seat') {
       let pName= siteTypeName?.substring(0,2)??''
      let infoBody= `<div class="seat info">
          <div class="info-item">
            <h4>${siteTypeName||''}</h4>
          </div>
          <div class="info-item">
            <label>${pName}顺序:</label>
            <div class="wrapper">${value.siteOrder||''}</div>
          </div>
          <div class="info-item">
            <label>${pName}地点:</label>
            <div class="wrapper">${value.siteName||''}</div>
          </div>
          <div class="info-item">
            <label>总运单数:</label>
            <div class="wrapper">${value.shipbillQty||''}</div>
          </div>
          <div class="info-item">
            <label>总件数:</label>
            <div class="wrapper">${value.totalPieceQty||''}</div>
          </div>
          <div class="info-item">
            <label>总重量:</label>
            <div class="wrapper">${value.totalWeightQty||''}</div>
          </div>
          <div class="info-item">
            <label>总体积:</label>
            <div class="wrapper">${value.totalVolumeQty||''}</div>
          </div>
          <div class="info-item">
            <label>要求${pName}时间:</label>
            <div class="wrapper">${value.estimatedTime||''}</div>
          </div>
          <div class="info-item">
            <label>实际${pName}时间:</label>
            <div class="wrapper">
              ${value.actualTime||''}
            </div>
          </div>
          <div class="info-item">
            <label></label>
            <div class="wrapper">
              ${value.timeDescription || ''}
            </div>
            <div>
        </div>`

        return infoBody;
      }


      let content = {
        wechat: `
                <div class="info">
                  <div class="info-item">
                    <label>派车单号:</label>
                    <div class="wrapper">${loadingBillNo||''}</div>
                  </div>
                  <div class="info-item">
                    <label>运单号:</label>
                    <div class="wrapper">${shipbillNo||''}</div>
                  </div>
                  <div class="info-item">
                    <label>车牌号:</label>
                    <div class="wrapper">${vehiclePlateNumber||''}</div>
                  </div>
                  <div class="info-item">
                    <label>当前位置:</label>
                    <div class="wrapper"> ${formattedAddress||''}</div>
                  </div>
                  ${consigneeAddress? `<div class="info-item">
                    <label>收货地址:</label>
                    <div class="wrapper">${consigneeAddress}</div>
                  </div>`
                      : ''
                  }
                 </div>
                `,
        device: `
                <div class="info">
                  <div class="info-item">
                    <label>运单号:</label>
                    <div class="wrapper">${deviceName}</div>
                  </div>
                  <div class="info-item">
                    <label>时间:</label>
                    <div class="wrapper">${gpsDate}</div>
                  </div>
                  <div class="info-item">
                    <label>坐标:</label>
                    <div class="wrapper">${[longitude, latitude].join(',')}</div>
                  </div>
                  <div class="info-item">
                    <label>道路信息:</label>
                    <div class="wrapper"> ${formattedAddress}</div>
                  </div>
                 </div>
                `,
        deviceLink: `<div class="info">
                  <div class="info-item">
                    <label>运单号:</label>
                    <div class="wrapper">${shipbillId||''}</div>
                    </div>
                    <div class="info-item">
                    <label>车牌号:</label>
                    <div class="wrapper">${vehiclePlateNumber||''}</div>
                  </div>
                   <div class="info-item">
                    <label>司机:</label>
                    <div class="wrapper">${driverName||''}</div>
                  </div>
                  <div class="info-item">
                    <label>手机号:</label>
                    <div class="wrapper">${driverPhoneNumber||''}</div>
                  </div>
                  <div class="info-item">
                    <label>当前位置:</label>
                    <div class="wrapper">${formattedAddress||''}</div>
                  </div>
                  </div>`,
      };


      return content[this.queryType];
    },
    // 画线

    //轨迹画线
    initPageLine(value) {
      let ednIcon = null;
      const { desc, status, tmsVehicleGpsDTOList, consigneeAddress } = value;
      if (desc == '在途') {
        ednIcon = new AMap.Icon(
          iconConfig({
            imageOffset: new AMap.Pixel(-52, -3),
          })
        );
      } else if (desc == '终点') {
        ednIcon = new AMap.Icon(
          iconConfig({
            imageOffset: new AMap.Pixel(-95, -3),
          })
        );
      }

      if (!tmsVehicleGpsDTOList || tmsVehicleGpsDTOList.length == 0) {
        return this.$exception({
          message: '未查到路线轨迹！',
        });
      }

      let _this = this;
      let lineArr = tmsVehicleGpsDTOList.map((item, index) => {
        const { longitude, latitude, shipbillNo } = item;
        let position = [longitude, latitude];
        let _item;
        if (this.queryType !== 'deviceLink') {
          if (desc && index === 0) {
            this.myMarker = _item = new AMap.Marker({
              extData: item,
              map: _this.myMap,
              icon: startIcon,
              position,
              anchor: 'center',
              //offset: new AMap.Pixel(-13, -26),
              zIndex: 13,
              cursor: 'pointer',
            });
            _item.position=position
          } else if (desc && ednIcon && tmsVehicleGpsDTOList.length == index + 1 && index !== 0) {
            _item = new AMap.Marker({
              map: _this.myMap,
              extData: item,
              icon: ednIcon,
              position,
              cursor: 'pointer',
              // offset: new AMap.Pixel(-13, -30),
            });
            _item.position=position

          } else {
            _item = new AMap.Marker({
              extData: item,
              content: `<i class='icon-marker-red'>${index}</i>`,
              position,
              anchor: 'center',
              cursor: 'pointer',
              //offset: new AMap.Pixel(-10, -31),
            });
            _item.position=position

          }

          _item &&
            _item.on('click', function () {
              _this.myMap.clearInfoWindow();
              _this.showLabel(this);
              _this.myMap.setCenter(_item.position, true);

            });

          _item && this.myMarkerList.push(_item);
        }
        return position;
      }, this);

      try {
        //=== 'deviceLink'
        if (this.queryType) {
          let loca = new Loca.Container({
            map: this.myMap,
          });
          let geo = new Loca.GeoJSONSource({
            data: {
              type: 'FeatureCollection',
              features: [
                {
                  type: 'Feature',
                  geometry: {
                    type: 'LineString',
                    coordinates: lineArr,
                  },
                },
              ],
            },
          });
          const layer = new Loca.PulseLineLayer({
            zIndex: 10,
            opacity: 1,
            visible: true,
            //zooms: [2, 22],
          });
          layer.setSource(geo);
          layer.setStyle({
            altitude: 0,
            lineWidth: 6,
            // 脉冲头颜色
            headColor: '#efd551',
            // 脉冲尾颜色
            trailColor: 'rgba(128, 128, 128, 0.5)',
            interval: 1,
            // 脉冲线的速度，几秒钟跑完整段路
            duration: 5000,
          });
          loca.add(layer);
          loca.animate.start();
          this.loca = loca;
          this.loca.layer = layer;
          let c = lineArr[~~((lineArr.length - 1) / 2)];
          this.myMap.setCenter(c, true);


        } else {
          this.polyline = new AMap.Polyline({
            map: this.myMap,
            path: lineArr,
            geodesic: true,
            extData: {},
            showDir: true,
            lineJoin: 'round',
            strokeColor: '#28F', //线颜色
            // strokeOpacity: 1,     //线透明度
            strokeWeight: 6, //线宽
            // strokeStyle: "solid"  //线样式
          });
          this.polyline.on('click', function () {
            _this.showLabel(this);
          });
        }

        this.myMap.setFitView(null, true);

      } catch (err) {
        this.$exception({
          message: '路线轨迹错误！',
        });
        throw new Error(err);
      }
    },
    // 轨迹画线


    //定位
    locationMap(value, ) {
      const { longitude, latitude, shipbillNo, vehiclePlateNumber, consigneeAddress } = value;
      let position = [longitude, latitude];
      this.geocoder?.getAddress(new AMap.LngLat(position[0], position[1]), (status, result) => {
        value.formattedAddress = '';
        if (status === 'complete' && result.regeocode) {
          const { formattedAddress } = result.regeocode;
          value.formattedAddress = formattedAddress;
        }

        let infoWindow = new AMap.InfoWindow({
          content: this.getLocationContent(value),
          offset: new AMap.Pixel(0, -40),
        });
        infoWindow.open(this.myMap, position);
      });

      this.myMarker = new AMap.Marker({
        icon: new AMap.Icon({
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          anchor: 'bottom-center',
          size: [28, 38],
        }),
        position,
        anchor: 'bottom-center',
      });

      this.myMap.add(this.myMarker);
      this.myMap.setCenter([longitude, latitude], true);
      this.myMap.setFitView(null, true,[20,20,20,120]);
    },

    reset() {
      this.myMarker && this.myMap.remove(this.myMarker);
      this.myMap.remove(this.myMarkerList);
      this.polyline && this.myMap.remove(this.polyline);
      this.myMap && this.myMap.destroy();
      if (this.loca) {
        this.loca.layer.destroy();
        this.loca.destroy();
        this.loca = null;
      }
      this.init();
    },
    useMap() {
      let _this = this;
      //简单标注
      AMapUI.loadUI(['overlay/SimpleMarker', 'overlay/SimpleInfoWindow'], (SimpleMarker, SimpleInfoWindow) => {
        //启动页面
        this.SimpleMarker = SimpleMarker;
        this.SimpleInfoWindow = SimpleInfoWindow;
      });
      AMap.plugin(['AMap.Driving', 'AMap.PlaceSearch', 'AMap.ToolBar'], () => {
        //异步同时加载多个插件
        _this.placeSearch = new AMap.PlaceSearch({
          map: _this.myMap,
        });
      });
      this.geocoder = new AMap.Geocoder();
    },
    showLabel(vNode,name) {
      let value = vNode.getExtData();
      value.formattedAddress = '';

      const { longitude, latitude } = value;
      this.geocoder?.getAddress(new AMap.LngLat(longitude, latitude), (status, result) => {
        if (status === 'complete' && result.regeocode) {
          value.formattedAddress = result.regeocode.formattedAddress;
        }
        let infoWindow = new AMap.InfoWindow({
          content: this.getPathContent(value,name),
          offset: new AMap.Pixel(0, -25),
          avoid: true,
          autoMove: true,
          anchor: 'bottom-center',
        });
        infoWindow.open(this.myMap, vNode.getPosition());
      });
    },
    init() {
      let _this = this;
      this.myMap = new AMap.Map('web-map-' + _this.$route.meta.menuId, {
        //scrollWheel: true,
        // resizeEnable: true,
        //viewMode: '2D', // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D',
        //mapStyle: 'amap://styles/light',
        showLabel: true,
        mapStyle: 'amap://styles/grey',
      });
      let toolBar = new AMap.ToolBar({
        position: {
          bottom: '20px',
          right: '20px',
        },
      });
      this.myMap.addControl(toolBar);
    },
  },
};
</script>
<style lang='less'>
.webMap {
  position: relative;

  .input-card {
    position: absolute;

    padding: 20px;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    left: 10px;
    width: 280px;
    z-index: 1;
    background-color: #fff;
  }

  .icon-jing {
    // width: 32px;
    // height: 46px;
    width: 25px;
    height: 37px;
    display: block;
    text-align: center;
    color: #fff;
    padding-top: 3px;
    font-weight: bold;
    background: url('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png') no-repeat center center;
    background-size: contain;
  }

  .timeline-sort {
    width: 20px;
    height: 20px;
    line-height: 20px;
    font-size: 15px;
    font-weight: bold;
    border-radius: 50%;
    background-color: #2b80ff;
    color: #fff;
    text-align: center;
  }

  .ant-timeline-item {
    //font-size: 1px;
  }

  .ti {
    font-size: 14px;
    border-radius: 10%;
    background-color: #2b80ff;
    display: inline-block;
  }

  .song {
    font-size: 15px;
    font-weight: bold;
    border-radius: 10%;
    background-color: rgb(107, 15, 216);
    display: inline-block;
  }

  .warning {
    color: red;
    margin-right: 10px;
  }

  .accurate {
    color: rgb(26, 34, 252);
    display: inline-block;
  }

  .late {
    color: red;
    display: inline-block;
  }
  .icon-marker-red {
    width: 25px;
    height: 37px;
    display: block;
    text-align: center;
    color: #fff;
    padding-top: 3px;
    font-weight: bold;
    background: url('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png') no-repeat center center;
    background-size: contain;
  }
  //a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png
  .map-icon-origin {
    background: url('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png') no-repeat center center;
    background-size: contain;
    width: 12px;
    height: 12px;
    border-radius: 100%;
    display: block;
    border: 3px solid rgba(#28f, 0.7);
    background-color: #fff;
    // &:hover {
    //   transform: scale(1.2, 1.2);
    // }
  }
  .amap-copyright,
  .amap-logo {
    z-index: -999;
  }
  .amap-icon img {
    width: 100%;
    height: 100%;
  }

  .amap-marker-label {
    border: 0;
    border-radius: 4px;
    box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
  }

  .info {
    &.seat{
      label {
        width: 100px;

      }
    }
    padding: 5px;
    position: relative;
    white-space: normal;
    min-width: 300px;
    line-height: 1.8;
  }
  .info-item {
    display: flex;
    label {
      width: 70px;
      color: #333;
      text-align: right;
    }
    .wrapper {
      flex: 1;
    }
  }
}
</style>


<!-- add,新增
del,删除
view,查看详情
edit,修改
status,停启用
copy,复制
mapParse,地址解析
saveSubmit,保存并提交 -->

