<template>
  <CommonRoot>
    <FlexCol v-if="showSwitch" position="fixed" :left="0" :top="0" :right="0" :zIndex="200">
      <StatusBarSpace />
      <FlexRow gap="gap.lg" :padding="30">
        <BubbleTip
          v-model:show="showFollowTip"
          position="bottom"
          crossPosition="left"
          arrowOffsetX="-50rpx"
          content="点此可以查看我关注的村社"
          @contentClick="handleCloseFollowTip(true)"
          @close="handleCloseFollowTip(false)"
        >
          <Button
            icon="https://xy.wenlvti.net/app_static/images/home/IconSwitch.png"
            :text="villageStore.currentVillage?.name || '未选择村社'"
            :textColor="topTab === 'village' ? 'text.titleLight' : 'text.content'"
            size="medium"
            @click="showMyFollowPopup = true"
          />
        </BubbleTip>
        <!-- <Button
          :textColor="topTab === 'around' ? 'text.titleLight' : 'text.content'"
          text="周边村社" 
          size="medium"
          @click="topTab = 'around'" 
        /> -->
      </FlexRow>
    </FlexCol>
    <Height :height="40" />
    <template v-if="delayShow">
      <FlexCol v-if="topTab === 'village' && villageStore.currentVillage" gap="gap.md">
        <FlexRow center :padding="[0,30]">
          <HomeLargeTitle title="村社名片" :active="tab === 'card'" @click="tab = 'card'" />
          <Width :width="30" />
          <HomeLargeTitle title="乡源树" titleColorAnim :active="tab === 'tree'" @click="tab = 'tree'">
            <template #icon>
              <Image src="https://xy.wenlvti.net/app_static/images/village/TreeIconAmin2.gif" :width="34" :height="50" mode="heightFix" />
            </template>
          </HomeLargeTitle>
          <Width :width="30" />
        </FlexRow>
        <Card 
          v-if="tab === 'card'" 
          ref="cardRef"
          @goTree="tab = 'tree'" 
          @goJoin="joinDialog?.show()"
        />
        <Tree 
          v-if="tab === 'tree'" 
          ref="treeRef"
        />
        <Height :height="150" />
      </FlexCol>
      <FlexCol v-else-if="topTab === 'village'" gap="gap.md">
        <FlexCol center :padding="[60,0]" gap="gap.md">
          <Image src="https://xy.wenlvti.net/app_static/images/home/BadgeNew.png" :width="320" mode="widthFix" />
          <Text text="还未选择一个村社" fontConfig="primaryTitle" />
          <Text text="欢迎关注或者认领村社，认领自己家乡参与建设，或四处看看" fontConfig="contentText" />
          <Height :height="20" />
          <FlexRow gap="gap.lg">
            <FrameButton text="去认领村社" @click="handleGoSuscribe" primary />
          </FlexRow>
        </FlexCol>
        <Height :height="150" />
      </FlexCol>
      <!-- <Around 
        v-else 
        @selectVillage="onSelectVillage" 
      /> -->
    </template>
    <LoadingPage v-else />
    <Height :height="200" />
    <Popup 
      v-model:show="showMyFollowPopup" 
      closeable
      position="bottom"
      round
      size="80vh"
    >
      <scroll-view scroll-y style="height: 100%">
        <VillageMyFollow @goDetails="onSelectVillage" />
      </scroll-view>
    </Popup>
    <JoinDialog
      ref="joinDialog" 
      v-if="villageStore.currentVillage"
      :villageId="villageStore.currentVillage.id" 
    />
  </CommonRoot>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useVillageStore } from '@/store/village';
import { useFollow } from './composeabe/Follow';
import { isDevEnv } from '@/common/config/AppCofig';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import type { VillageListItem } from '@/api/light/LightVillageApi';
import FlexCol from '@/components/layout/FlexCol.vue';
import Height from '@/components/layout/space/Height.vue';
import Image from '@/components/basic/Image.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Card from './introd/card.vue';
import Tree from './introd/tree.vue';
import StatusBarSpace from '@/components/layout/space/StatusBarSpace.vue';
import Button from '@/components/basic/Button.vue';
import Popup from '@/components/dialog/Popup.vue';
import Text from '@/components/basic/Text.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import Width from '@/components/layout/space/Width.vue';
import VillageMyFollow from '../components/VillageMyFollow.vue';
import HomeLargeTitle from '@/common/components/parts/HomeLargeTitle.vue';
import Around from './recommed/around.vue';
import FrameButton from '@/common/components/FrameButton.vue';
import JoinDialog from './dialogs/JoinDialog.vue';
import BubbleTip from '@/components/feedback/BubbleTip.vue';
import MemoryTimeOut from '@/components/composeabe/MemoryTimeOut';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';

const topTab = ref<'village' | 'around'>('village');
const tab = ref('card');
const delayShow = ref(false);
const villageStore = useVillageStore();
const { isFollowed } = useFollow();

const showMyFollowPopup = ref(false);
const joinDialog = ref<InstanceType<typeof JoinDialog>>();
  
const cardRef = ref<InstanceType<typeof Card>>(); 
const treeRef = ref<InstanceType<typeof Tree>>();

const props = withDefaults(defineProps<{
  showSwitch?: boolean;
}>(), {
  showSwitch: false,
});
const emit = defineEmits(['goHome']);

const showFollowTipTimeout = new MemoryTimeOut('FollowTip', 1000 * 3600 * 30);//30h
const showFollowTip = ref(false);

function handleShowFollowTip() {
  if (showFollowTipTimeout.isTimeout()) {
    showFollowTip.value = true;
  }
}
function handleCloseFollowTip(open: boolean) {
  showFollowTipTimeout.recordTime();
  if (open) 
    showMyFollowPopup.value = true;
}

function handleGoSuscribe() {
  emit('goHome');
}

function onSelectVillage(village: VillageListItem) {
  topTab.value = 'village';
  villageStore.setCurrentVillage(village);
  uni.pageScrollTo({ scrollTop: 0 });
  showMyFollowPopup.value = false;
}

watch(() => villageStore.currentVillage?.id, (newVal) => {
  if (newVal && topTab.value === 'around')
    topTab.value = 'village';
  tab.value = 'card';
  handleTestGoTree();
  handleShowFollowTip();
});
watch(() => isFollowed.value, (newVal) => {
  handleShowFollowTip();
});

onMounted(async () => {
  if (!props.showSwitch) {
    uni.setNavigationBarTitle({
      title: villageStore.currentVillage?.name || '未选择村庄',
    });
  }
  await waitTimeOut(100);
  delayShow.value = true;
  await waitTimeOut(1000);
  handleTestGoTree();
});

function handleTestGoTree() {
  if (isDevEnv) {
    //tab.value = 'tree';
  }
}

defineExpose({
  onPageBack: (name: string, data: Record<string, unknown>) => {
    cardRef.value?.onPageBack(name, data);
    treeRef.value?.onPageBack(name, data);
  },
  goTreePage: () => {
    tab.value = 'tree';
  },
  goCollectPage: () => {
    tab.value = 'card';
    uni.pageScrollTo({
      scrollTop: 1000
    })
  },
})
</script>