import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { VillageListItem } from '@/api/light/LightVillageApi';
import FollowVillageApi from '@/api/light/FollowVillageApi';
import LightVillageApi from '@/api/light/LightVillageApi';

/** 
 * 村庄各页面共享 数据
 */
export const useVillageStore = defineStore('village', () => {
  
  const currentVillage = ref<VillageListItem | null>(null);
  const currentLonlat = ref<{ longitude: number, latitude: number } | null>(null);
  const currentRegion = ref<string | null>(null);
  const myFollowVillages = ref<VillageListItem[]>([]);
  const myJoinedVillages = ref<VillageListItem[]>([]);
  const shareFromVillageUserId = ref(0);

  async function setCurrentVillage(village: VillageListItem) {
    currentVillage.value = await LightVillageApi.getVillageDetails(village.id);
    console.log('currentVillage', currentVillage.value);
    uni.setStorageSync('currentVillage', village.id);
  }
  function loadCurrentVillage() {
    return uni.getStorageSync('currentVillage') as number|unknown;
  }
  function setCurrentLonlat(lonlat: { longitude: number, latitude: number }) {
    currentLonlat.value = lonlat;
  }
  function setCurrentRegion(region: string) {
    currentRegion.value = region;
  }
  async function loadMyFollowVillages() {
    const villages = await FollowVillageApi.getFollowVillageList();
    myFollowVillages.value = villages.list;
  }
  function setMyJoinedVillages(villages: VillageListItem[]) {
    myJoinedVillages.value = villages;
  }
  function setShareFromVillageUserId(userId: number) {
    shareFromVillageUserId.value = userId;
  }

  return { 
    currentVillage,
    currentLonlat,
    currentRegion,
    myFollowVillages,
    myJoinedVillages,
    shareFromVillageUserId,
    loadCurrentVillage,
    setCurrentVillage,
    setCurrentLonlat,
    setCurrentRegion,
    loadMyFollowVillages,
    setMyJoinedVillages,
    setShareFromVillageUserId,
  }
})
