import { Injectable } from '@angular/core';
import { Observable, Subject, throwError } from 'rxjs';
import AMapLoader from '@amap/amap-jsapi-loader';
import { amapConf } from '@conf/amap.config';
declare var AMap: any;

const CONFIG = amapConf;
@Injectable({
  providedIn: 'root'
})
export class AmapService {
  constructor() {}
  public length = 0;
  public time = 0;

  sub = new Subject<any>();
  currentSub = new Subject<any>();

  //计算路径驾车最优路线的长度与所需时间
  drivingCompute(starts: any[], ends: any[]): Observable<any> {
    AMap.plugin('AMap.Driving', () => {
      let driving = new AMap.Driving({
        // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
        policy: AMap.DrivingPolicy.LEAST_TIME
      });
      const points = starts.concat(ends).map(item => {
        return { keyword: item.address, city: item.city };
      });
      driving.search(points, (status: any, result: any) => {
        const repData = { distance: (result.routes[0].distance / 1000).toFixed(2), time: (result.routes[0].time / 60 / 60).toFixed(2) };
        this.sub.next(repData);
      });
    });
    return this.sub;
  }

  getCurrentPosition(): Observable<any> {
    AMapLoader.load({
      key: CONFIG.key,
      version: CONFIG.version,
      plugins: [
        // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        'AMap.PathSimplifier'
      ],
      AMapUI: {
        version: CONFIG.AMapUIVersion,
        plugins: ['misc/PathSimplifier'] // 需要加载的 AMapUI ui插件
      }
    })
      .then(AMap => {
        AMap.plugin('AMap.Geolocation', () => {
          let driving = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 10000, //超过10秒后停止定位，默认：5s
            buttonPosition: 'RB', //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true //定位成功后是否自动调整地图视野到定位点
          });
          driving.getCurrentPosition((status: string, result: any) => {
            if (status == 'complete') {
              this.currentSub.next(result);
            } else {
              console.log('定位获取失败');
            }
          });
        });
      })
      .catch(e => {
        throwError(e);
      });

    return this.currentSub;
  }
}
