<script setup lang="ts">
import {ref, provide} from 'vue'
import PageRenderEngine from "./engine/PageRenderEngine.vue";
import {onLoad, onShareAppMessage, onShareTimeline} from "@dcloudio/uni-app";
import {fetchPageConfig} from "./engine/api";
import {PageConfig} from "./engine/types";
import {useUserStore} from "@/stores/user";

const userStore = useUserStore();

const pageOptions = ref({})
const pageId = ref<string>()
const debugMode = ref(false)
const shareData = ref({
  title: '星妈会',
  imageUrl: 'https://course.feihe.com/momclub-picture/activity/1015/v1/share-image.png',
  path: '/pages/activity/page',
})
const refreshingPageConfig = ref(false)
const pageConfig = ref<PageConfig>()


function navBack() {
  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'
    })
  }
}

function updateShareData(data) {
  Object.assign(shareData.value, data)
}

async function refreshPageConfig() {
  refreshingPageConfig.value = true
  const resp = await fetchPageConfig(pageId.value)
  pageConfig.value = JSON.parse(resp.data.content)
  refreshingPageConfig.value = false
  console.log(pageConfig.value)

  updateShareData({
    title: pageConfig.value?.shareConfig?.title,
    imageUrl: pageConfig.value?.shareConfig?.cover,
  })
}

function getShareData() {
  const {title, imageUrl, path} = shareData.value

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

  return {
    title,
    path,
    imageUrl,
  }
}

onLoad(async (options) => {
  pageOptions.value = options
  pageId.value = options.id
  debugMode.value = options.debugMode

  shareData.value.path = '/pages/activity/page?id=' + pageId.value

  await userStore.normalAutoLogin()
  await userStore.loadUserInfo()

  await refreshPageConfig()
})

onShareAppMessage(() => {
  return getShareData()
})

onShareTimeline(() => {
  return getShareData()
})

provide('updateShareData', updateShareData)
</script>

<template>
  <PageRenderEngine
    v-if="!refreshingPageConfig"
    :id="pageId"
    :page-config="pageConfig"
    :debug-mode="debugMode"
  />
  <view v-else class="loading-view">
    <text>加载中…</text>
  </view>
  <image class="btn-back" src="@/assets/images/back-btn.png" mode="aspectFit" @click="navBack"/>
</template>

<style scoped lang="less">
.btn-back {
  position: fixed;
  left: 20rpx;
  top: 70rpx;
  width: 60rpx;
  height: 60rpx;
}

.loading-view{
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>