<template>
  <FlexCol :padding="30" gap="gap.lg">

    <!-- 卡片背景 -->
    <BackgroundBox 
      color1="#eecaa0"
      color2="white"
      color2Position="85%"
      color3="white"
      radius="radius.lg"
      direction="column"
      :padding="[35,30]"
      gap="gap.lg"
    >

      <!-- 标题 -->
      <FlexRow justify="space-between" width="100%">
        <FlexCol gap="gap.md">
          <Text :text="villageInfoLoader.content.value?.title" fontConfig="primaryTitle" />
          <Text :text="villageInfoLoader.content.value?.address" fontConfig="contentText" />
        </FlexCol>
        <FlexRow center gap="gap.lg">
          <Button 
            icon="https://xy.wenlvti.net/app_static/images/village/IconJoin.png" 
            radius="radius.lgr"
            @click="isFollowed ? onUnFollow() : onFollow()"
          >
            {{ isFollowed ? '已关注' : '关注' }}
          </Button>
          <Button 
            icon="https://xy.wenlvti.net/app_static/images/village/IconFollow.png"
            radius="radius.lgr"
            @click="handleGoJoin()"
          >
            {{ isJoined ? '已加入' : '加入' }}
          </Button>
        </FlexRow>
      </FlexRow>

      <!-- 状态与申请 -->
      <Construction text="暂无数据">
        <FlexRow 
          backgroundColor="background.tertiary" 
          radius="radius.md" 
          padding="space.md" 
          justify="space-between" 
        >
          <FlexCol gap="gap.md"> 
            <Text :text="`${villageInfoLoader.content.value?.applyCount} 个乡源果可申请`" fontConfig="secondText" />  
            <Text :text="`存储空间内存：${villageInfoLoader.content.value?.sizeText}`" fontConfig="secondText" />
          </FlexCol>
          <FlexCol gap="gap.md">
            <Button icon="https://xy.wenlvti.net/app_static/images/village/IconUser.png" radius="radius.lgr" :padding="[10, 30]" backgroundColor="white">申请管理者</Button>
          </FlexCol>
        </FlexRow>
      </Construction>
      
      <!-- 图片 -->
      <Construction text="暂无接口">
        <FlexRow v-if="villageInfoLoader.content.value" justify="space-between">
          <Image 
            v-for="index of 3" 
            :key="index" 
            :src="villageInfoLoader.content.value.images[index - 1]" 
            radius="radius.md"
            :width="200"
            :height="140"
            mode="aspectFill"
            defaultImage=""
            touchable
          >
            <template #empty>
              <Touchable 
                direction="column" 
                position="absolute" 
                inset="0" 
                center
                backgroundColor="background.primary"
              >
                <Icon name="add" size="fontSize.md" />
                <Text text="上传封面" fontConfig="secondText" />
              </Touchable>
            </template>
            <FlexCol 
              v-if="index === 3 && villageInfoLoader.content.value.images.length > 3" 
              position="absolute" inset="0" 
              center 
              backgroundColor="mask.default"
            >
              <Text :text="`+${villageInfoLoader.content.value.images.length - 3}`" fontSize="fontSize.lg" color="white" />
            </FlexCol>
          </Image>
        </FlexRow>
      </Construction>

      <!-- 地址 -->
      <FlexRow align="center" gap="gap.sm">
        <Icon name="https://xy.wenlvti.net/app_static/images/village/IconMap.png" size="fontSize.md" />
        <Text :text="villageInfoLoader.content.value?.address" fontConfig="contentText" />
      </FlexRow>
      <VillageMiniMap 
        v-if="villageInfoLoader.content.value"
        :lonlat="{ 
          longitude: villageInfoLoader.content.value.longitude, 
          latitude: villageInfoLoader.content.value.latitude 
        }" 
      />

      <FlexRow justify="space-between" align="center">
        <FlexRow center gap="gap.lg" flexBasis="50%">
          <Text text="村社排名" fontConfig="contentText" />
          <Text text="No." fontConfig="lightTitle" />
          <Text :text="villageInfoLoader.content.value?.rankText" fontConfig="primaryTitle" />
        </FlexRow>
        <FlexRow center gap="gap.lg" flexBasis="50%">
          <Text text="村社等级" fontConfig="contentText" />
          <Text :text="villageInfoLoader.content.value?.levelText" fontConfig="primaryTitle" />
        </FlexRow>
      </FlexRow>

      <FlexRow backgroundColor="background.tertiary" radius="radius.md" :padding="[30, 20]">
        <FlexCol center gap="gap.sm" flexBasis="25%">
          <Text text="乡源光" fontConfig="secondText" />
          <Text :text="villageInfoLoader.content.value?.light" fontConfig="importantTitle" />
        </FlexCol>
        <Divider type="vertical" />
        <FlexCol center gap="gap.sm" flexBasis="25%">
          <Text text="乡源人数" fontConfig="contentText" />
          <Text :text="villageInfoLoader.content.value?.memberCount" fontConfig="importantTitle" />
        </FlexCol>
        <Divider type="vertical" />
        <FlexCol center gap="gap.sm" flexBasis="25%">
          <Text text="关注人数" fontConfig="contentText" />
          <Text :text="villageInfoLoader.content.value?.followerCount" fontConfig="importantTitle" />
        </FlexCol>
        <Divider type="vertical" />
        <Button 
          :padding="0" 
          type="text" 
          size="small" 
          textColor="text.title"
          text="新手上路" 
          rightIcon="arrow-right" 
          @click="handleGoNew()"
        />
      </FlexRow>
    </BackgroundBox>

    <!-- 排行榜 -->
    <HomeTitle title="排行榜" showMore @moreClicked="navTo('/pages/home/village/rank/volunteer', {
      villageId: villageStore.currentVillage?.id ?? undefined,
    })" />
    <RoundTags v-model:active="rankActiveTag" :tags="['乡源果', '志愿者', '乡源光']" />
    <VillageUserRankList :list="villageUserRankListLoader.content.value ?? []" />

    <!-- 魅力乡源 -->
    <HomeTitle title="魅力乡源" showMore @moreClicked="handleGoCollect()">
      <template #right>
        <Touchable 
          :padding="[15, 20]"
          :innerStyle="{ 
            marginRight: '20rpx'
          }"
          borderStyle="solid"
          borderColor="border.secondary"
          borderWidth="1px"
          backgroundColor="background.quaternary"
          radius="radius.md"
          direction="row"
          center
          gap="gap.sm"
          @click="handleGoCollect()"
        >
          <Icon name="https://xy.wenlvti.net/app_static/images/village/IconHistory.png" :size="30" />
          <Text text="共编村史" fontConfig="contentText" />
        </Touchable>
      </template>
    </HomeTitle>
    <ProvideVar :vars="{
      GridItemIconSize: 90,
      GridItemBackgroundColor: 'transparent',
      GridItemPaddingHorizontal: 0,
      GridItemPaddingVertical: 8,
    }">
      <Grid :borderGrid="false" :mainAxisCount="4">
        <GridItem title="村社概况" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeIntrod.png" touchable @click="handleGoCollect('overview')" />
        <GridItem title="自然风光" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeEnvirounment.png" touchable @click="handleGoCollect('environment', '自然环境')" />
        <GridItem title="历史沿革" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeHistory.png" touchable @click="handleGoCollect('history', '建村历史')" />
        <GridItem title="特色产业" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeIndustry.png" touchable @click="handleGoCollect('product')"    />
        <GridItem title="文艺活动" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeActivity.png" touchable @click="handleGoCollect('custom')" />
        <GridItem title="非遗展示" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeShow.png" touchable @click="handleGoCollect('ich')" />
        <GridItem title="民俗风采" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeFolkloreVibe.png" touchable @click="handleGoCollect('custom')" />
        <GridItem title="乡贤故事" icon="https://xy.wenlvti.net/app_static/images/village/IconGoods.png" touchable @click="handleGoCollect('history', '历史人物')" />
      </Grid>
    </ProvideVar>

    <!-- 活力乡源 -->
    <HomeTitle title="活力乡源" />
    <ProvideVar :vars="{
      GridItemIconSize: 90,
      GridItemBackgroundColor: 'transparent',
      GridItemPaddingHorizontal: 0,
      GridItemPaddingVertical: 8,
    }">
      <Grid :borderGrid="false" :mainAxisCount="4">
        <GridItem title="乡源荣光" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeHornor.png" touchable @click="toast('暂未开放，敬请期待！')" />
        <GridItem title="乡源好物" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeGoods.png" touchable @click="navTo('/pages/home/village/goods/index')" />
        <GridItem title="乡源树" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeTree.png" touchable @click="emit('goTree')" />
        <GridItem title="政贤连心" icon="https://xy.wenlvti.net/app_static/images/village/IconGovAffairs.png" touchable @click="toast('暂未开放，敬请期待！')" />
        <GridItem title="互动游戏" icon="https://xy.wenlvti.net/app_static/images/village/IconLargeGame.png" touchable @click="navTo('/pages/home/village/games/index')" />
      </Grid>
    </ProvideVar>

    <!-- 文脉乡源 -->
    <HomeTitle title="文脉乡源">
      <template #right>
        <BackgroundImageButton 
          backgroundImage="https://xy.wenlvti.net/app_static/images/village/TagActive.png"
          :backgroundCutBorder="[10, 10, 10, 10]"
          :backgroundCutBorderSize="[10, 10, 10, 10]"
          :padding="[15, 20]"
          :innerStyle="{ marginRight: '20rpx' }"
          direction="row"
          center
          gap="gap.sm"
          @click="handleGoPublish()"
        >
          <Icon name="https://xy.wenlvti.net/app_static/images/village/IconLargeHistory.png" :size="30" />
          <Text text="去发布" fontConfig="contentText" color="white" />
        </BackgroundImageButton>
      </template>
    </HomeTitle>
    <RoundTags v-model:active="listActiveTag" :tags="['广场', '老味道', '老手艺', '老物件', '老故事']" />
  </FlexCol>
  <OfficialAccountPublishWrap
    :topic="recommendTagName" 
    @publishsuccess="onPublishSuccess"
  />

</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useUserTools } from '@/common/composeabe/UserTools';
import { useOfficialAccount } from '../../composeabe/OfficialAccount';
import { useAuthStore } from '@/store/auth';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { useVillageStore } from '@/store/village';
import { useReqireLogin } from '@/common/composeabe/RequireLogin';
import { useFollow } from '../composeabe/Follow';
import { confirm, toast } from '@/components/utils/DialogAction';
import { ArrayUtils } from '@imengyu/imengyu-utils';
import { navTo } from '@/components/utils/PageAction';
import HomeTitle from '@/common/components/parts/HomeTitle.vue';
import Button from '@/components/basic/Button.vue';
import Icon from '@/components/basic/Icon.vue';
import Image from '@/components/basic/Image.vue';
import Text from '@/components/basic/Text.vue';
import BackgroundBox from '@/components/display/block/BackgroundBox.vue';
import Touchable from '@/components/feedback/Touchable.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import VillageMiniMap from '../../components/VillageMiniMap.vue';
import Divider from '@/components/display/Divider.vue';
import RoundTags from '@/common/components/parts/RoundTags.vue';
import VillageUserRankList from '../../components/VillageUserRankList.vue';
import BackgroundImageButton from '@/components/basic/BackgroundImageButton.vue';
import ProvideVar from '@/components/theme/ProvideVar.vue';
import Grid from '@/components/layout/grid/Grid.vue';
import GridItem from '@/components/layout/grid/GridItem.vue';
import LightVillageApi from '@/api/light/LightVillageApi';
import Construction from '@/common/components/Construction.vue';
import OfficialAccountPublishWrap from '@/common/components/OfficialAccountPublishWrap.vue';

const authStore = useAuthStore();
const { getIsVolunteer } = useUserTools();
const { requireLogin } = useReqireLogin();
const { onPublishSuccess } = useOfficialAccount();
const { isFollowed, onFollow, onUnFollow } = useFollow();
const villageStore = useVillageStore();
const { getIsJoinedVillage } = useUserTools();
const isJoined = ref(false);
const villageInfoLoader = useSimpleDataLoader(async () => {
  const village = villageStore.currentVillage;  
  if (village) 
    isJoined.value = await getIsJoinedVillage(village.id);
  return {
    title: village?.name || '',
    desc: village?.desc || '',
    address: village?.address,
    applyCount: village?.applyCount || 0,
    sizeText: village?.sizeText || 0,
    levelText: village?.level.toString() || '',
    rankText: village?.rank.toString() || '',
    light: village?.light as number || 0,
    memberCount: village?.volunteerCount as number || 0,
    followerCount: village?.followCount as number || 0,
    images: village?.images || [],
    longitude: village?.longitude as number || 0,
    latitude: village?.latitude as number || 0,
  };
});

const emit = defineEmits<{
  (e: 'goTree'): void;
}>();

const rankActiveTag = ref('乡源果');
const listActiveTag = ref('广场');

const villageUserRankListLoader = useSimpleDataLoader(async () => {
  const res = (await LightVillageApi.getVolunteerRankList({ 
    num: 3,
    village_id: villageStore.currentVillage?.id ?? undefined,
  }))
    .map((item, i) => ({
      id: item.id,
      image: item.image ?? '',
      title: item.name,
      rank: i + 1,
      score: item.points,
    }));
  if (res.length >= 3) {
    //移动第一名到中间
    const first = res[0];
    ArrayUtils.removeAt(res, 0);
    ArrayUtils.insert(res, 1, first);
  }
  return res
});

watch(rankActiveTag, () => {
  villageUserRankListLoader.reload();
});



const recommendTagName = computed(() => {
  return '亮乡源·' + villageInfoLoader.content.value?.title + '·' + listActiveTag.value;
});

function handleGoJoin() {
  if (isJoined.value)
    return;
  navTo('/pages/home/light/submit', {
    villageId: villageStore.currentVillage?.id ?? undefined,
    unit: (villageStore.currentVillage?.city as string) + (villageStore.currentVillage?.district as string) + (villageStore.currentVillage?.township as string),
    regionId: villageStore.currentVillage?.region ?? undefined,
  });
}
function handleGoNew() {
  navTo('/pages/home/light/help/new');
}
function handleGoCollect(taskName?: string, taskFindCatalogName?: string) {
  if (!taskName) {
    navTo('/pages/dig/details', {
      villageId: villageStore.currentVillage?.id ?? undefined,
    });
    return;
  }
  
  navTo('/pages/dig/forms/list', {
    villageId: villageStore.currentVillage?.id ?? undefined,
    taskName: taskName,
    taskFindCatalogName: taskFindCatalogName,
  });
}
function handleGoPublish() {
  if (!authStore.isLogged) {
    confirm({
      title: '提示',
      content: '登录后就可以发布村社贴图了',
      confirmText: '去登录',
    }).then((res) => {
      if (res) {
        navTo('/pages/user/login');
      }
    });
    return;
  }
  navTo('/pages/chat/dependent/post/publish', {
    tag: listActiveTag.value,
    villageId: villageStore.currentVillage?.id ?? undefined,
  });
}
function handleGoPost(id: number) {
  navTo('/pages/home/post/detail', {
    id: id,
  });
}

watch(() => villageStore.currentVillage, () => {
  villageInfoLoader.reload();
  villageUserRankListLoader.reload();
}, { immediate: true });
</script>