import { reactive } from "vue";
import { useMainStore } from "@/store/index";

export function useLocation() {
  const { storeState, setLocation } = useMainStore();

  const locationState = reactive({
    showGetLocation: false,
    latitude: 0,
    longitude: 0
  });

  const getLocation = () => {
    return new Promise((resolve) => {
      // 1️⃣ 优先使用 store 里的定位
      if (storeState.location?.latitude && storeState.location?.longitude) {
        locationState.latitude = storeState.location.latitude;
        locationState.longitude = storeState.location.longitude;
        resolve(true);
        return;
      }

      // 2️⃣ 本地已经有定位
      if (locationState.latitude && locationState.longitude) {
        resolve(true);
        return;
      }
     
      // 3️⃣ 没有定位才请求
      SFUIP.getLocation().then(res => {
        console.log(res,"SFUIP.getLocation");
        if (!res.success) {
          resolve(false);
          return;
        }

        const { latitude, longitude } = res.data || {};

        if (latitude && longitude) {
          locationState.latitude = latitude;
          locationState.longitude = longitude;
          locationState.showGetLocation = false;

          setLocation({ latitude, longitude });
          resolve(true);
        } else {
          resolve(false);
        }
      });

    });
  };

  return { locationState, getLocation };
}