<template>
	<view class="xingmalabdetailpage modal_center" :class="pageClass">
		<!-- <span class="xingmalabdetailpagebg"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.background)})` }"></span> -->

		<!-- 左上角头部区域 - 脱离滚动 -->
		<div class="xingmalabdetailpageheader">
			<!-- 返回按钮 -->
			<span class="xingmalabdetailpagebackbtn"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.backBtn)})` }"
				@click="handleGoBack"></span>

			<!-- 用户信息 -->
			<div class="xingmalabdetailpageuserinfo">
				<image v-if="detailData.avatar" :src="detailData.avatar" class="xingmalabdetailpageavatar"
					mode="aspectFit" />
				<span class="xingmalabdetailpagenickname">{{ detailData.nickname || '星妈用户' }}</span>
			</div>
		</div>

		<!-- 文本和时间容器 -->
		<div class="xingmalabdetailpagecontent">
			<span class="xingmalabdetailpagetext">{{
				detailData.content
				|| config.texts.title }}</span>
			<span class="xingmalabdetailpagetime" v-if="detailData.owner && detailData.gmtCreate">
				{{ formatTime(detailData.gmtCreate) }}
			</span>
		</div>
		<span class="xingmalabdetailpagepicbg"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.picBg)})` }"></span>
		<image v-if="detailData.imgUrl" :src="detailData.imgUrl" class="xingmalabdetailpagepic" mode="aspectFit" />
		<span class="xingmalabdetailpagenum">{{ config.texts.collectionNumber }}{{ detailData.bizNo || collectionNumber
		}}</span>
		<div class="xingmalabdetailpagebottomcon" v-if="detailData.state === 1">
			<span class="xingmalabdetailpagebottomconbg"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.bottomConBg)})` }"></span>

			<!-- 收藏按钮 -->
			<span class="xingmalabdetailpagebottomconlikebtn" :class="{ liked: detailData.collection }"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(detailData.collection ? config.images.bottomConLikeBtnSel : config.images.bottomConLikeBtn)})` }"
				@click="handleLikeClick"></span>

			<!-- 分享按钮 -->
			<view class="xingmalabdetailpagebottomconsharebtn"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.bottomConShareBtn)})` }"
				@click="handleShareClick"></view>

			<!-- 未登录时覆盖的授权按钮层 -->
			<div v-if="homeStore && !homeStore.isLogin" class="auth-overlay">
				<!-- 收藏按钮授权覆盖 -->
				<button open-type="getPhoneNumber" @getphonenumber="(e) => onGetPhoneNumber(e, 'like')"
					class="auth-like-btn phone-auth-btn-cover"></button>

				<!-- 分享按钮授权覆盖 -->
				<button open-type="getPhoneNumber" @getphonenumber="(e) => onGetPhoneNumber(e, 'share')"
					class="auth-share-btn phone-auth-btn-cover"></button>
			</div>
		</div>
		
		<!-- 分享弹窗 -->
		<XingmaLabSharePopup 
			:visible="showSharePopup"
			@close="handleCloseSharePopup"
			@shareToFriend="handleShareToFriend"
			@generatePoster="handleGeneratePoster" />
		
		<!-- 海报页面 -->
		<XingmaLabPosterPage 
			:visible="showPosterPage"
			:imageUrl="detailData.imgUrl"
			:content="detailData.content || '可爱'"
			:collectionNumber="detailData.bizNo || collectionNumber"
			:defaultNickname="detailData.nickname || '星妈用户'"
			:avatar="detailData.avatar || ''"
			:recordId="recordId || detailData.id || ''"
			@close="handleClosePosterPage"
			@download="handleDownloadPoster" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed,
		onUnmounted
	} from 'vue'
	import {
		xingmaLabDetailConfig,
		getImageUrl
	} from './config.js'
	import {
		fetchRecordDetail,
		fetchFavoriteAdd,
		fetchFavoriteRemove
	} from '@/api/xingmaLab.js'
	import {
		useHomeStore
	} from '@/stores/home.js'
	import {
		useUserStore
	} from '@/stores/user.js'
	import md from '../../md';
	import XingmaLabSharePopup from '@/components/xingmaLab/XingmaLabSharePopup.vue'
	import XingmaLabPosterPage from '@/components/xingmaLab/XingmaLabPosterPage.vue'

	// 组件名称
	defineOptions({
		name: 'XingmaLabDetailPage'
	})

	// 响应式数据
	const collectionNumber = ref('')
	const recordId = ref('') // 添加记录ID的响应式变量
	const detailData = ref({
		content: '',
		gmtCreate: '',
		owner: false,
		imgUrl: '',
		nickname: '',
		avatar: '',
		collection: false,
		bizNo: '',
		state: null
	})
	
	// 分享弹窗和海报页面状态
	const showSharePopup = ref(false)
	const showPosterPage = ref(false)

	// 配置对象
	const config = xingmaLabDetailConfig
	
	const isSinglePageMode = ref(false)

	// 计算属性动态返回类名
	const pageClass = computed(() => {
		return isSinglePageMode.value ? 'page2' : 'page1'
	})
	
	// 格式化时间
	const formatTime = (timeStr) => {
		if (!timeStr) return ''
		const date = new Date(timeStr)
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		return `${year}-${month}-${day} `
	}

	// 同步收藏状态到上一页
	const syncCollectionStatusToPrevPage = () => {
		const pages = getCurrentPages()
		if (pages.length > 1) {
			let prevPage = pages[pages.length - 2]
			prevPage.setData({
				isFavorite: detailData.value.collection ? 1 : -1
			})
			console.log('✅ 收藏状态已同步到上一页:', detailData.value.collection ? 1 : -1)
		}
	}

	// 获取详情数据
	const fetchDetailData = async (id) => {
		try {
			uni.showLoading({
				title: '加载中...',
				mask: true
			})

			const result = await fetchRecordDetail({
				id
			})

			if (result.success) {
				detailData.value = result.data
				recordId.value = id // 保存记录ID
				console.log('✅ 详情数据获取成功:', detailData.value)

				// 初始化时同步收藏状态到上一页
				syncCollectionStatusToPrevPage()
			} else {
				throw new Error(result.message || '获取详情失败')
			}
		} catch (error) {
			console.error('❌ 获取详情失败:', error)
			uni.showToast({
				title: error.message || '获取详情失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	// 获取 stores
	const homeStore = useHomeStore()
	const userStore = useUserStore()

	// 手机号授权回调
	const onGetPhoneNumber = (e, action) => {
		if (e.detail.errMsg !== 'getPhoneNumber:ok') {
			uni.showToast({
				title: '请授权使用手机号',
				icon: 'none',
			});
			return;
		}
		console.log('detail', e.detail, 'action:', action);

		// 调用手机号授权回调
		userStore.phoneCallback(e.detail, null, null, () => {
			// 授权成功后，根据点击的按钮执行相应功能
			if (action === 'like') {
				handleLikeClick();
			} else if (action === 'share') {
				handleShareClick();
			}
		});
	}

	// 方法
	const handleLikeClick = async () => {

		//TODO:埋点
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab-藏品详情页",
			componentName: "藏品详情",
			componentContent: "收藏"
		});

		try {
			const recordId = detailData.value.id
			if (!recordId) {
				uni.showToast({
					title: '记录ID不存在',
					icon: 'none'
				})
				return
			}

			if (detailData.value.collection) {
				// 取消收藏
				const result = await fetchFavoriteRemove({
					relationId: recordId
				})
				if (result.success) {
					detailData.value.collection = false
					// 更新时同步收藏状态到上一页
					syncCollectionStatusToPrevPage()
					uni.showToast({
						title: '已取消收藏',
						icon: 'none'
					})
				} else {
					throw new Error(result.message || '取消收藏失败')
				}
			} else {
				// 添加收藏
				const result = await fetchFavoriteAdd({
					relationId: recordId
				})
				if (result.success) {
					detailData.value.collection = true
					// 更新时同步收藏状态到上一页
					syncCollectionStatusToPrevPage()
					uni.showToast({
						title: '收藏成功',
						icon: 'none'
					})
				} else {
					throw new Error(result.message || '收藏失败')
				}
			}
		} catch (error) {
			console.error('收藏操作失败:', error)
			uni.showToast({
				title: error.message || '操作失败，请重试',
				icon: 'none'
			})
		}
	}

	const handleShareClick = () => {
		// 显示分享弹窗
		showSharePopup.value = true
		
		// 埋点
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab-藏品详情页",
			componentName: "藏品详情",
			componentContent: "分享"
		});
	}
	
	// 关闭分享弹窗
	const handleCloseSharePopup = () => {
		showSharePopup.value = false
	}
	
	// 分享给好友
	const handleShareToFriend = () => {
		// 埋点
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab-藏品详情页",
			componentName: "分享弹窗",
			componentContent: "分享给好友"
		});
		// 分享功能由 button 的 open-type="share" 自动触发
	}
	
	// 生成分享海报
	const handleGeneratePoster = () => {
		showPosterPage.value = true
		
		// 埋点
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab-藏品详情页",
			componentName: "分享弹窗",
			componentContent: "生成分享海报"
		});
	}
	
	// 关闭海报页面
	const handleClosePosterPage = () => {
		showPosterPage.value = false
	}
	
	// 下载海报
	const handleDownloadPoster = (data) => {
		// TODO: 实现海报下载逻辑
		// 可以使用 canvas 将海报内容绘制成图片，然后保存到相册
		console.log('下载海报', data)
	}


	// 返回上一页
	const handleGoBack = () => {
		// 检查是否有上一页
		const pages = getCurrentPages()

		console.log('pages', pages)
		if (pages.length > 1) {
			// 有上一页，直接返回上一页（收藏状态已在更新时同步）
			uni.navigateBack({
				delta: 1
			})
		} else {
			// 没有上一页，跳转到星妈实验室页面，并传递index参数
			uni.redirectTo({
				url: `/pages/xingmaLab/xingmaLab`
			})
		}
	}

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

		md.sensorComponentLogTake({
			xcxComponentExposure: "true",
			pageName: "星妈lab-藏品详情页",
			componentName: "藏品详情",
			componentContent: "收藏"
		});

		md.sensorComponentLogTake({
			xcxComponentExposure: "true",
			pageName: "星妈lab-藏品详情页",
			componentName: "藏品详情",
			componentContent: "分享"
		});

		// 调用 home 接口获取登录状态
		await homeStore.loadHomeInfo()

		// 获取页面跳转参数中的 id 和 index
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		console.log('🔍 currentPage:', currentPage);
		const id = currentPage.options?.id || ''
		if (id) {
			console.log('🔍 获取到页面参数 id:', id)
			recordId.value = id // 立即保存ID，确保分享时能获取到
			await fetchDetailData(id)

			md.sensorComponentLogTake({
				xcxComponentExposure: "true",
				pageName: "星妈lab-藏品详情页",
				componentName: "藏品详情",
				componentContent: "藏品详情页+" + detailData.value.content
			});
		} else {
			console.warn('⚠️ 未获取到页面参数 id', currentPage.options)
			// uni.showToast({
			// 	title: '参数错误',
			// 	icon: 'none'
			// })
			// uni.redirectTo({
			// 	url: `/pages/xingmaLab/xingmaLab`
			// })
		}

		// uni.hideShareMenu({
		// 	menus: ['shareTimeline']
		// })
		// 启用分享菜单（仅限分享给好友，禁用朋友圈）
		uni.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		})
	}

	// 生命周期
	onMounted(async (options) => {
		console.log('星妈lab详情页面已加载')

		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		console.log('🔍 🚀 启动参数currentPage.options:', currentPage.options);

		const optionsSync = wx.getEnterOptionsSync()
		if (optionsSync.scene == '1154') { //朋友圈分享点进来的
			console.log("📱 单页模式（通过启动参数检测）")
			isSinglePageMode.value = true;
			detailData.value = {
				...detailData.value, // 保持原有结构
				...currentPage.options, // 合并传入的参数
				state: 0 // state=0是为了不显示按钮区
			}
		} else {
			console.log('🔍 正常模式')

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

	// 定义分享函数
	const getShareData = () => {
		const shareImage = detailData.value.imgUrl || ''
		const shareContent = detailData.value.content || ''
		const currentRecordId = recordId.value || detailData.value.id || ''

		// 截取分享文案，超出字数显示省略号
		const maxLength = 50
		const truncatedContent = shareContent.length > maxLength ?
			shareContent.substring(0, maxLength) + '...' :
			shareContent

		console.log('分享参数:', {
			title: truncatedContent,
			imageUrl: shareImage,
			path: `/pages/XingmaLabDetailPage/XingmaLabDetailPage?id=${currentRecordId}`,
			recordId: currentRecordId,
			detailDataId: detailData.value.id
		})

		return {
			title: truncatedContent,
			imageUrl: shareImage,
			path: `/pages/XingmaLabDetailPage/XingmaLabDetailPage?id=${currentRecordId}`
		}
	}

	// 获取朋友圈分享数据
	const getShareTimelineData = () => {
		const shareImage = detailData.value.imgUrl || ''

		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage.options || {}
		const id = options.id || ''

		return {
			title: detailData.value.content,
			query: `id=${id}&content=${detailData.value.content}&bizNo=${detailData.value.bizNo}&avatar=${detailData.value.avatar}&nickname=${detailData.value.nickname}&imgUrl=${detailData.value.imgUrl}`,
			imageUrl: shareImage
		}
	}

	// 暴露给 Options API 使用
	defineExpose({
		getShareData,
		getShareTimelineData
	})
</script>

<script>
	// 微信小程序分享配置 - 使用 Options API
	export default {
		// 自定义分享内容
		onShareAppMessage() {
			console.log('onShareAppMessage 被调用')

			// 获取当前页面的数据
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			const options = currentPage.options || {}
			const id = options.id || ''

			// 获取页面实例
			const pageInstance = currentPage.$vm
			if (pageInstance && pageInstance.getShareData) {
				return pageInstance.getShareData()
			}

			// 如果无法获取页面实例，返回默认分享内容
			return {
				title: '',
				path: `/pages/XingmaLabDetailPage/XingmaLabDetailPage?id=${id}`,
				imageUrl: ''
			}
		},

		// 朋友圈分享已禁用
		onShareTimeline() {
			console.log('onShareTimeline 被调用')
			// 获取当前页面的数据
			// const pages = getCurrentPages()
			// const currentPage = pages[pages.length - 1]
			// const options = currentPage.options || {}
			// const id = options.id || ''
			// // 朋友圈分享功能已禁用
			// return {
			// 	title: '分享到朋友圈的标题',
			// 	query: `content=${detailData.value.content}&bizNo=${detailData.value.bizNo}&avatar=${detailData.value.avatar}&nickname=${detailData.value.nickname}&imgUrl=${detailData.value.imgUrl}`,
			// 	imageUrl: ''
			// }
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			const pageInstance = currentPage.$vm

			if (pageInstance && pageInstance.getShareTimelineData) {
				return pageInstance.getShareTimelineData()
			}

			// 备用方案
			const options = currentPage.options || {}
			const id = options.id || ''
			return {
				title: '',
				query: `id=${id}`,
				imageUrl: ''
			}
		}
	}
</script>

<style lang="less" scoped>
	@import './XingmaLabDetailPage.less';
</style>