<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" />

    <!-- 邀请奖品弹窗 -->
    <InvitePrizePanel
      :visible="globalStore.isShowInvitePrizePanel"
      :inviteCount="globalStore.inviteCount"
      :prizeName="globalStore.prizeName"
      :prizeImage="globalStore.prizeImage"
      :prizeType="globalStore.prizeType"
      :memberId="globalStore.memberId"
      @close="handleCloseInvitePrizePanel"
      @record="handleInvitePrizePanelRecord"
      @prize="handleInvitePrizePanelPrize"
    />

    <!-- 任务完成弹窗 -->
    <!-- <TaskComplete 
		:visible="globalStore.isShowTaskComplete"
		:points="globalStore.taskCompletePoints"
		:taskTitle="globalStore.taskCompleteTitle"
		@close="handleCloseTaskComplete"
		@accept="handleAcceptTaskComplete"
	/> -->

    <!-- 任务弹窗 -->
    <TaskPop
      :visible="globalStore.isShowTaskPop"
      :taskTodo="globalStore.taskTodo"
      @close="handleCloseTaskPop"
      @taskClick="handleTaskClick"
    />

    <!-- 任务完成提示弹窗 -->
    <TaskCompleteTips
      :visible="globalStore.isShowTaskComplete"
      :points="globalStore.taskCompletePoints"
      :taskTitle="globalStore.taskCompleteTitle"
      @close="handleCloseTaskCompleteTips"
    />

    <!-- 任务信息弹窗 -->
    <TaskPerson
      :visible="globalStore.isShowTaskPerson"
      @close="handleCloseTaskPerson"
      @submit="handleTaskPersonSubmit"
    />

    <!-- 公众号弹窗 -->
    <GongzhonghaoPop
      :visible="showGongzhonghaoPop"
      :title="gongzhonghaoTitle"
      :description="gongzhonghaoDescription"
      :qrCodeUrl="gongzhonghaoQrCodeUrl"
      @close="handleCloseGongzhonghaoPop"
      @download="handleDownloadQrCode"
    />

    <!-- 视频弹窗 -->
    <view v-if="showVideo" class="video-popup1">
      <video
        :src="currentVideoUrl"
        controls
        autoplay
        :style="{ width: videoWidth + 'px', height: videoHeight + 'px' }"
        @loadedmetadata="onVideoLoadedMeta"
        @play="onVideoPlay"
      ></video>
      <view class="close-btn-bottom" @tap="closeVideo">×</view>
    </view>

    <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>

    <!-- 悬浮授权手机号模块 -->
    <view class="auth-phone-module" v-if="!userStore.memberInfo?.mobile">
      <image class="auth-phone-bg" :src="$baseUrl + 'homepage/Q3Res/accessBg3.png'"></image>
      <view class="auth-phone-btn-container">
        <image
          class="auth-phone-btn"
          :src="$baseUrl + 'homepage/Q3Res/accessBtn3.png'"
          @tap="handleAuthPhoneClick"
        >
        </image>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, nextTick } 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 md from '@/md';
import WxFriendCircleSimplePage from '@/components/WxFriendCircleSimplePage.vue';
import InvitePrizePanel from '@/components/integralArea/InvitePrizePanel.vue';
// import TaskComplete from "@/components/qiandao/TaskComplete.vue";
import TaskPop from '@/components/renwu/TaskPop.vue';
import TaskPerson from '@/components/renwu/TaskPerson.vue';
import TaskCompleteTips from '@/components/renwu/TaskCompleteTips.vue';
import { useGlobalStore } from '@/stores/global.js';
import { useUserStore } from '@/stores/user.js';
import { jump, JumpType } from '../../utils';
import { taskCompleteJSON, taskReceiveJSON } from '../../api/integral';
import { useIntegralStore } from '@/stores/integral';
import GongzhonghaoPop from '@/components/renwu/GongzhonghaoPop.vue';

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 taskId = ref(0);
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 + 'common/shareImg.png',
  },
  2: {
    title: '星妈会 | 解锁你的会员服务',
    path: '/pages/index/index?pageType=integral',
    imageUrl: $baseUrl + 'common/shareImg.png',
  },
};

// 公众号弹窗参数

const showGongzhonghaoPop = ref(false);
const gongzhonghaoTitle = ref('公众号');
const gongzhonghaoDescription = ref('长按关注星妈会公众号,了解更多专业育儿资讯');
const gongzhonghaoQrCodeUrl = ref('https://course.feihe.com/momclub-picture/homepage/qrcode_gzh.png');

// 视频弹窗相关
const showVideo = ref(false);
const currentVideoUrl = ref('');
const videoWidth = ref(375);
const videoHeight = ref(210);

// 处理返回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);
  // tab切换时，如果授权手机号模块显示，触发曝光埋点
  if (!userStore.memberInfo?.mobile) {
    nextTick(() => {
      md.sensorComponentLogTake({
        xcxComponentExposure: 'true',
        pageName: `${['首页', '品牌', '积分', '我的'][index]}`,
        componentName: '去授权手机号引导',
        componentContent: '去授权手机号引导',
      });
    });
  }
}

// 处理授权手机号按钮点击
const handleAuthPhoneClick = () => {
  md.sensorComponentLogTake({
    xcxComponentClick: 'true',
    pageName: `${['首页', '品牌', '积分', '我的'][globalStore.curTabIndex]}`,
    componentName: '去授权手机号引导',
    componentContent: '去授权手机号引导',
  });
  jump({
    type: JumpType.INNER,
    url: '/pages/activity/register',
  });
};

// 检查任务结果并更新全局状态
const checkAndUpdateTaskResult = async () => {
  const integralStore = useIntegralStore();
  await integralStore.queryTodoResultServer();
  console.log('queryTodoResult:', integralStore.queryTodoResult);

  if (integralStore.queryTodoResult?.success && integralStore.queryTodoResult?.data?.length > 0) {
    globalStore.isShowTaskComplete = true;
    globalStore.taskCompletePoints = integralStore.queryTodoResult.data[0]?.actualCredits;
    globalStore.taskCompleteTitle = integralStore.queryTodoResult.data[0]?.taskName;
  }
};

onMounted(async () => {
  // globalStore.isShowInvitePrizePanel = true;return
  // globalStore.isShowTaskComplete = true;//?????????
  //任务奖品
  await checkAndUpdateTaskResult();

  // 调用邀请活动首页接口
  const integralStore = useIntegralStore();
  //获取邀请码和奖励
  const res = await integralStore.getOriginInviteHome();

  // const unionId = uni.getStorageSync('unionId');
  const unclaimedPrize = res.data?.unclaimedPrize;

  if (res.success) {
    if (unclaimedPrize) {
      globalStore.isShowInvitePrizePanel = true;
      globalStore.inviteCount = res.data?.invitedCount;
      globalStore.prizeName = unclaimedPrize?.prizeName;
      globalStore.prizeImage = unclaimedPrize?.prizeImageUrl;
      globalStore.prizeType = unclaimedPrize?.prizeType;
      globalStore.memberId = res.data?.memberId;
    }
  }
  console.log('邀请活动首页数据:', res);
});

// 关闭了任务奖励弹窗
const handleCloseTaskCompleteTips = async () => {
  globalStore.isShowTaskComplete = false;
  await checkAndUpdateTaskResult();
};

// 完成任务并显示完成提示
const handleTaskComplete = async (taskIdParam) => {
  taskId.value = 0;
  const integralStore = useIntegralStore();
  const res = await taskCompleteJSON(taskIdParam);

  if (!res.success) {
    uni.showToast({
      title: '完成任务失败',
      icon: 'none',
    });
    return;
  }

  console.log('taskCompleteJSON res:', integralStore.queryTodoResult);
  console.log('integralStore.queryTodoResultServer res:', integralStore.queryTodoResult);
  await integralStore.queryTodoResultServer();
  if (integralStore.queryTodoResult?.success && integralStore.queryTodoResult?.data?.length > 0) {
    globalStore.isShowTaskComplete = true;
    globalStore.taskCompletePoints = integralStore.queryTodoResult.data[0]?.actualCredits;
    globalStore.taskCompleteTitle = integralStore.queryTodoResult.data[0]?.taskName;
  }else{
    console.info('taskCompleteJSON res error:', integralStore.queryTodoResult);
  }
};

onShow(async () => {
  console.log('onShow--index');

  if (!userStore.memberInfo?.mobile) {
    md.sensorComponentLogTake({
      xcxComponentExposure: 'true',
      pageName: `${['首页', '品牌', '积分', '我的'][globalStore.curTabIndex]}`,
      componentName: '去授权手机号引导',
      componentContent: '去授权手机号引导',
    });
  }

  //完成了浏览任务
  if (taskId.value > 0) {
    await handleTaskComplete(taskId.value);
  }
});

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

  // 加载会员信息，确保能正确判断手机号授权状态
  if (userStore.isLogin) {
    userStore.loadMemberInfo();
  }
  if (optionsSync.scene == '1069') {
    isBackApp.value = true;
  } else {
    isBackApp.value = false;
  }

  if (
    options.scene &&
    typeof options.scene === 'string' &&
    (options.scene.startsWith('home_') ||
      options.scene.startsWith('brand_') ||
      options.scene.startsWith('integral_') ||
      options.scene.startsWith('my_'))
  ) {
    const [page] = options.scene.split('_');
    globalStore.setPreviewScene(page, options.scene);
    options.pageType = page;
  }

  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;
    }
  }
});

onShareAppMessage((e) => {
  const pageType = globalStore.curTabIndex;
  console.log('onShareAppMessage pageType:', pageType);
  const integralStore = useIntegralStore();
  if (e.from === 'button') {
    return {
      title: integralStore.originInviteHome?.data?.invitationText,
      path: '/pages/invate/sharepage' + '?inviteCode=' + integralStore.originInviteHome?.data?.invitationCode,
      imageUrl:
      integralStore.originInviteHome?.data?.invitationImageUrl
    };
  }
  return shareOptions[pageType] || shareOptions[0];
});

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

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

// 页面显示时检查会员信息
// onShow(() => {
//   if (userStore.isLogin) {
//     userStore.loadMemberInfo();
//   }
// });

// 邀请奖品弹窗相关方法
// const handleInviteClick = () => {
// 	console.log('邀请按钮点击，显示奖品弹窗');
// 	globalStore.isShowInvitePrizePanel = true;
// };

const handleCloseInvitePrizePanel = () => {
  globalStore.isShowInvitePrizePanel = false;
};

const handleInvitePrizePanelRecord = () => {
  console.log('查看邀请记录');
  globalStore.isShowInvitePrizePanel = false;
  // 这里可以添加跳转到邀请记录页面的逻辑
};

const handleInvitePrizePanelPrize = () => {
  console.log('查看奖品');
  globalStore.isShowInvitePrizePanel = false;
  // 这里可以添加跳转到奖品页面的逻辑
};

// 任务完成弹窗处理方法
const handleCloseTaskComplete = () => {
  globalStore.isShowTaskComplete = false;
};

const handleAcceptTaskComplete = () => {
  //当前未用到
  // console.log('接受任务完成奖励');
  // globalStore.isShowTaskComplete = false;
  // 这里可以添加接受奖励后的逻辑
};

// 任务弹窗处理方法
const handleCloseTaskPop = () => {
  globalStore.closeTaskPop();
};

//去完成按钮，完成任务
const handleTaskClick = async (data) => {
  console.log('任务点击:', data);

  // 如果是完善信息任务，显示TaskPerson弹窗
  if (!data.task) {
    uni.showToast({
      title: '任务不存在',
      icon: 'none',
    });
    return;
  }
  // data.task.taskTodoExtra.type = 'FollowWx'
  taskId.value = 0;
  const res = await taskReceiveJSON(data.task.id);

  if (!res.success) {
    uni.showToast({
      title: '领取任务失败',
      icon: 'none',
    });

    return;
  }
  
  switch (data.task.taskTodoExtra.type) {
    case 'Perfect':
      globalStore.closeTaskPop(); // 先关闭TaskPop
      setTimeout(() => {
        globalStore.showTaskPerson(); // 延迟显示TaskPerson
      }, 100);
      break;
    case 'BROWSE_PAGE': //浏览商城
      globalStore.closeTaskPop();
      taskId.value = data?.task?.id;
      // 这里可以设置任务ID用于后续完成检测
      const extra1 = JSON.parse(data?.task?.taskTodoExtra?.extra);

      if (extra1.type == 'VIDEO') {
        showVideo.value = true;
        currentVideoUrl.value = extra1.url;
      } else if (extra1.type == 'GOODS') {
        let url = `subPackages/shopMainProcess/product/index?productId=${extra1.value}&skuId=${extra1.skuId}&entrySource=xmh_wechatmp_points_north`;
        jump({
          type: JumpType.MINI,
          url: url,
          extra: { envVersion: 'release', appId: 'wx4205ec55b793245e', embedded: true },
        });
      } else if (extra1.type == 'PAGE' || extra1.type == 'MINI_APP') {
        jump({
          type: JumpType.INNER,
          url: extra1.url,
        });
      } else if (extra1.type == 'MINI_APP_THIRD') {
        jump({
          type: JumpType.MINI,
          url: extra1.url,
          extra: { envVersion: 'release', appId: extra1.value, embedded: true },
        });
      } else if (extra1.type == 'SELF_GOODS') {
        jump({
          type: JumpType.INNER,
          url: `/v3/goodDetail/goodDetail?gid=${extra1.value}`,
        });
      } else {
        jump({
          type: JumpType.H5,
          url: extra1.url,
        });
      }

      // console.log('extra66666:', extra1);
      break;
    case 'FirstOrder': //完成首单优选消费
      const extra2 = JSON.parse(data?.task?.taskTodoExtra?.extra);
      console.log('extra666661111:', extra2);
      jump({
        type: JumpType.MINI,
        url: 'subPackages/xmhMainProcess/member/index?entrySource=xmh_wechatmp_points_recgoodsbot',
        extra: { envVersion: 'release', appId: 'wx4205ec55b793245e', embedded: true },
      });
      break;
    case 'EXCHANGE_GOODS': //消费商品
      const extra3 = JSON.parse(data?.task?.taskTodoExtra?.extra);

      if (extra3.length > 0) {
        let url =
          'subPackages/shopMainProcess/product/index?productId={productId}&skuId={skuId}&entrySource=xmh_wechatmp_points_north';
        url = url.replace('{productId}', extra3[0].itemId).replace('{skuId}', extra3[0].skuId);
        jump({
          type: JumpType.MINI,
          url: url,
          extra: { envVersion: 'release', appId: 'wx4205ec55b793245e', embedded: true },
        });
      }
      break;
    case 'FollowWx': //关注公众号
      globalStore.closeTaskPop(); // 先关闭TaskPop
      setTimeout(() => {
        // 设置公众号弹窗参数
        gongzhonghaoTitle.value = '公众号';
        gongzhonghaoDescription.value = '长按关注星妈会公众号,了解更多专业育儿资讯';
        gongzhonghaoQrCodeUrl.value = 'https://course.feihe.com/momclub-picture/homepage/qrcode_gzh.png';
        showGongzhonghaoPop.value = true; // 延迟显示公众号弹窗
      }, 100);
      break;
    case 'AddQw': //添加企业微信
      globalStore.closeTaskPop(); // 先关闭TaskPop
      setTimeout(() => {
        // 设置公众号弹窗参数
        gongzhonghaoTitle.value = '企业微信';
        gongzhonghaoDescription.value = '长按添加星妈管家，享受专家问诊与社群福利活动';
        gongzhonghaoQrCodeUrl.value = 'https://course.feihe.com/momclub-picture/homepage/qrcode_qw.png';
        showGongzhonghaoPop.value = true; // 延迟显示企业微信弹窗
      }, 100);
      break;
    case 'Register': //注册会员
      // 这里可以处理注册逻辑
      uni.showToast({
        title: '请先注册会员',
        icon: 'none',
      });
      break;
    default:
      uni.showToast({
        title: '任务类型不支持',
        icon: 'none',
      });
      break;
  }
};

// 任务信息弹窗处理方法
const handleCloseTaskPerson = () => {
  globalStore.closeTaskPerson();
};

// 关闭公众号弹窗
const handleCloseGongzhonghaoPop = () => {
  showGongzhonghaoPop.value = false;
};

// 处理下载二维码
const handleDownloadQrCode = (title) => {
  console.log('下载二维码', title);
  // 这里可以添加下载二维码的具体逻辑
  // '公众号', '企业微信'
  md.sensorLogTake({
    xcxClick: `${title}拉起半屏二维码入口页面点击`,
    pageName: `${title}拉起半屏二维码入口页面点击`,
    buttonName: `下载二维码`,
  });

  if (title === '公众号') {
    const courseUrl = 'https://course.feihe.com/momclub-picture/homepage/qrcode_gzh.png';
    downloadQrCode(courseUrl);
  } else if (title === '企业微信') {
    const courseUrl = 'https://course.feihe.com/momclub-picture/homepage/qrcode_qw.png';
    downloadQrCode(courseUrl);
  }
};

const downloadQrCode = (imgurl) => {
  //现在二维码图片
  uni.downloadFile({
    url: imgurl,
    success: (downloadRes) => {
      if (downloadRes.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: downloadRes.tempFilePath,
          success: (res) => {
            uni.showToast({
              title: '保存成功',
              icon: 'success',
            });
          },
          fail: (err) => {
            uni.showToast({
              title: '保存失败',
              icon: 'none',
            });
          },
        });
      } else {
        uni.showToast({
          title: '下载失败',
          icon: 'none',
        });
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '下载失败',
        icon: 'none',
      });
    },
  });
};

const handleTaskPersonSubmit = (formData) => {
  console.log('任务信息提交:', formData);
  globalStore.closeTaskPerson();
  // 可以显示成功提示
  uni.showToast({
    title: '信息提交成功',
    icon: 'success',
  });
};

// 视频弹窗相关方法
const closeVideo = async () => {
  //完成了浏览任务
  if (taskId.value > 0) {
    await handleTaskComplete(taskId.value);
  }

  showVideo.value = false;
  currentVideoUrl.value = '';
};

const onVideoLoadedMeta = (e) => {
  const { width, height } = e.detail;
  const pageWidth = uni.upx2px(750);
  const ratio = height / width;
  videoWidth.value = pageWidth;
  videoHeight.value = pageWidth; // pageWidth * ratio;
};

const onVideoPlay = () => {
  console.log('视频播放');
};
</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;
}

/* 悬浮授权手机号模块样式 */
.auth-phone-module {
  position: fixed;
  bottom: 200rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 698rpx;
  height: 96rpx;
  z-index: 998;
  // position: relative;
  border-radius: 44rpx;
  overflow: hidden;
}

.auth-phone-bg {
  width: 100%;
  height: 100%;
  display: block;
}

.auth-phone-btn-container {
  position: absolute;
  bottom: 18rpx;
  right: 40rpx;
}

.auth-phone-btn {
  width: 160rpx;
  height: 60rpx;
  display: block;
}

.auth-phone-btn:active {
  transform: scale(0.95);
}

.video-popup1 {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.close-btn-bottom {
  margin: 32rpx auto 0 auto;
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 44rpx;
  line-height: 64rpx;
  text-align: center;
  z-index: 10001;
}
</style>
