<template>
  <div class="place-search-map" :style="{ width: width, height: height }" v-loading="loading">
    <div id="container"></div>
    <div class="input-card">
      <h4>轨迹回放控制</h4>
      <div class="input-item">
        <input type="button" class="btn" value="开始动画" id="start" @click="startAnimation()" />
        <input type="button" class="btn" value="暂停动画" id="pause" @click="pauseAnimation()" />
      </div>
      <div class="input-item">
        <input type="button" class="btn" value="继续动画" id="resume" @click="resumeAnimation()" />
        <input type="button" class="btn" value="停止动画" id="stop" @click="stopAnimation()" />
      </div>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import globalConfig from '@/utils/config/globalConfig'
import AreaTextSelect from '@/components/AreaTextSelect/index.vue'
import { getArea } from '@/api/system/area'
import { listParking } from '@/api/system/parking'
export default {
  name: "TrajectoryMap",
  components: { AreaTextSelect },
  props: {
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    initLng: {
      type: String,
      default: '120.250452'
    },
    initLat: {
      type: String,
      default: '27.101745'
    },
    areaId: {
      type: Number,
      default: ''
    },
    tripRouteStr: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      AMap: null,
      map: null,  // 地图实例
      placeSearch: null,  // POI查询
      geocoder: null, // 逆地理编码
      loading: false,
      keyword: null,
      markers: [],
      line: [],
      area: {
        province: '福建省',
        city: '宁德市',
      },
      area:{},
      parkingList:[],
      noParkingList:[],
      noridingList:[],
      labels: [],
    }
  },
  mounted() {
    console.log(this.areaId,'areaIdareaIdareaId');
    // this.initAMap();
    this.getAreas(this.areaId)
  },
  beforeDestroy() {
    this.destroyMap();
  },
  methods: {
    destroyMap() {
      if (this.map) {
        console.log("轨迹=====地图实例存在，销毁地图...");
        this.map.destroy();
        console.log("轨迹=====地图已销毁");
      } else {
        console.log("轨迹=====地图实例不存在，无需销毁");
      } 
    },
    showMarkers() {
      if (this.show) {
        // this.markers.forEach(marker => {
        //   marker.show();
        // });
        this.labels.forEach(label => {
          label.show();
        });
      } else {
        // this.markers.forEach(marker => {
        //   marker.hide();
        // });
        this.labels.forEach(label => {
          label.hide();
        });
      }
      this.show = !this.show;
      const elements = document.querySelectorAll('.apiary-marker-name');
      elements.forEach(element => {
        element.style.visibility = this.show ? 'hidden' : 'visible';
      });
    },
    async getAreas(areaId) {
      getArea(this.areaId).then(response => {
      
          console.log(response,'responseresponse');
          this.area = response.data;
          
        
          listParking({ areaId: this.area.areaId }).then(response => {
            let list = response.rows;
            console.log(list,'listlistlist');
            list.forEach(item => {
              if (item.type == '1') {
                this.parkingList.push(item);
              } else if (item.type == '2') {
                this.noParkingList.push(item);
              } else if (item.type == '3') {
                this.noridingList.push(item);
              }
            });
          
            this.initAMap();
          });
      });
    },
    initAMap() {
      AMapLoader.load({
        key: globalConfig.aMap.key, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.PlaceSearch", "AMap.MoveAnimation"], // 确保包含 "AMap.MoveAnimation"
      }).then((AMap) => {
        let abb;
      try {
        abb = JSON.parse(this.tripRouteStr);
      } catch (error) {
        console.error("Error parsing tripRouteStr:", error);
        return;
      }
      let latitude = parseFloat(abb[0][1]);
      let longitude = parseFloat(abb[0][0]);
        this.AMap = AMap;
        this.map = new AMap.Map("container", {
          // 设置地图容器id
          resizeEnable: true,
          viewMode: "3D", // 是否为3D地图模式
          zoom: 16, // 初始化地图级别
          // center: [this.initLng == null ? 120.250452 : this.initLng, this.initLat == null ? 27.101745 : this.initLat], // 初始化地图中心点位置
          center:[longitude,latitude]
        });
        this.addArea(JSON.parse( this.area.boundaryStr) || []);
         //停车区
         this.parkingList.forEach(parking => {
          this.addParking(JSON.parse(parking.boundaryStr) || [], parking.parkingName, parking.longitude, parking.latitude);
          this.addMarker2(parking, "https://lxnapi.ccttiot.com/FqcYf6ecsnbC0OT6YYAF5npgu-kh", parking.parkingName, "#1890ff");
        });
        //禁停区
        this.noParkingList.forEach(noparking => {
          this.addNoParking(JSON.parse(noparking.boundaryStr) || []);
          this.addMarker2(noparking, "https://lxnapi.ccttiot.com/FjKE5PWbnEnZUq3k-wVIvV4lv8Ab", noparking.parkingName, "#ff4444");
        });
        //禁行区
        this.noridingList.forEach(noriding => {
          this.addNoriding(JSON.parse(noriding.boundaryStr) || [], noriding.parkingName, noriding.longitude, noriding.latitude);
          this.addMarker2(noriding, "https://lxnapi.ccttiot.com/FmX1diEPPbFYe1vcUfKp6qbKzzh2", noriding.parkingName, "#ffcc00");
        });
        this.trajectory(); //轨迹

      }).catch((e) => {
        console.log("地图加载失败！！！");
        console.log(e);
      });
    },
    addMarker2(parking, icon, title, color) {
      let marker = new AMap.Marker({
        map: this.map,
        icon: new AMap.Icon({
          image: icon,
          size: new AMap.Size(25, 36), // 设置图标的宽高
          imageSize: new AMap.Size(25, 36) // 设置图标的实际显示尺寸
        }),
        position: [parking.longitude, parking.latitude],
        offset: new AMap.Pixel(-12.5, -36)
      });

      this.markers.push(marker);

      // console.log("title============="+title)
      // 创建一个 Text 实例来显示标题
      let text = new AMap.Text({
        text: title,
        anchor: 'center', // 设置文本的锚点
        position: [parking.longitude, parking.latitude],
        offset: new AMap.Pixel(0, -50),
        style: {
          'background-color': color, // 背景颜色为蓝色
          'border': 'none', // 边框颜色与背景一致
          'border-radius': '5px', // 圆角 5px
          'color': 'white', // 文字颜色为白色
          'font-size': '12px', // 字体大小
        }
      });

      // 将文本标签添加到地图实例
      this.map.add(text);
      // console.log("text=============",text)
      this.labels.push(text)
    },
    addParking(data, title, lon, lat) {
      let polygon = new AMap.Polygon({
        path: data,
        fillColor: '#ccebc5',
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: '#3b7ed9',  // 修改边界颜色为红色
        strokeWeight: 2,         // 加粗边界
        strokeStyle: 'solid',
        strokeDasharray: [5, 5],
      });
      polygon.on('mouseover', () => {
        polygon.setOptions({
          fillOpacity: 0.7,
          fillColor: '#71b7cc'  // 鼠标悬浮时填充颜色为红色
        });
      });
      polygon.on('mouseout', () => {
        polygon.setOptions({
          fillOpacity: 0.5,
          fillColor: '#a7c1d0'  // 鼠标移出时恢复填充颜色
        });
      });
      this.map.add(polygon);
    },
    addNoParking(data) {
      let polygon = new AMap.Polygon({
        path: data,
        fillColor: '#ccebc5',
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: '#ff0000',  // 修改边界颜色为红色
        strokeWeight: 2,         // 加粗边界
        strokeStyle: 'solid',
        strokeDasharray: [5, 5],
      });
      polygon.on('mouseover', () => {
        polygon.setOptions({
          fillOpacity: 0.7,
          fillColor: '#ff0000'  // 鼠标悬浮时填充颜色为红色
        });
      });
      polygon.on('mouseout', () => {
        polygon.setOptions({
          fillOpacity: 0.5,
          fillColor: '#cc7b7b'  // 鼠标移出时恢复填充颜色
        });
      });
      this.map.add(polygon);
    },
    addNoriding(data, title, lon, lat) {
      let polygon = new AMap.Polygon({
        path: data,
        fillColor: '#ccebc5',
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: '#ffcc00',  // 修改边界颜色为红色
        strokeWeight: 2,         // 加粗边界
        strokeStyle: 'solid',
        strokeDasharray: [5, 5],
      });
      polygon.on('mouseover', () => {
        polygon.setOptions({
          fillOpacity: 0.7,
          fillColor: '#FFEBA4FF'
        });
      });
      polygon.on('mouseout', () => {
        polygon.setOptions({
          fillOpacity: 0.5,
          fillColor: '#ffeba4'
        });
      });
      this.map.add(polygon);
    },
  
    addArea(data) {
      let polygon = new AMap.Polygon({
        path: data,
        fillColor: '#ccebc5',
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: '#2b8cbe',
        strokeWeight: 1,
        strokeStyle: 'dashed',
        strokeDasharray: [5, 5],
      });
      // polygon.on('mouseover', () => {
      //   polygon.setOptions({
      //     fillOpacity: 0.7,
      //     fillColor: '#7bccc4'
      //   })
      // })
      // polygon.on('mouseout', () => {
      //   polygon.setOptions({
      //     fillOpacity: 0.5,
      //     fillColor: '#ccebc5'
      //   })
      // })
      this.map.add(polygon);
    },
    // 显示轨迹
    trajectory() {
      this.line = JSON.parse(this.tripRouteStr)
      console.log("this.line================" + this.line)
      let abb;
      try {
        abb = JSON.parse(this.tripRouteStr);
      } catch (error) {
        console.error("Error parsing tripRouteStr:", error);
        return;
      }
      let latitude = parseFloat(abb[0][1]);
      let longitude = parseFloat(abb[0][0]);
      let latitude1 = parseFloat(abb[abb.length - 1][1]);
      let longitude1 = parseFloat( abb[abb.length - 1][0]);
      
      this.marker = new AMap.Marker({
        map: this.map,
        position: [longitude, latitude],
        icon: new AMap.Icon({
          size: new AMap.Size(25, 38),  // 图标大小
          image: "https://lxnapi.ccttiot.com/bike/img/static/u06paUGiHLvL08Pw7BGr",
          imageSize: new AMap.Size(25, 38)  // 图标图片大小
        }),
        offset: new AMap.Pixel(-12.5, -19.5),
      });
      this.marker = new AMap.Marker({
        map: this.map,
        position: [longitude1, latitude1],
        icon: new AMap.Icon({
          size: new AMap.Size(25, 38),  // 图标大小
          image: "https://lxnapi.ccttiot.com/bike/img/static/uwpAj9vYtPRmhtTOtflx",
          imageSize: new AMap.Size(25, 38)  // 图标图片大小
        }),
        offset: new AMap.Pixel(-12.5, -19.5),
      });
      // console.log(latitude,longitude,'longitudelongitudelongitude');
      let line = this.line;
      this.marker = new AMap.Marker({
        map: this.map,
        position: line[0],
        icon: new AMap.Icon({
          image: globalConfig.icon.trajectory,
          size: new AMap.Size(25, 39), // 设置图标的宽高
          imageSize: new AMap.Size(25, 39) // 设置图标的实际显示尺寸
        }),
        offset: new AMap.Pixel(-12.5, -19.5),
        autoRotation: true,
        angle: 90
      });
      // 绘制轨迹
      let polyline = new AMap.Polyline({
        map: this.map,
        path: line,
        showDir: true,
        strokeColor: "#28F", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      });

      let passedPolyline = new AMap.Polyline({
        map: this.map,
        // path: this.lineArr,
        strokeColor: "#AF5", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      });

      this.marker.on("moving", function (e) {
        passedPolyline.setPath(e.passedPath);
      });

      this.map.setFitView();
    },
    startAnimation() {
      this.marker.moveAlong(this.line, {
        // 每一段的时长
        duration: 200,//可根据实际采集时间间隔设置
      });
    },
    pauseAnimation() {
      this.marker.pauseMove();
    },
    resumeAnimation() {
      this.marker.resumeMove();
    },
    stopAnimation() {
      this.marker.stopMove();
    }
  },
};
</script>
<style scoped lang="scss">
.place-search-map {
  position: relative;
  overflow: hidden;

  #container {
    height: 1000px;
    width: 100%;
  }

  .input-card .btn {
    margin-right: 1.2rem;
    width: 9rem;
  }

  .input-card .btn:last-child {
    margin-right: 0;
  }

  .btn {
    display: inline-block;
    font-weight: 400;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    border: 1px solid transparent;
    transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
    background-color: transparent;
    background-image: none;
    color: #25A5F7;
    border-color: #25A5F7;
    padding: .25rem .5rem;
    line-height: 1.5;
    border-radius: 1rem;
    -webkit-appearance: button;
    cursor: pointer;
  }

  .input-item {
    position: relative;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    -ms-flex-align: center;
    align-items: center;
    width: 100%;
    height: 3rem;
  }

  .input-card {
    position: absolute !important;
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border-radius: .25rem;
    width: 22rem;
    border-width: 0;
    border-radius: 0.4rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
    position: fixed;
    bottom: 1rem;
    right: 1rem;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 0.75rem 1.25rem;
  }
}
</style>
