<template>
	<view class="index" :style="{
    backgroundImage: tabIndex === 4 ? 
      `url('https://xy.wenlvti.net/app_static/images/mine/TopBanner.png')` 
      : `url('https://xy.wenlvti.net/app_static/images/home/BannerHome.png')`,
    backgroundRepeat: 'no-repeat',
    backgroundSize: '100% auto',
    backgroundPosition: 'top center',
    backgroundColor: themeContext.resolveThemeColor('background.primary'),
  }">
    <CommonRoot>
      <StatusBarSpace backgroundColor="transparent" />
      <NavBar
        :titleScroll="false"
        backgroundColor="transparent"
        textColor="whweixinite"
        align="left"
        :zIndex="200"
      />
      <HomeIndex v-show="tabIndex === 0" @goVillage="tabIndex = 1" @goDig="tabIndex = 2" />
      <VillageIndex v-if="tabIndex === 1" showSwitch ref="villageIndex" @goHome="tabIndex=0" />
      <DigIndex v-show="tabIndex === 2" />
      <DiscoverIndex v-show="tabIndex === 3" @goVillage="tabIndex = 1" />
      <UserIndex v-show="tabIndex === 4" @goSubmit="tabIndex = 2" />
      <TabBar
        v-model:selectedTabIndex="tabIndex"
        fixed
        xbarSpace
        :innerStyle="{
          zIndex: 201,
          backgroundColor: '#ffead8',
        }"
      >
        <TabBarItem icon="https://xy.wenlvti.net/app_static/images/tabs/TabIconHome.png" activeIcon="https://xy.wenlvti.net/app_static/images/tabs/TabIconHomeActive.png" text="首页" :iconSize="70" />
        <TabBarItem icon="https://xy.wenlvti.net/app_static/images/tabs/TabIconVillage.png" activeIcon="https://xy.wenlvti.net/app_static/images/tabs/TabIconVillageActive.png" text="乡源" :iconSize="70" />
        <TabBarItem icon="https://xy.wenlvti.net/app_static/images/tabs/TabIconDig.png" activeIcon="https://xy.wenlvti.net/app_static/images/tabs/TabIconDigActive.png" text="挖掘" :iconSize="70" />
        <TabBarItem icon="https://xy.wenlvti.net/app_static/images/tabs/TabIconDiscover.png" activeIcon="https://xy.wenlvti.net/app_static/images/tabs/TabIconDiscoverActive.png" text="发现" :iconSize="70" />
        <TabBarItem icon="https://xy.wenlvti.net/app_static/images/tabs/TabIconMine.png" activeIcon="https://xy.wenlvti.net/app_static/images/tabs/TabIconMineActive.png" text="我的" :iconSize="70" />
      </TabBar>
    </CommonRoot>
	</view>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { useTheme } from '@/components/theme/ThemeDefine';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { useVillageStore } from '@/store/village';
import { useAuthStore } from '@/store/auth';
import { isDevEnv } from '@/common/config/AppCofig';
import { navTo } from '@/components/utils/PageAction';
import StatusBarSpace from '@/components/layout/space/StatusBarSpace.vue';
import NavBar from '@/components/nav/NavBar.vue';
import TabBar from '@/components/nav/TabBar.vue';
import TabBarItem from '@/components/nav/TabBarItem.vue';
import DigIndex from './home/dig.vue';
import UserIndex from './user/index.vue';
import HomeIndex from './home/index.vue';
import DiscoverIndex from './home/discover/index.vue';
import VillageIndex from './home/village/index.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import LightVillageApi from '@/api/light/LightVillageApi';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { injectAppConfiguration } from '@/api/system/useAppConfiguration';

const tabIndex = ref(0);
const themeContext = useTheme();
const villageStore = useVillageStore();
const authStore = useAuthStore();
const appConfiguration = injectAppConfiguration();

const villageIndex = ref<InstanceType<typeof VillageIndex>>();

const { querys } = useLoadQuerys({ 
  openLogin: false,
  villageId: 0,
  userId: 0,
}, (querys) => {
  if (querys.openLogin) {
    navTo('/pages/user/login');
  }
  if (querys.villageId) {
    loadShareVillageInfo();
  }
  if (querys.userId) {
    villageStore.setShareFromVillageUserId(querys.userId);
  }
});

async function loadShareVillageInfo(id?: number) {
  try {
    const res = await LightVillageApi.getVillageDetails(id ?? querys.value.villageId as number);
    villageStore.setCurrentVillage(res);
  } catch (error) {
    console.error(error);
    return;
  }
  tabIndex.value = 1;
}
function getShareVillageInfo() {
  if (villageStore.currentVillage) {
    //分享村社信息
    const villageInfoInList = villageStore.myJoinedVillages.find(v => v.id === villageStore.currentVillage?.id);
    const myNickName = villageInfoInList?.villageNickname || authStore.userInfo?.nickname || authStore.userInfo?.username || '老友';
    return {
      title: `同乡 ${myNickName} 邀您回 ${villageStore.currentVillage.name} 看看，心系故土，携手共建美好家乡`,
      path: `/pages/index?villageId=${villageStore.currentVillage.id}&userId=${authStore.userInfo?.id || 0}`,
      imageUrl: villageStore.currentVillage.image || appConfiguration.value.sharePost.villageDefault,
    }
  }
  return {
    title: '村社文化资源挖掘平台',
    path: '/pages/index',
    imageUrl: appConfiguration.value.sharePost.default,
  };
}
async function paySuccessAndRefresh() {
  try {
    uni.showLoading({
      title: '请稍后...',
    });

    tabIndex.value = 0;
    await villageStore.reloadVillageInfo();
    await waitTimeOut(100);
    tabIndex.value = 1;
  } catch (error) {
    console.error(error);
    return;
  } finally {
    uni.hideLoading();
  }
}

watch(tabIndex, () => {
  uni.setStorageSync('lastTabIndex', tabIndex.value);
  uni.pageScrollTo({ scrollTop: 0, duration: 0 });
});


defineExpose({
  onPageBack: (name: string, data: Record<string, unknown>) => {
    if (name === 'goVillage') {
      tabIndex.value = 1;
      if (data.id) {
        loadShareVillageInfo(data.id as number);
      }
      if (data.taskType) {
        setTimeout(() => {
          switch (data.taskType) {
            case 'collect':
              villageIndex.value?.goCollectPage();
              break;
            case 'post':
              break;
            case 'tree':
              villageIndex.value?.goTreePage();
              break;
          }
        }, 500);
      }
    } else if (name === 'paySuccessAndRefresh') {
      paySuccessAndRefresh();
    } else {
      villageIndex.value?.onPageBack(name, data);
    }
  }
})
onShareAppMessage(() => {
  return getShareVillageInfo();
})
onShareTimeline(() => {
  return getShareVillageInfo();
})
onMounted(() => {
  if (isDevEnv) {
    tabIndex.value = Number(uni.getStorageSync('lastTabIndex') ?? 0);
  }
})
</script>