import {Component, Input, OnInit} from '@angular/core';
import * as Parse from "parse";
import * as  AMapLoader from '@amap/amap-jsapi-loader';


(window as any)._AMapSecurityConfig = {
  securityJsCode: '32aa3f4ab0fa0061de03edd4eafdd50a',
}

@Component({
  selector: 'app-page-plan-route',
  templateUrl: './page-plan-route.component.html',
  styleUrls: ['./page-plan-route.component.scss']
})
export class PagePlanRouteComponent implements OnInit {
  AMap: any
  map: any // AMap.Map
  placeList: Array<any> = []
  currentTab: string = "place"

  constructor() {
    this.addNewPlace()
    this.currentTab = "plan"
  }

  addNewPlace() {
    if (this.placeList?.length >= 0) {
      this.placeList.push({
        name: "秋水广场",
        address: "南昌市秋水广场",
        location: new Parse.GeoPoint({latitude: 28.682634, longitude: 115.86273})
      })
    } else {
      this.placeList.push({
        name: "八一广场",
        address: "南昌市八一广场",
        location: new Parse.GeoPoint({latitude: 28.673856, longitude: 115.904477})
      })
    }

  }

  ngAfterViewInit(): void {
  }

  async initMap() {
    await this.createMap()
    this.goAndMarkPlace(this.placeList[0])
  }

  async createMap() {
    this.AMap = await AMapLoader.load({
      key: "473b52010df7d3a32db0a2f5db245c8e",       // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0",                 // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    })
    this.map = new this.AMap.Map('container-plan');
  }

  goAndMarkPlace(place: any) {
    this.map.setCenter([place.location.latitude, place.location.longitude])
    this.map.setZoom(18)
    if (place.marker) return
    place.marker = new this.AMap.Marker({
      position: [place.location.latitude, place.location.longitude]
    })
    this.map.add(place.marker);
  }

  clearMark(place: any) {
    place?.marker?.remove()
  }

  /**
   * 路线规划 地点1 => 地点2
   */
  planRoute(p1: any, p2: any) {
    let transfer;
    this.map.plugin(["AMap.Transfer"], () => { //加载公交换乘插件
      let transOptions = {
        map: this.map,
        city: '南昌市',
        panel: 'panel',
        // cityd:'经开区',
        policy: this.AMap.TransferPolicy.LEAST_TIME
      };
      //构造公交换乘类
      transfer = new this.AMap.Transfer(transOptions);
      //根据起、终点坐标查询公交换乘路线
      let p1pos = new this.AMap.LngLat(p1.location.longitude, p1.location.latitude)
      let p2pos = new this.AMap.LngLat(p2.location.longitude, p2.location.latitude)
      transfer.search(p1pos, p2pos, (status: string, result: any) => {
        // result即是对应的公交路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_TransferResult
        if (status === 'complete') {
          console.log('绘制公交路线完成：')
          console.log(result)
        } else {
          console.error('公交路线数据查询失败' + result)
        }
      });
    });


  }

  async createPlan() {
    await this.initMap();
    this.planRoute(this.placeList[0], this.placeList[1]);
  }

  ngOnInit(): void {
  }


  // async createMap() {
  //   try {
  //     this.AMap = await AMapLoader.load({
  //       "key": "473b52010df7d3a32db0a2f5db245c8e",
  //       "version": "2.0",
  //       "plugins": [],
  //     });
  //
  //     this.map = new this.AMap.Map('AMap.Driving', {
  //       resizeEnable: true,
  //       viewMode: "3D",
  //       zoom: 13,
  //       zooms: [4, 18],
  //       center: [116.397428, 39.90923],
  //       layers: [],
  //     });
  //
  //     this.AMap.plugin(['AMap.ToolBar', 'AMap.Driving'], () => {
  //       var toolbar: any = new this.AMap.ToolBar();
  //       this.map.addControl(toolbar);
  //
  //       var driving = new this.AMap.Driving({
  //         map: this.map,
  //         panel: "panel",
  //       });
  //       console.log(this.keyword_destination)
  //       console.log(this.city_destination)
  //       console.log(this.startLngLat)
  //
  //       driving.search(this.startLngLat, (status: string, result: any) => {
  //         if (status === 'complete') {
  //           console.log(1);
  //         } else {
  //           console.log(result);
  //         }
  //       });
  //     });
  //   } catch (error) {
  //     console.log(error);
  //   }
  // }
  //
  //
  // async goCurrentCenter() {
  //   this.AMap = await AMapLoader.load({
  //     "key": "473b52010df7d3a32db0a2f5db245c8e",
  //     "version": "2.0",
  //     "plugins": [],
  //   });
  //   this.AMap.plugin(["AMap.Geolocation"], () => {
  //     // 创建定位对象
  //     let geolocation = new this.AMap.Geolocation({
  //       enableHighAccuracy: true, // 是否使用高精度定位，默认为true
  //       timeout: 10000, // 超过10秒后停止定位，默认：无穷大
  //       maximumAge: 0, // 定位结果缓存0毫秒，默认：0
  //       convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
  //       showButton: true, // 显示定位按钮，默认：true
  //       buttonPosition: 'RB', // 定位按钮停靠位置，默认：'LB'，左下角
  //       buttonOffset: new this.AMap.Pixel(10, 10), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
  //       showMarker: false, // 定位成功后在定位到的位置显示点标记，默认：true
  //       showCircle: false, // 定位成功后用圆圈表示定位精度范围，默认：true
  //       panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
  //       zoomToAccuracy: false // 定位成功后将定位精度范围显示在地图上，默认：true
  //     });
  //     this.map = new this.AMap.Map('container');
  //     // 添加定位插件
  //     this.map.addControl(geolocation);
  //
  //     // 获取当前位置信息
  //     geolocation.getCurrentPosition((status: string, result: any) => {
  //       if (status == 'complete') {
  //         // 定位成功
  //         this.startLngLat.push(result.position.getLng(), result.position.getLat())
  //         console.log('当前位置经度：' + result.position.getLng());
  //
  //         console.log('当前位置纬度：' + result.position.getLat());
  //       } else {
  //         // 定位失败
  //         console.log('定位失败：' + result.message);
  //       }
  //     });
  //   })
  // }

}

