<template>
  <FlexCol padding="padding.md">
    <HomeLargeTitle title="挖掘" />
    <ImageSwiper
      :images="bannerLoader.content.value || []"
      :height="appConfiguration?.banners.dig.height"
      width="100%"
      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">
          <BoxMid 
            v-for="item in villageListLoader.content.value"
            :key="item.id"
            radius="radius.md"
            :padding="20"
            direction="row"
            align="center"
            justify="space-between"
          >
            <FlexRow align="center" gap="gap.lg">
              <Image 
                mode="aspectFill"
                :src="item.image" 
                round
                :width="80"
                :height="80"
              />
              <Text 
                :text="item.villageName" 
                :maxWidth="260"
                :lines="2"
                fontConfig="lightGoldTitle" 
              />
            </FlexRow>
            <FlexRow align="center" gap="gap.md">
              <BubbleBox :items="[
                {
                  icon: 'edit-filling',
                  text: '管理',
                  onClick: () => goManagePage(item),
                },
                {
                  icon: 'edit-filling',
                  text: '采编',
                  onClick: () => goSubmitDigPage(item),
                },
              ]">
                <FrameButton v-if="authStore.isAdmin" icon="edit-filling" text="采编/管理" size="small" />
              </BubbleBox>
              <FrameButton v-if="!authStore.isAdmin" icon="edit-filling" text="采编" size="small" @click="goSubmitDigPage(item)" />
              <FrameButton primary size="small" icon="edit-filling" text="我的投稿" @click="goMyDigPage(item)" />
            </FlexRow>
          </BoxMid>
        </FlexCol>
      </SimplePageContentLoader>
    </RequireLogin>

    <Height :height="20" />
    <HomeTitle v-if="authStore.isLogged" title="我的贡献" />
    <BoxMid 
      v-if="authStore.isLogged" 
      :padding="[40,20]"
      direction="row"
    >
      <FlexCol :flex="1" :gap="10" center>
        <Text fontConfig="lightGoldTitle">{{ volunteerInfo?.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.{{ volunteerInfo?.level || 1 }}</Text>
        <Text>等级</Text>
      </FlexCol>
    </BoxMid>
    <Height :height="300" />
  </FlexCol>
  <ClamVolunteerDialog 
    ref="clamVolunteerDialog"
    :villageId="clamVolunteerVillageId"
    @finish="clamFinish"
  />
</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 { useVolunteerInfo } from './village/composeabe/VolunteerInfo';
import { useStorageVar } from '@/components/composeabe/StorageVar';
import { injectAppConfiguration } from '@/api/system/useAppConfiguration';
import { confirm } from '@/components/dialog/CommonRoot';
import VillageApi, { VillageListItem } from '@/api/inhert/VillageApi';
import BannerApi from '@/api/system/Banner';
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 ImageSwiper from '@/common/components/parts/ImageSwiper.vue';
import BoxMid from '@/common/components/box/BoxMid.vue';
import ClamVolunteerDialog from './village/dialogs/ClamVolunteerDialog.vue';

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

const bannerLoader = useSimpleDataLoader(async () => {
  return (await BannerApi.getBannerList({
    keywords: '亮乡源大众版挖掘首页',
  })).map(p => ({
    image: p.image,
    url: p.url,
  }));
});

const { notVolunteerError, volunteerInfo, getIsVolunteer } = useVolunteerInfo();

const villageListLoader = useSimpleDataLoader(async () => await VillageApi.getClaimedVallageList(), true);
const rankListLoader = useSimpleDataLoader(async () => await VillageApi.getVolunteerRanklist(), true);

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

const clamVolunteerDialog = ref<InstanceType<typeof ClamVolunteerDialog>>();
const clamVolunteerVillageId = ref<number>(0);

function checkIsVolunteer(item: VillageListItem) {
  if (!item.collectFlag) {
    confirm({
      title: '提示',
      content: '您还不是本村志愿者，申请成为志愿者后即可开始采编挖掘',
      confirmText: '去申请',
      cancelText: '取消',
    }).then((res) => {
      if (res) {
        clamVolunteerVillageId.value = item.villageId;
        clamVolunteerDialog.value?.show();
      }
    })
    return false;
  }
  return true;
}

function clamFinish() {
  getIsVolunteer();
  rankListLoader.reload();
}

function goSubmitDigPage(item: VillageListItem) {
  if (!checkIsVolunteer(item))
    return;
  
  navTo('./dig/details', { 
    name: item.villageName,
    villageId: item.villageId,
    villageVolunteerId: item.villageVolunteerId,
    points: volunteerInfo.value?.points,
    level: volunteerInfo.value?.level,
  })
}
function goManagePage(item: VillageListItem) {
  navTo('./dig/admin/index', { 
    id: item.villageId,
    name: item.villageName,
    villageId: item.villageId,
    villageVolunteerId: item.villageVolunteerId,
    points: volunteerInfo.value?.points,
    level: volunteerInfo.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>
