<template>
  <view class="activity-page" v-if="!loading" :style="bgStyle">
    <!-- 返回按钮 -->
    <view class="nav-left">
      <image class="back-btn" src="@/assets/images/back-btn.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"
        :is-login="isLogin"
        :debug-mode="DEBUG_MODE"
      />
      <ClickArea
        v-else-if="component.type === 'click-area'"
        v-bind="component"
        :is-login="isLogin"
        @getphonenumber="onGetPhoneNumber"
        :debug-mode="DEBUG_MODE"
      />
      <InviteTask
        v-else-if="component.type === 'invite-task'"
        v-bind="component"
        :is-login="isLogin"
        :debug-mode="DEBUG_MODE"
      />
    </template>
  </view>

</template>

<script setup lang="ts">
import {ref, onMounted, computed, getCurrentInstance, provide} from 'vue'
import {fetchPageConfig} from './api.ts'
import {useUserStore} from '@/stores/user';
import ClickArea from "./components/ClickArea.vue";
import ImageSwiper from "./components/ImageSwiper.vue";
import InviteTask from "./components/InviteTask.vue";
import { hideLoading, showLoading } from "@/utils";

const DEBUG_MODE = false

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

// 邀请相关数据
const shareData = ref({
  title: '星妈会超级品牌周来啦！',
  imageUrl: 'https://course.feihe.com/momclub-picture/activity/1015/v2/share-image.png',
  path: '/pages/activity/1015/home',
})

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

const isLogin = computed(()=>{
  //return false
  return userStore.isLogin
})

function updateShareData(data) {
  console.log('updateShareData:', data)
  Object.assign(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 = (event) => {
  console.log('getShareData 被调用', event)

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

  const pathToUse = event.from == 'button' ? pathWithCode : path

  console.log('分享参数:', {
    title,
    pathToUse,
    imageUrl,
  })

  return {
    title,
    path: pathToUse,
    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()
    //console.log('获取到的配置数据:', JSON.stringify(response.data, null, 2))

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

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

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

  await Promise.all([
    userStore.loadUserInfo(),
  ])
  // 获取页面配置
  await updatePageConfig()

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

// 生命周期
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)
  showLoading('授权中...')
  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 () => {
        hideLoading()
        // 重新获取用户信息（登录后）getphonenumber
        await Promise.all([
          userStore.loadUserInfo(),
          userStore.loadMemberInfo(),
        ])
        console.warn('授权后重新获取用户信息')
      }, {
        wxLoginBusinessDTO: {
          activityUserInvite915Code: incomingCode
        }
      })
    } catch (error) {
      hideLoading()
      console.error('授权后处理失败:', error)
      uni.showToast({title: '授权失败', icon: 'none'});
    }
  } else {
    hideLoading()
    uni.showToast({title: '授权失败', icon: 'none'});
  }
};

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

provide('pageName', '1015专题活动首页')
provide('updateShareData', updateShareData)
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>

<style scoped lang="less">
.activity-page {
  width: 750rpx;
  height: calc(4937rpx + 845rpx);
  position: relative;
  max-width: 100vw; // 确保不超过视口宽度
  overflow-x: hidden; // 防止水平滚动
  background-size: contain;
  background-repeat: no-repeat;
  background-position: left 845rpx;

  // 返回按钮样式
  .nav-left {
    position: fixed;
    top: 100rpx;
    left: 30rpx;
    z-index: 999;

    .back-btn {
      width: 60rpx;
      height: 60rpx;
    }
  }
}
</style>
