<template>
  <CommonTopBanner title="村社排名">
    <SimplePageContentLoader :loader="villageRankListLoader">
      <FlexCol gap="gap.lg" padding="space.md">
        <RankVillageItem
          v-for="item in villageRankListLoader.content.value"
          :key="item.id"
          :id="item.id"
          :image="item.image"
          :rank="item.rank"
          :title="item.title"
          :points="item.points"
          @click="handleGoDetails(item)"
        />
      </FlexCol>
    </SimplePageContentLoader>
  </CommonTopBanner>
</template>

<script setup lang="ts">
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { useVillageStore } from '@/store/village';
import { backAndCallOnPageBack, navTo } from '@/components/utils/PageAction';
import FlexCol from '@/components/layout/FlexCol.vue';
import LightVillageApi from '@/api/light/LightVillageApi';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import SimplePageContentLoader from '@/components/loader/SimplePageContentLoader.vue';
import RankVillageItem from './components/RankVillageItem.vue';

const { querys } = useLoadQuerys({
  regionId: 0,
}, () => {
  villageRankListLoader.reload();
});

const villageRankListLoader = useSimpleDataLoader(async () => {
  const res = await LightVillageApi.getVillageRankList({ 
    region_id: querys.value.regionId || undefined, 
    num: 30
  });
  return res.map((item, i) => ({
    image: item.image ?? '',
    title: item.name,
    rank: i + 1,
    id: item.id,
    points: item.points,
  }));
});

const villageStore = useVillageStore();

async function handleGoDetails(item: { id: number }) {
  const details = await LightVillageApi.getVillageDetails(item.id);
  villageStore.setCurrentVillage(details);
  await waitTimeOut(100);
  backAndCallOnPageBack('villageRank', {
    type: 'goVillage'
  })
}
</script>