<template>
  <CommonTopBanner title="志愿者排名">
    <SimplePageContentLoader :loader="villageUserRankListLoader">
      <VillageUserRankList 
        :list="villageUserRankListFirst3" 
        @goDetails="goDetails" 
      />
      <FlexCol gap="gap.lg" padding="space.md">
        <RankVolunteerItem
          v-for="(item, index) in villageUserRankListAfter3"
          :key="item.id"
          :id="item.id"
          :image="item.image"
          :rank="index + 4"
          :title="item.title"
          :score="item.score"
          :isAdmin="item.isAdmin"
          @click="goDetails(item)"
        />
      </FlexCol>
    </SimplePageContentLoader>
  </CommonTopBanner>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { ArrayUtils } from '@imengyu/imengyu-utils';
import { navTo } from '@/components/utils/PageAction';
import FlexCol from '@/components/layout/FlexCol.vue';
import VillageUserRankList from '../../components/VillageUserRankList.vue';
import LightVillageApi from '@/api/light/LightVillageApi';
import SimplePageContentLoader from '@/components/loader/SimplePageContentLoader.vue';
import CommonTopBanner from '@/common/components/CommonTopBanner.vue';
import RankVolunteerItem from './components/RankVolunteerItem.vue';

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

const villageUserRankListLoader = useSimpleDataLoader(async () => {
  const res = (await LightVillageApi.getVolunteerRankList({ 
    region_id: querys.value.regionId || undefined, 
    village_id: querys.value.villageId || undefined,
    num: 30,
  }))
    .map((item, i) => ({
      id: item.id,
      image: item.image ?? '',
      title: item.name,
      rank: i + 1,
      score: item.points,
      isAdmin: item.type === 'admin',
    }));

  if (res.length >= 3) {
    //移动第一名到中间
    const first = res[0];
    ArrayUtils.removeAt(res, 0);
    ArrayUtils.insert(res, 1, first);
  }
  return res
});
const villageUserRankListFirst3 = computed(() => {
  return villageUserRankListLoader.content.value?.slice(0, 3) ?? [];
});
const villageUserRankListAfter3 = computed(() => {
  return villageUserRankListLoader.content.value?.slice(3) ?? [];
});

function goDetails(item: {
  id: number;
  image: string;
  title: string;
  rank: number;
  score: number;
}) {
  console.log(item);
  
  navTo('../volunteer/detail', { id: item.id });
}

</script>