<template>
  <view class="container">
    <Home v-if="globalStore.curTabIndex == 0 && !globalStore.isWxFriendCircle" :scroll-top="scrollTop" />
    <Brand v-if="globalStore.curTabIndex == 1 && !globalStore.isWxFriendCircle" :scroll-top="scrollTop" />
    <Integral v-if="globalStore.curTabIndex == 2 && !globalStore.isWxFriendCircle" :scrollTop="scrollTop" />
    <My v-if="globalStore.curTabIndex == 3 && !globalStore.isWxFriendCircle" />
    <TabBar v-if="!globalStore.isWxFriendCircle" :curTabIndex="globalStore.curTabIndex" @tabClick="handleTabClick" />
    <WxFriendCircleSimplePage v-if="globalStore.isWxFriendCircle" />

    <button v-if="isBackApp" class="back-app" open-type="launchApp" app-parameter="wechat"
      @binderror="handleLaunchAppError" :style="{
        backgroundImage: `url(${$baseUrl}homepage/backAppBtn.png)`,
      }">
      <!-- <text class="back-text">返回app</text> -->
    </button>

    <!-- 活动入选弹窗 -->
    <ActivitySelectedPopup :visible="showActivitySelectedPopup" :activityList="selectedActivityList"
      @close="showActivitySelectedPopup = false" @viewActivity="handleViewActivity" />

  </view>
</template>

<script setup>
import { ref, getCurrentInstance, watch, onMounted } from "vue";
import { onLoad, onShareAppMessage, onShareTimeline, onPageScroll, onShow } from "@dcloudio/uni-app";
import TabBar from "@/components/TabBar.vue";
import Home from "@/views/Home.vue";
import Brand from "@/views/Brand.vue";
import Integral from "@/views/Integral.vue";
import My from "@/views/My.vue";
import WxFriendCircleSimplePage from "@/components/WxFriendCircleSimplePage.vue";
import ActivitySelectedPopup from "@/components/ActivitySelectedPopup.vue";
import { useGlobalStore } from "@/stores/global.js";
import { useUserStore } from "@/stores/user.js";
import { fetchUserClickActivity } from "../../api/home";
import { jump, JumpType } from "../../utils";

const globalStore = useGlobalStore();
const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const $baseUrl = proxy.$baseUrl;
const homeRef = ref(null);
const scrollTop = ref(0);
const isBackApp = ref(false);
// 活动入选弹窗
const showActivitySelectedPopup = ref(false);
const selectedActivityList = ref([]);
const hasShownActivityPopup = ref(false); // 标记是否已经显示过弹窗
const shareOptions = {
  0: {
    title: "8000万中国妈妈信赖的育儿品牌",
    path: "/pages/index/index?pageType=home",
    imageUrl: $baseUrl + "share/share_home0901.jpg",
  },
  1: {
    title: "飞鹤提供家庭营养一站式解决方案",
    path: "/pages/index/index?pageType=brand",
    imageUrl: $baseUrl + "share/share_brand.png",
  },
  2: {
    title: "超凡吸收！更多妈妈推荐的奶粉",
    path: "/pages/index/index?pageType=integral",
    imageUrl: $baseUrl + "share/share_integral.png",
  },
};

// 处理返回APP失败的情况
const handleLaunchAppError = (e) => {
  console.error('返回APP失败:', e.detail.errMsg);

  // 根据错误类型给出不同的提示
  let errorMessage = '返回APP失败';
  if (e.detail.errMsg.includes('fail')) {
    errorMessage = '无法返回APP，请检查APP是否已安装';
  }

  uni.showToast({
    title: errorMessage,
    icon: 'none',
    duration: 2000
  });
};

function handleTabClick({ index }) {
  globalStore.setCurTabIndex(index);
}

// 查看活动
const handleViewActivity = (activity, index) => {
  console.log('查看活动:', activity, index)
  // 接口调用已在组件内部完成，这里只需要处理跳转逻辑
  // 根据 activityUri 跳转到对应页面
  const uri = activity.uri || activity.activityUri
  if (!uri) {
    console.warn('活动没有跳转地址')
    return
  }

  console.log('跳转到活动页面:', uri)

  // 判断跳转类型
  // H5 链接
  jump({
    type: JumpType.H5,
    url: uri
  })

}

// 显示活动入选弹窗
const showActivitySelectedPopupFunc = (activityList) => {
  selectedActivityList.value = activityList || []
  showActivitySelectedPopup.value = true
}

// 检查并显示活动入选弹窗
const checkAndShowActivityPopup = () => {
  // 如果已经显示过弹窗，不再重复显示
  if (hasShownActivityPopup.value) {
    console.log('活动入选弹窗已显示过，跳过')
    return
  }

  const memberInfo = userStore.memberInfo
  console.log('检查活动入选弹窗 - memberInfo:', memberInfo)
  console.log('检查活动入选弹窗 - passedActivityList:', memberInfo?.passedActivityList)

  if (memberInfo && memberInfo.passedActivityList && memberInfo.passedActivityList.length > 0) {
    // 将 passedActivityList 转换为组件需要的格式
    const activityList = memberInfo.passedActivityList.map(item => ({
      id: item.activityId,
      name: item.activityName,
      uri: item.activityUri,
      disabled: false
    }))

    console.log('转换后的活动列表:', activityList)
    selectedActivityList.value = activityList
    showActivitySelectedPopup.value = true
    hasShownActivityPopup.value = true // 标记已显示
    console.log('显示活动入选弹窗:', activityList)
  } else {
    console.log('没有活动入选数据，不显示弹窗')
  }
}

// 监听 memberInfo 变化，检查是否有 passedActivityList
watch(() => userStore.memberInfo, (newVal, oldVal) => {
  if (newVal && newVal.passedActivityList && newVal.passedActivityList.length > 0) {
    // 检查是否是新的活动列表（通过比较 activityId 来判断）
    const oldActivityIds = oldVal?.passedActivityList?.map(item => item.activityId) || []
    const newActivityIds = newVal.passedActivityList.map(item => item.activityId)

    // 如果有新的活动，重置标记并显示弹窗
    const hasNewActivity = newActivityIds.some(id => !oldActivityIds.includes(id))
    if (hasNewActivity) {
      hasShownActivityPopup.value = false
    }

    // 延迟一下，确保页面已经渲染完成
    setTimeout(() => {
      checkAndShowActivityPopup()
    }, 300)
  }
}, { deep: true })

onLoad(async (options) => {
  const optionsSync = wx.getEnterOptionsSync()
  if (optionsSync.scene == '1154') {
    globalStore.setIsWxFriendCircle(true)

  }
  if (optionsSync.scene == '1069') {
    isBackApp.value = true;
  } else {
    isBackApp.value = false;
  }

  console.warn('options231', options, globalStore.isWxFriendCircle)
  if (options.pageType) {
    switch (options.pageType) {
      case "home":
        globalStore.setCurTabIndex(0);
        break;
      case "brand":
        globalStore.setCurTabIndex(1);
        break;
      case "integral":
        globalStore.setCurTabIndex(2);
        break;
      case "my":
        globalStore.setCurTabIndex(3);
        break;
    }
  }

  // 加载会员信息，检查是否有活动入选
  if (userStore.isLogin) {
    await userStore.loadMemberInfo()
    checkAndShowActivityPopup()
  }
});

onShow(async () => {
  // 页面显示时，如果已登录，刷新会员信息（但不强制显示弹窗，由 watch 监听处理）
  if (userStore.isLogin) {
    await userStore.loadMemberInfo()
  }
});

onShareAppMessage(() => {
  const pageType = globalStore.curTabIndex;
  return shareOptions[pageType] || shareOptions[0];
});

onShareTimeline(() => {
  const pageType = globalStore.curTabIndex;
  return shareOptions[pageType] || shareOptions[0];
});

onPageScroll((e) => {
  scrollTop.value = e.scrollTop;
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;

  .content {
    padding-bottom: 100rpx; // 为底部TabBar留出空间
  }
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

}

// .back-app{
//     position: fixed;
//     top: 100rpx;
//     border-radius: 34rpx;
//     height: 68rpx;
//     width: 250rpx;
//     left:20rpx;
//     // background-image: url('https://course.feihe.com/momclub-picture/back_app.png');
//     // .back-text{
//     //   position: absolute;
//     //   font-size: 28rpx;
//     //   left: 30rpx;
//     // }
//   }

.back-app {
  position: fixed;
  top: 100rpx;
  border-radius: 34rpx;
  height: 68rpx;
  width: 150rpx;
  left: 20rpx;
  border: none;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  z-index: 999;

  &:active {
    transform: scale(0.98);
  }

  &::after {
    border: none !important;
  }
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>