<!--
Webview页面使用说明：

1. 基本使用：
   uni.navigateTo({
     url: '/pages/syWebview/syWebview?url=' + encodeURIComponent('https://example.com')
   });

2. 带标题的使用：
   uni.navigateTo({
     url: '/pages/syWebview/syWebview?url=' + encodeURIComponent('https://example.com') + '&title=' + encodeURIComponent('页面标题')
   });

3. 分享功能：
   - 页面会自动接收webview发送的消息
   - 消息格式：{ title: '标题', link: '链接', imgUrl: '图片', desc: '描述' }
   - 支持数组格式：[{ title: '标题', link: '链接', imgUrl: '图片', desc: '描述' }]

4. 分享数据示例：
   {
     title: '分享标题',
     link: 'https://example.com/share',
     imgUrl: 'https://example.com/image.jpg',
     desc: '分享描述'
   }
-->

<template>
	<view class="webview-container">
		<!-- Webview内容 -->
		<web-view :src="webviewUrl" @message="getMessage" class="webview-content"></web-view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user.js'
import { useGlobalStore } from '../../stores/global'
import { fetchSyWebviewJSON } from '../../api/sywebview'
import { onLoad, onShareAppMessage, onShareTimeline, onPageScroll } from "@dcloudio/uni-app";
import md from '../../md';


// 响应式数据
const statusBarHeight = ref(0)
const webviewUrl = ref('')
const share = ref(null) // 分享数据

// 获取用户store
const userStore = useUserStore()
const globalStore = useGlobalStore()

// 登录获取 cuk
const wxAutoLogin = async () => {
	await new Promise(resolve => {
		userStore.syWxAutoLogin(resolve)
	})
}

// 接收webview消息
const getMessage = (e) => {
	console.log('=== Webview 消息接收开始 ===')
	console.log('完整事件对象:', e)
	console.log('事件详情:', e.detail)

	// 尝试多种方式获取数据
	let messageData = null

	// 方式1：从 e.detail.data 获取
	if (e.detail && e.detail.data) {
		messageData = e.detail.data
		console.log('从 e.detail.data 获取到数据:', messageData)
	}

	if (messageData) {
		console.log('消息数据类型:', typeof messageData)
		console.log('消息数据是否为数组:', Array.isArray(messageData))

		share.value = messageData[messageData.length - 1]


	}

}

// 页面参数接收
onLoad(async (options) => {
	console.log('页面参数:', options)

	wx.showShareMenu({
		withShareTicket: true,
		menus: ['shareAppMessage', 'shareTimeline']// shareAppMessage表示“发送给朋友”按钮，shareTimeline表示“分享到朋友圈”按钮 
	})
	console.warn("wx", wx.showShareMenu)
	// 获取状态栏高度
	const systemInfo = uni.getSystemInfoSync()
	statusBarHeight.value = systemInfo.statusBarHeight || 0

	// 确保登录以获取 cuk
	await wxAutoLogin()

	const res = await fetchSyWebviewJSON()
	console.log('res', res)

	if (!res.data.url) {
		uni.redirectTo({
			url: '/pages/index/index'
		})
		return
	}

	let baseUrl = res.data.url
	const cuk = globalStore.cuk
	const openId = globalStore.openId
	const unionId = globalStore.unionId

	// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
	const scene = decodeURIComponent(decodeURIComponent(options.scene))
	options.scene = null

	console.warn("scene", scene)

	// 将 options 的所有参数原样作为查询参数传给 H5，并补齐 cuk
	const params = { ...(options || {}) }
	if (cuk && !params.cuk) params.cuk = cuk
	// 添加用户信息参数
	if (openId && !params.openId) params.openId = openId
	if (unionId && !params.unionId) params.unionId = unionId

	const paramStr = Object.keys(params)
		.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
		.map(key => `${key}=${encodeURIComponent(params[key])}`)
		.join('&')

	// p 渠道参数
	// openId 用户openid
	// unionId 用户unionid
	// cuk 
	// shareToken 分享人token
	// pt 分享海报人token

	// 示例：
	// https://25niansuyuan.feihe.com/projects/Firmus/dev/index?p=xmh&openId=用户openid&unionId=用户unionid&&pt=yzhd123&shareToken=yzhd123&cuk=12121



	if (scene) {
		if (scene[0] === '?') {
			baseUrl += scene
		} else {
			baseUrl += `?${scene}`
		}
	}

	webviewUrl.value = paramStr
		? baseUrl + (baseUrl.includes('?') ? '&' : '?') + paramStr
		: baseUrl

	console.log('Webview页面加载，URL:', webviewUrl.value, paramStr, cuk, openId, unionId)
})

// 分享功能
onShareAppMessage((options) => {
	console.log('分享数据:', share.value)
	console.log('分享选项:', options)

	debugger;

	md.sensorLogTake({
		xcxClick: "suyuan202508H5Click",
		pageName: "星妈会分享页",
		buttonName: "星妈会分享出",
	});
	if (share.value) {
		const shareurl = share.value.shareUrl
		const title = share.value.shareTitle
		const imageUrl = share.value.shareImageUrl

		console.log('使用分享数据:1', { title, shareurl, imageUrl })

		return {
			title: title,
			path: shareurl || '/pages/index/index',
			imageUrl: imageUrl || '',
			success: function (res) {
				console.log('分享成功:', res)
				//星妈会埋点方法，用户分享成功后触发事件

			},
			fail: function (res) {
				console.log('分享失败:', res)
			},
			complete: function (res) {
				console.log('分享完成:', res)
			}
		}
	}

	// 如果没有分享数据，返回默认分享
	return {
		path: '/pages/index/index'
	}
})

onShareTimeline((options) => {
	console.log('分享朋友圈数据:', share.value)
	md.sensorLogTake({
		xcxClick: "suyuan202508H5Click",
		pageName: "星妈会分享页",
		buttonName: "星妈会分享出",
	});
	if (share.value) {
		const shareurl = share.value.shareUrl
		const title = share.value.shareTitle
		const imageUrl = share.value.shareImageUrl

		console.log('使用分享数据:', { title, shareurl, imageUrl })

		return {
			title: title || '分享',
			path: shareurl || '/pages/index/index',
			imageUrl: imageUrl || '',
			success: function (res) {
				//星妈会埋点方法，用户分享成功后触发事件

				console.log('分享成功:', res)
			},
			fail: function (res) {
				console.log('分享失败:', res)
			},
			complete: function (res) {
				console.log('分享完成:', res)
			}
		}
	}

	// 如果没有分享数据，返回默认分享
	return {
		path: '/pages/index/index'
	}
})

</script>

<style lang="less" scoped>
.webview-container {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #fff;
}

.webview-content {
	flex: 1;
	width: 100%;
}
</style>
