import { hLoading, jsonp, sLoading } from "./util";

const mapsInfo = reactive({
  lat: 0, // 纬度
  lng: 0, // 经度
  addr: "", // 地址
});

const windows: any = window;

const useQqMaps = () => {
  const geolocation = new windows.qq.maps.Geolocation(
    "3M5BZ-SFCRJ-AHSF7-XRA5Q-Y6NIJ-DXBH4",
    "XBRLPX"
  );

  const initQqMaps = () => {
    // 获取当前所在地理位置
    sLoading();
    // console.log(geolocation, "geolocation");
    geolocation.getLocation(showPosition, showErr);
  };

  // 监听位置信息的改变
  const watchPosition = () => {
    geolocation.watchPosition(updatePosition);
  };

  // 清除监听
  const clearWatch = () => {
    geolocation.clearWatch();
  };

  const showPosition = (position: any) => {
    // console.log(position, "hLoading");
    let url = "https://apis.map.qq.com/ws/geocoder/v1/";
    mapsInfo.lat = position.lat;
    mapsInfo.lng = position.lng;
    jsonp(url, {
      key: "3M5BZ-SFCRJ-AHSF7-XRA5Q-Y6NIJ-DXBH4",
      output: "jsonp",
      // 需要传入的参数
      location: position.lat + "," + position.lng,
      get_poi: 1,
    }).then((res: any) => {
      // console.log(res, "hLoading");
      hLoading();
      mapsInfo.addr = res.result.address;
      // console.log(mapsInfo)
    });
  };

  const updatePosition = (data: any) => {
    console.log(data);
  };
  const showErr = () => {};

  // 计算距离
  const calculateDistance = (
    lat1: number,
    lon1: number,
    lat2: number,
    lon2: number
  ) => {
    const point1 = new windows.qq.maps.LatLng(lat1, lon1);
    const point2 = new windows.qq.maps.LatLng(lat2, lon2);
    // 使用 computeDistanceBetween 方法计算距离
    var distance = windows.qq.maps.geometry.spherical.computeDistanceBetween(
      point1,
      point2
    );

    return distance; // 返回距离，单位为米
  };
  return {
    initQqMaps,
    watchPosition,
    clearWatch,
    calculateDistance,
    mapsInfo,
  };
};

export default useQqMaps;
