<template>
  <view class="activity-page" v-if="!loading" :style="bgStyle">
    <!-- 返回按钮 -->
    <view class="nav-left">
      <image class="back-btn" src="@/assets/images/backBtn.png" mode="aspectFit"
             @click="handleBack"/>
    </view>

    <template v-for="(component, index) in pageConfig.components" :key="'comp-' + index">
      <ImageSwiper
        v-if="component.type === 'image-swiper'"
        v-bind="component"
        :activity-data="activityInfo"
      />
      <ClickArea
        v-else-if="component.type === 'click-area'"
        v-bind="component"
        debug-mode
        :activity-data="activityInfo"
      />
      <InviteTask
        v-else-if="component.type === 'invite-task'"
        v-bind="component"
        :debug-mode="false"
        :activity-data="activityInfo"
      />
    </template>

    <GotPrizeModal :visible="showGotPrizeModal" :award-name="currentAwardName" :award-image-url="currentAwardImageUrl"
                  @close="handleGotPrizeModalClose" @happy-get="handleHappyGet"/>
  </view>

</template>

<script setup lang="ts">
import {ref, onMounted, computed, getCurrentInstance, provide} from 'vue'
import {fetchPageConfig, fetchActivityInfo, invitationAssist} from '../api.ts'
import {useHomeStore} from '@/stores/home'; // Assuming homeStore path
import {useUserStore} from '@/stores/user'; // Import userStore
import {jump, JumpType} from '@/utils/index.js'; // Import jump function
import GotPrizeModal from '../components/GotPrizeModal.vue'; // Import GotPrizeModal if needed
import md from '@/md.js';
import ClickArea from "../components/ClickArea.vue";
import ImageSwiper from "../components/ImageSwiper.vue";
import './index.less'
import InviteTask from "../components/InviteTask.vue";
import {ActivityInfo} from "../types";

// 响应式数据
const pageConfig = ref({}) // 配置对象
const loading = ref(true) // 加载状态

// 邀请相关数据
const showGotPrizeModal = ref(true);
const currentAwardName = ref('');
const currentAwardImageUrl = ref('');
const isLogin = ref(false);
const activityInfo = ref<ActivityInfo>(undefined)
const shareData = ref({
  title: '星妈会超级品牌周来啦！',
  imageUrl: 'https://course.feihe.com/momclub-picture/Act915Page/v2/act915ShareImg.png',
  path: '/activities/1015/home/index',
})

// 获取store实例
const homeStore = useHomeStore();
const userStore = useUserStore();

function updateShareData(data) {
  shareData.value = data
}

// 获取背景样式的辅助函数
const bgStyle = computed(() => {
  const backgroundImage = pageConfig.value?.background?.image
  if (backgroundImage) {
    // 获取全局属性
    const {proxy} = getCurrentInstance()
    const $baseUrl = proxy.$baseUrl
    return {
      //backgroundImage: `url(${$baseUrl}${backgroundImage})`
      backgroundImage: `url(${backgroundImage})`
    }
  } else {
    // 如果背景图片不存在，使用渐变背景
    return {
      background: `linear-gradient(to bottom, ${pageConfig.value?.background?.color}, ${pageConfig.value?.background?.color2})`
    }
  }
})

// 定义分享函数
const getShareData = (type) => {
  console.log('getShareData 被调用', type)

  const {title, imageUrl, path} = shareData.value

  const sharePath = type.from == 'button' ? `${path}?invitationCode=${invitationCode.value}` : path

  console.log('分享参数:', {
    title,
    path: sharePath,
    imageUrl,
    invitationCode: invitationCode.value,
  })

  return {
    title,
    path: sharePath,
    imageUrl,
  }
}

// 返回按钮处理
const handleBack = () => {
  console.log('点击返回按钮')

  try {
    uni.navigateBack({
      delta: 1,
      success: () => {
        console.log('返回成功')
      },
      fail: () => {
        // 如果返回失败，跳转到首页
        uni.redirectTo({
          url: '/pages/index/index'
        })
      }
    })
  } catch (error) {
    console.log('返回失败:', error)
    uni.redirectTo({
      url: '/pages/index/index'
    })
  }
}

// 获取配置数据
const updatePageConfig = async () => {
  try {
    loading.value = true
    const response = await fetchPageConfig()

    if (response && response.data) {
      pageConfig.value = response.data

      updateShareData(pageConfig.value.shareConfig)
    }
  } finally {
    loading.value = false
  }
}

const updateActivityInfo = async () => {
  try {
    console.log('开始请求 fetchActivityInfo 接口...')
    const response = await fetchActivityInfo()
    console.log('fetchActivityInfo 接口返回结果:', response)

    if (response && response.ok && response.data) {
      const data = response.data
      activityInfo.value = data

      isLogin.value = !data.notLogin
      invitationCode.value = data.invitationCode
    }

    return response
  } catch (error) {
    console.error('getAct915Home 接口请求失败:', error)
    return null
  }
}

// 显示奖品弹窗
const showPrizeModal = () => {
  if (unclaimedPrizes.value.length > 0) {
    // 计算总奖品数量
    const totalQuantity = unclaimedPrizes.value.reduce((sum, prize) => sum + (prize.quantity || 1), 0)
    const firstPrize = unclaimedPrizes.value[0]
    currentAwardName.value = `${firstPrize.prizeName} × ${totalQuantity}`
    currentAwardImageUrl.value = firstPrize.prizeImageUrl
    showGotPrizeModal.value = true
  }
}

const handleLotteryClick = () => {
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "1015专题活动首页",
    componentName: "中部抽奖banner",
    componentContent: "中部抽奖banner"
  });
  // 从配置中获取抽奖banner链接
  const lotteryLink = pageConfig.value?.lottery?.link
  if (lotteryLink) {
    jump(lotteryLink)
  } else {
    uni.navigateTo({
      url: '/activity01015/lottery/lottery'
    })
  }
}

// 页面初始化逻辑
const initPage = async () => {
  console.log('开始初始化页面...')

  // 获取页面配置
  await updatePageConfig()

  console.log('配置数据:', pageConfig.value)

  // 请求 getAct915Home 接口（包含助力逻辑处理）
  await updateActivityInfo();

  if (unclaimedPrizes.value?.length > 0) {
    showPrizeModal()
  }
}

// 生命周期
onMounted(async () => {
  console.log('1015活动页面已加载')

  // 先进行自动登录获取基础信息，登录成功后执行页面初始化
  try {
    console.log('开始执行 normalAutoLogin...')
    await userStore.normalAutoLogin(initPage)
    console.log('normalAutoLogin 完成')
  } catch (error) {
    console.error('normalAutoLogin 失败:', error)
    // 即使登录失败也执行页面初始化
    await initPage()
  }

  // 先隐藏朋友圈分享
  uni.hideShareMenu({
    menus: ['shareTimeline']
  })

  // 显示分享菜单
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage']
  });
});

// Phone authorization
const onGetPhoneNumber = async (e) => {
  console.log('onGetPhoneNumber', e.detail)
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  const incomingCode = options.invitationCode;

  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    try {
      // console.warn('onGetPhoneNumber', e.detail)
      // 隐藏授权弹窗
      userStore.phoneCallback(e.detail, null, null, async () => {
        // 重新获取用户信息（登录后）
        await updateActivityInfo();

        console.warn('授权后重新获取用户信息')
      }, {
        wxLoginBusinessDTO: {
          activityUserInvite1015Code: incomingCode
        }
      })
    } catch (error) {
      console.error('授权后处理失败:', error)
      uni.showToast({title: '授权失败', icon: 'none'});
    }
  } else {
    uni.showToast({title: '授权失败', icon: 'none'});
  }
};

// 抽奖成功弹窗关闭处理
const handleGotPrizeModalClose = () => {
  console.log('关闭抽奖成功弹窗');
  showGotPrizeModal.value = false;
};

// 开心领取处理
const handleHappyGet = () => {
  console.log('点击开心领取');
  showGotPrizeModal.value = false;
  // uni.showToast({
  // 	title: '奖品领取成功',
  // 	icon: 'success'
  // });
};

// 暴露给 Options API 使用
defineExpose({
  getShareData
})

provide('pageName', '1015专题活动首页')
provide('isLogin', isLogin)
provide('updateShareData', updateShareData)
provide('updateActivityInfo', updateActivityInfo)
provide('onGetPhoneNumber', onGetPhoneNumber)
</script>

<script lang="ts">
// 微信小程序分享配置 - 使用 Options API
export default {
  // 自定义分享内容
  onShareAppMessage(event) {
    console.log('onShareAppMessage 被调用', event)
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const pageInstance = currentPage.$vm
    return pageInstance.getShareData(event)
  },
}
</script>
