import {Component} 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-comp-plan-route',
  templateUrl: './comp-plan-route.component.html',
  styleUrls: ['./comp-plan-route.component.scss']
})
export class CompPlanRouteComponent {
  AMap: any;
  map: any; // AMap.Map
  placeList: Array<any> = [];
  current_pos_lng: any = '';
  current_pos_lat: any = '';
  des_pos_lng: any = '';
  des_pos_lat: any = '';
  driving: any;
  transfer: any;
  riding: any;

  city: string = "";
  num_select: any = 0
  options = ['驾车', '骑行', '公交'];

  handleIndexChange(e: number): void {
    console.log(typeof e);

    if (this.des_pos_lng) {
      if (e == 0) {
        setTimeout(() => {
          this.plan();
        }, 1000);
      } else if (e == 1) {
        setTimeout(() => {
          this.plan_driver();
        }, 1000);
      } else if (e == 2) {
        setTimeout(() => {
          this.plan_bus();
        }, 1000);
      }
    }
  }


  async initMap() {
    this.createMap();
    await this.getSearchPos();
    await this.getCurrentPos();
  }

  constructor() {
    this.initMap();
  }

  createMap() {
    this.AMap = AMapLoader.load({
      key: "473b52010df7d3a32db0a2f5db245c8e",
      version: "2.0",
    });
  }

  async getSearchPos() {
    const AMap = await this.AMap;
    var autoOptions_d = {
      input: "tipinput_d",

    };
    var autoOptions_s = {
      input: "tipinput_s",
    };
    AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], () => {
      var auto_s = new AMap.AutoComplete(autoOptions_s);
      var auto_d = new AMap.AutoComplete(autoOptions_d);
      //起始点监听
      auto_s.on("select", (e: any) => {
        console.log(e.poi.location);
        this.des_pos_lng = e.poi.location.lng;
        this.des_pos_lat = e.poi.location.lat;

        console.log(e.poi)
        console.log()
        let district = e.poi.district;
        let provinceIndex = district.indexOf('省');
        const cityIndex = district.indexOf('市')
        const subStr = district.substring(provinceIndex + 1, cityIndex + 1);
        this.city = subStr;
        console.log(subStr)
        this.current_pos_lng = e.poi.location.lng;
        this.current_pos_lat = e.poi.location.lat;

        // if (this.num_select == 0) {
        //   setTimeout(() => {
        //     this.plan();
        //   }, 1000);
        // } else if (this.num_select == 1) {
        //   setTimeout(() => {
        //     this.plan_driver();
        //   }, 1000);
        // } else if (this.num_select == 2) {
        //   setTimeout(() => {
        //     this.plan_bus();
        //   }, 1000);
        // }

      });
      //终点监听
      auto_d.on("select", (e: any) => {
        console.log(e.poi.location);
        this.des_pos_lng = e.poi.location.lng;
        this.des_pos_lat = e.poi.location.lat;

        console.log(e.poi)
        console.log()
        let district = e.poi.district;
        let provinceIndex = district.indexOf('省');
        const cityIndex = district.indexOf('市')
        const subStr = district.substring(provinceIndex + 1, cityIndex + 1);
        this.city = subStr;
        console.log(subStr)
        if (this.num_select == 0) {
          setTimeout(() => {
            this.plan();
          }, 1000);
        } else if (this.num_select == 1) {
          setTimeout(() => {
            this.plan_driver();
          }, 1000);
        } else if (this.num_select == 2) {
          setTimeout(() => {
            this.plan_bus();
          }, 1000);
        }

      });


    });
  }

  async getCurrentPos() {
    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秒后停止定位，默认：5s
        position: 'RB',    //定位按钮的停靠位置
        offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
        zoom: 13,
        showCircle: false,
        markerOptions: {//自定义定位点样式，同Marker的Options
          'offset': this.AMap.Pixel(-18, -36),
          'content': '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
        }
      });
      this.map = new this.AMap.Map('container');
      // 添加定位插件
      this.map.addControl(geolocation);


      // 获取当前位置信息
      geolocation.getCurrentPosition((status: string, result: any) => {
        if (status == 'complete') {
          // 定位成功
          this.current_pos_lng = result.position.lng;
          this.current_pos_lat = result.position.lat;
        } else {
          // 定位失败
          console.log('定位失败：' + result.message);
        }
      });
    })
  }

  plan() {
    // this.map = new this.AMap.Map("container", {
    //   resizeEnable: true,
    //   center: [116.397428, 39.90923],
    //   zoom: 13
    // });
    this.AMap.plugin('AMap.Driving', () => {
        var driving = new this.AMap.Driving({
          map: this.map,
          panel: "panel",
          policy: [0, 1, 2],

        });
        console.log(this.current_pos_lat)
        console.log(this.current_pos_lng);
        console.log(this.des_pos_lat)
        console.log(this.des_pos_lng)

        var startLngLat = [this.current_pos_lng, this.current_pos_lat];
        var endLngLat = [this.des_pos_lng, this.des_pos_lat];
        console.log(endLngLat);
        console.log(startLngLat);
        this.driving = driving
        this.clear_route(this.driving, this.transfer, this.riding)
        driving.search(startLngLat, endLngLat, (status: string, result: any) => {
          if (status === 'complete') {
            console.log("路线加载成功")
            console.log(result.routes)

          } else {
            console.log('获取驾车数据失败：' + result);
          }
        });
      }
    );
  }

  plan_driver() {
    // this.map = this.AMap.Map("container", {
    //   resizeEnable: true,
    //   center: [116.397428, 39.90923],
    //   zoom: 13
    // });
    this.AMap.plugin('AMap.Riding', () => {
      var riding = new this.AMap.Riding({
        map: this.map,
        panel: "panel",
        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
        policy: [0, 1, 2],
      });

      this.riding = riding
      this.clear_route(this.driving, this.transfer, this.riding)
      var startLngLat = [this.current_pos_lng, this.current_pos_lat];
      var endLngLat = [this.des_pos_lng, this.des_pos_lat];
      console.log(endLngLat);
      console.log(startLngLat);
      riding.search(startLngLat, endLngLat, (status: string, result: any) => {
        if (status === 'complete') {
          console.log('绘制驾车路线完成');
        } else {
          console.log('获取驾车数据失败：' + result);
        }
      });
    });

  }

  plan_bus() {
    // let that = this;
    // console.log(that.city)
    // console.log(1)
    // this.map = this.AMap.Map("container", {
    //   resizeEnable: true,
    //   center: [116.397428, 39.90923],//地图中心点
    //   zoom: 13, //地图显示的缩放级别
    //   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.AMap.plugin('AMap.Transfer', () => {
      console.log(this.city)
      let transOptions = new this.AMap.Transfer({
        map: this.map,
        panel: "panel",
        city: '南昌市',
      });
      let transfer = new this.AMap.Transfer(transOptions)

      let startLngLat = [this.current_pos_lng, this.current_pos_lat];
      let endLngLat = [this.des_pos_lng, this.des_pos_lat];
      console.log(endLngLat);
      console.log(startLngLat);
      this.transfer = transfer;
      this.clear_route(this.driving, this.transfer, this.riding)
      transfer.search(startLngLat, endLngLat, (status: string, result: any) => {
        if (status === 'complete') {
          console.log('绘制驾车路线完成');
        } else {
          console.log('获取驾车数据失败：' + result);
        }
      });
    });
  }

  clear_route(route1: any, route2: any, route3: any
  ) {
    if (route1) {
      route1.clear();
    }
    if (route2) {
      route2.clear();
    }
    if (route3) {
      route3.clear()
    }
  }
}
