import {Component, Input, OnInit} from '@angular/core';

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 {
  @Input() keyword_destination: string
  @Input() city_destination: string

  AMap: any;
  map: any;
  location_pos: any

  constructor() {
    this.keyword_destination = '';
    this.city_destination = ''
  }

  ngOnInit() {
    this.getCurrentCity();
    this.createMap()
  }

  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: [],
        policy: this.AMap.DrivingPolicy.LEAST_TIME
      });

      this.AMap.plugin(['AMap.ToolBar', 'AMap.Driving'], () => {
        var toolbar = 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.location_pos)

        driving.search([], (status: string, result: any) => {
          if (status === 'complete') {
            console.log(1);
          } else {
            console.log(result);
          }
        });
      });
    } catch (error) {
      console.log(error);
    }
  }

  async getCurrentCity() {
    this.AMap = await AMapLoader.load({
      "key": "473b52010df7d3a32db0a2f5db245c8e",
      "version": "2.0",
      "plugins": [],
    });
    this.map = new this.AMap.Map('container', {
      resizeEnable: true
    })
    this.AMap.plugin('AMap.Geolocation', async () => {
      var geolocation = new this.AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        buttonPosition: 'RB',
        buttonOffset: new this.AMap.Pixel(10, 20),
        zoomToAccuracy: true,
      });
      this.map.addControl(geolocation);
      await geolocation.getCurrentPosition(<PositionCallback>(status: any, result: any) => {
          if (status === 'complete') {
            console.log(result[0].formattedAddress)
            console.log(result)
            this.location_pos = result.position;
          } else {
            alert(result)
          }
        }
      )
      ;
    });

  }

}

