<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/dig/TopBanner.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"
      />
      <HomeIndex v-show="tabIndex === 0" @goVillage="tabIndex = 1" />
      <VillageIndex v-if="tabIndex === 1" showSwitch ref="villageIndex" />
      <DigIndex v-else-if="tabIndex === 2" />
      <DiscoverIndex v-else-if="tabIndex === 3" />
      <UserIndex v-else-if="tabIndex === 4" @goSubmit="tabIndex = 2" />
      <TabBar
        v-model:selectedTabIndex="tabIndex"
        fixed
        xbarSpace
        :innerStyle="{
          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 } 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';

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

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() {
  try {
    const res = await LightVillageApi.getVillageDetails(querys.value.villageId as number);
    villageStore.setCurrentVillage(res);
  } catch (error) {
    console.error(error);
    return;
  }
  tabIndex.value = 1;
}
async function reloadVillageInfo() {
  try {
    if (!villageStore.currentVillage)
      return;
    const res = await LightVillageApi.getVillageDetails(villageStore.currentVillage.id as number);
    villageStore.setCurrentVillage(res);
  } catch (error) {
    console.error(error);
    return;
  }
  tabIndex.value = 1;
}
function getShareVillageInfo() {
  if (villageStore.currentVillage) {
    //分享村社信息
    return {
      title: `邀请您加入${villageStore.currentVillage.name}村社`,
      path: `/pages/index?villageId=${villageStore.currentVillage.id}&userId=${authStore.userInfo?.id || 0}`,
      imageUrl: villageStore.currentVillage.image || 'https://mn.wenlvti.net/app_static/xiangyuan/images/index-post.jpg',
    }
  }
  return {
    title: '村社文化资源挖掘平台',
    path: '/pages/index',
    imageUrl: 'https://mn.wenlvti.net/app_static/xiangyuan/images/index-post.jpg',
  };
}
async function paySuccessAndRefresh() {
  try {
    uni.showLoading({
      title: '请稍后...',
    });

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

defineExpose({
  onPageBack: (name: string, data: Record<string, unknown>) => {
    if (data.type === 'goVillage') {
      tabIndex.value = 1;
    } else if (name === 'paySuccessAndRefresh') {
      paySuccessAndRefresh();
    }
  }
})
onShareAppMessage(() => {
  return getShareVillageInfo();
})
onShareTimeline(() => {
  return getShareVillageInfo();
})
onMounted(() => {
  if (isDevEnv) {
    tabIndex.value = 1;
  }
})
</script>