import {Component, Input, Output, EventEmitter, ViewChild, AfterViewInit} from '@angular/core';
import * as Parse from "parse";
// 弹窗依赖
import {IonModal, ModalController} from '@ionic/angular';
import {ComponentRef} from '@angular/core';

import {OverlayEventDetail} from '@ionic/core';

// 高德依赖
import * as AMapLoader from "@amap/amap-jsapi-loader"

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

@Component({
  selector: 'app-comp-poi-picker',
  templateUrl: './comp-poi-picker.component.html',
  styleUrls: ['./comp-poi-picker.component.scss']
})
export class CompPoiPickerComponent implements AfterViewInit {


  @Input("address") _address?: string // 详细地址
  get address() {
    return this._address
  }

  set address(v) {
    this._address = v;
    this.addressChange.emit(v)
  }

  @Output() addressChange: EventEmitter<string> = new EventEmitter()

  @Input("location") _location?: Parse.GeoPoint // 经纬度数组
  get location() {
    return this._location
  }

  set location(v) {
    this._location = v;
    this.locationChange.emit(v)
  }

  @Output() locationChange: EventEmitter<Parse.GeoPoint> = new EventEmitter()

  constructor(private modalController: ModalController) {
  }

  /**
   * 弹窗效果区域
   */
  isModalOpen: boolean = false;
  @ViewChild(IonModal, {static: false}) modal: IonModal | undefined;

  cancel() {
    this.isModalOpen = false;
    this.modal?.dismiss(null, 'cancel');
  }

  confirm() {
    this.isModalOpen = false;
    this.modal?.dismiss(this.address, 'confirm');
  }

  onWillDismiss(event: Event) {
    const ev = event as CustomEvent<OverlayEventDetail<string>>;
    if (ev.detail.role === 'confirm') {
      console.log("确认")
    }
  }

  openModal() {
    this.isModalOpen = true
    this.initMap()
  }

  /**
   * 高德地图插件区域
   */
  AMap: any;
  map: any;

  async ngAfterViewInit() {
    const modalElement = await this.modalController.getTop();
    const componentProps = modalElement?.componentProps;
    const modal = componentProps?.['modal'] as IonModal;
  }

  initMap() {
    this.createMap();
  }

  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');
    this.goCurrentCenter()
  }

  goCurrentCenter() {
    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.addControl(geolocation);

      // 获取当前位置信息
      geolocation.getCurrentPosition(<PositionCallback>function (status: any, result: any) {
        if (status === 'complete') {
          // 定位成功
          console.log('当前位置经度：' + result.position.getLng());
          console.log('当前位置纬度：' + result.position.getLat());
        } else {
          // 定位失败
          console.log('定位失败：' + result.message);
        }
      });
    })
  }

  searchByAddress() {
    this.AMap.plugin(["AMap.PlaceSearch"], () => {
      //构造地点查询类
      let placeSearch = new this.AMap.PlaceSearch({
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码
        // city: "010", // 兴趣点城市
        // citylimit: true,  //是否强制限制在设置的城市内搜索
        map: this.map, // 展现结果的地图实例
        panel: "panel", // 结果列表将在此容器中进行展示。
        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      });
      // 预设地点选择后事件
      placeSearch.on('selectChanged', (event: any) => {
        // 在这里处理选择的点的具体值
        this.location = new Parse.GeoPoint({
          latitude: event.selected.data.location.lat,
          longitude: event.selected.data.location.lng
        })
      })
      // this.AMap.event.addListener(placeSearch, 'selectChanged', (event) => {
      //   // 在这里处理选择的点的具体值
      //   console.log(event);
      // });

      // 关键字查询
      placeSearch.search(this.address);
    });
  }
}
