import FollowVillageApi from "@/api/light/FollowVillageApi";
import { useRequireLogin } from "@/common/composeabe/RequireLogin";
import { useVillageStore } from "@/store/village";
import { computed } from "vue";
import { toast, confirm } from "@/components/dialog/CommonRoot";

export function useFollow() {

  const { requireLogin } = useRequireLogin();
  const villageStore = useVillageStore();
  const isFollowed = computed(() => {
    return villageStore.myFollowVillages.some(p => p.id === villageStore.currentVillage?.id);
  });

  async function onFollow() {
    if (!villageStore.currentVillage) 
      return;
    requireLogin(async () => {
      try {
        await FollowVillageApi.followVillage(villageStore.currentVillage!.id);
        villageStore.myFollowVillages.push(villageStore.currentVillage!);
        toast('关注成功');
      } catch {
        toast('关注失败');
      }
    }, '登录后才能关注村庄哦');
  }
  function onUnFollow() {
    if (!villageStore.currentVillage) return;
    confirm({
      title: '取消关注',
      content: '确定取消关注该村庄吗？',
      confirmText: '取消关注',
      cancelText: '取消',
    }).then(async (res) => {
      if (res) {
        try { 
          await FollowVillageApi.unfollowVillage(villageStore.currentVillage!.id);
          villageStore.myFollowVillages = villageStore.myFollowVillages.filter(p => p.id !== villageStore.currentVillage!.id);
          toast('取消关注成功');
        } catch {
          toast('取消关注失败');
        }
      }
    });
  }

  return {
    isFollowed,
    onFollow,
    onUnFollow,
  };
}