<template>
  <FlexCol>
    <FlexCol :padding="30">
      <HomeLargeTitle title="挖掘" />
      <ImageSwiper
        :images="appConfiguration?.banners.dig"
        width="100%"
        :height="400"
        radius="radius.md"
        :innerStyle="{
          border: '1px solid #fff',
          overflow: 'hidden',
        }"
      />
      <HomeTitle title="我的村社" />
      <RequireLogin unLoginMessage="欢迎您成为志愿者！在这之前您需要登录或者注册完善基础信息后才能投稿和查看我认领的村社哦">
        <FlexCol 
          v-if="notVolunteerError"
          gap="gap.lg" 
          padding="padding.md"
          center
        >
          <Image src="https://xy.wenlvti.net/app_static/images/home/BadgeNew.png" :width="320" mode="widthFix" />
          <CommonDivider />
          <Text 
            textAlign="center"
            text="认领属于你的村庄，参与建设家乡 或者先随便看看，了解更多乡村故事" 
            fontConfig="contentSpeicalText" 
          />
          <FlexRow justify="space-around" gap="gap.md">
            <FrameButton primary text="去认领村庄" @click="navTo('/pages/home/light/submit-map', {
              city: currentCity,
            })" width="220rpx" />
          </FlexRow>
        </FlexCol>
        <SimplePageContentLoader
          v-else
          :loader="villageListLoader"
          :showEmpty="villageListLoader.content.value?.length == 0"
          :emptyView="{
            text: '您点亮的村社正在审核中，审核通过后您可以查看和管理',
            button: false,
          }"
        >
          <FlexCol :gap="10">
            <FlexRow 
              v-for="item in villageListLoader.content.value"
              :key="item.id"
              radius="radius.md"
              :padding="20"
              align="center"
              justify="space-between"
              :innerStyle="{
                border: '1px solid #fff',
              }"
            >
              <FlexRow align="center" :gap="20">
                <Image 
                  mode="aspectFill"
                  :src="item.image" 
                  round
                  :width="80"
                  :height="80"
                />
                <H3>{{ item.villageName }}</H3>
              </FlexRow>
              <ButtonGroup direction="row" align="center" :gap="0">
                <BubbleBox :items="[
                  {
                    icon: 'edit-filling',
                    text: '管理',
                    onClick: () => goManagePage(item),
                  },
                  {
                    icon: 'edit-filling',
                    text: '采编',
                    onClick: () => goSubmitDigPage(item),
                  },
                ]">
                  <Button v-if="authStore.isAdmin" icon="edit-filling" size="small">采编/管理</Button>
                </BubbleBox>
                <Button v-if="!authStore.isAdmin" icon="edit-filling" size="small" @click="goSubmitDigPage(item)">采编</Button>
                <Button type="primary" size="small" icon="edit-filling" @click="goMyDigPage(item)">我的投稿</Button>            
              </ButtonGroup>
            </FlexRow>
          </FlexCol>
        </SimplePageContentLoader>
      </RequireLogin>

      <Height :height="20" />
      <HomeTitle v-if="authStore.isLogged" title="我的贡献" />
      <BackgroundBox 
        v-if="authStore.isLogged" 
        backgroundImage="https://xy.wenlvti.net/app_static/images/village/BoxMid.png"
        :backgroundCutBorder="32"
        :backgroundCutBorderSize="36"
        :padding="[40,20]"
        direction="row"
      >
        <FlexCol :flex="1" :gap="10" center>
          <Text fontConfig="lightGoldTitle">{{ volunteerInfoLoader.content.value?.points || 0 }}</Text>
          <Touchable direction="row" align="center" :gap="10" @click="navTo('/pages/dig/about/point')">
            <Text>文化积分</Text>
            <Icon icon="help-filling" color="primary" :size="40" />
          </Touchable>
        </FlexCol>
        <FlexCol :flex="1" :gap="10" center>
          <Text fontConfig="lightGoldTitle">Lv.{{ volunteerInfoLoader.content.value?.level || 1 }}</Text>
          <Text>等级</Text>
        </FlexCol>
      </BackgroundBox>
    </FlexCol>
  </FlexCol>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { navTo } from '@/components/utils/PageAction';
import { useAuthStore } from '@/store/auth';
import { useCollectStore } from '@/store/collect';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { useStorageVar } from '@/components/composeabe/StorageVar';
import { injectAppConfiguration } from '@/api/system/useAppConfiguration';
import VillageApi, { VillageListItem } from '@/api/inhert/VillageApi';
import RequireLogin from '@/common/components/RequireLogin.vue';
import SimplePageContentLoader from '@/components/loader/SimplePageContentLoader.vue';
import Button from '@/components/basic/Button.vue';
import Image from '@/components/basic/Image.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import H3 from '@/components/typography/H3.vue';
import Text from '@/components/basic/Text.vue';
import Height from '@/components/layout/space/Height.vue';
import ButtonGroup from '@/components/basic/ButtonGroup.vue';
import BubbleBox from '@/components/feedback/BubbleBox.vue';
import HomeTitle from '@/common/components/parts/HomeTitle.vue';
import HomeLargeTitle from '@/common/components/parts/HomeLargeTitle.vue';
import type { RequestApiError } from '@imengyu/imengyu-utils';
import FrameButton from '@/common/components/FrameButton.vue';
import CommonDivider from '@/common/components/CommonDivider.vue';
import Touchable from '@/components/feedback/Touchable.vue';
import Icon from '@/components/basic/Icon.vue';
import BackgroundBox from '@/components/display/block/BackgroundBox.vue';
import ImageSwiper from '@/common/components/parts/ImageSwiper.vue';

const authStore = useAuthStore();
const collectStore = useCollectStore();
const appConfiguration = injectAppConfiguration();
const { value: currentCity } = useStorageVar('currentCityName', '');

const notVolunteerError = ref(false);
const villageListLoader = useSimpleDataLoader(async () => await VillageApi.getClaimedVallageList(), true);
const volunteerInfoLoader = useSimpleDataLoader(async () => {
  try {
    const res = await VillageApi.getVolunteerInfo()
    notVolunteerError.value = false;
    return res;
  } catch (error) {
    notVolunteerError.value = checkIsNotVolunteerError(error);
    throw error;
  }
}, true);
const rankListLoader = useSimpleDataLoader(async () => await VillageApi.getVolunteerRanklist(), true);

function checkIsNotVolunteerError(e: unknown) {
  return (e as RequestApiError).errorMessage.includes('请认领')
}

watch(() => authStore.isLogged, (newVal) => {
  if (newVal) {
    villageListLoader.reload();
    volunteerInfoLoader.reload();
    rankListLoader.reload();
  }
})

function goSubmitDigPage(item: VillageListItem) {
  navTo('./dig/details', { 
    name: item.villageName,
    villageId: item.villageId,
    villageVolunteerId: item.villageVolunteerId,
    points: volunteerInfoLoader.content.value?.points,
    level: volunteerInfoLoader.content.value?.level,
  })
}
function goManagePage(item: VillageListItem) {
  navTo('./dig/admin/index', { 
    id: item.villageId,
    name: item.villageName,
    villageId: item.villageId,
    villageVolunteerId: item.villageVolunteerId,
    points: volunteerInfoLoader.content.value?.points,
    level: volunteerInfoLoader.content.value?.level,
  })
}
function goMyDigPage(item: VillageListItem) {
  navTo('./dig/forms/submits', { 
    villageName: item.villageName,
    villageId: item.villageId,
    villageVolunteerId: item.villageVolunteerId,
  })
}
function goPreviewDigPage(item: VillageListItem) {
  navTo('./dig/admin/preview', { 
    villageName: item.villageName,
    villageId: item.villageId,
    villageVolunteerId: item.villageVolunteerId,
  })
}
</script>
