import LightVillageApi from "@/api/light/LightVillageApi";
import MapApi from "@/api/map/MapApi";
import TenMapApi from "@/api/map/TenMapApi";
import { useVillageStore } from "@/store/village";
import { ref } from "vue";

export function useGetCurrentLocation(
  options: {
    onCityChanged?: (city: string) => void;
  }
) {

  const { onCityChanged } = options;
  
  const villageStore = useVillageStore();
  const currentLonlat = ref<{ longitude: number, latitude: number }>({ 
    longitude: 0, 
    latitude: 0,
  });


  async function getCurrentExactLocation() {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        success: async (res) => {
          currentLonlat.value = {
            longitude: res.longitude,
            latitude: res.latitude,
          };
          villageStore.setCurrentLonlat(currentLonlat.value);
          const address = (await TenMapApi.geocoder(`${res.latitude},${res.longitude}`));
          villageStore.setCurrentRegion(address?.address_component?.city || '');
          onCityChanged?.(address?.address_component?.city || '');
          resolve(currentLonlat.value);
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  }
  async function getCurrentFuzzyLocation() {
    const res = await LightVillageApi.getIpAddress();
    currentLonlat.value = {
      longitude: Number(res.point.x),
      latitude: Number(res.point.y),
    };
    if (isNaN(currentLonlat.value.longitude) || isNaN(currentLonlat.value.latitude))
      throw new Error('获取模糊定位失败');
    villageStore.setCurrentLonlat(currentLonlat.value);
    villageStore.setCurrentRegion(res.address_detail.district);
    onCityChanged?.(res.address_detail.city);
  }

  async function setCurrentLocationWithCity(city: string) {
    const res = (await MapApi.simpleGetRegion(city)).requireData();
    currentLonlat.value = {
      longitude: Number(res.center.split(',')[0]),
      latitude: Number(res.center.split(',')[1]),
    };
    console.log('currentLonlat.value', currentLonlat.value);
    villageStore.setCurrentLonlat(currentLonlat.value);  
    villageStore.setCurrentRegion(res.name);
    onCityChanged?.(city);
  }

  return {
    currentLonlat,
    getCurrentExactLocation,
    getCurrentFuzzyLocation,
    setCurrentLocationWithCity,
  };
}