<template>
	<view class="xingmalabdetailpage modal_center">
		<!-- <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>

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

			<!-- 未登录时覆盖的授权按钮层 -->
			<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>

				<!-- 分享按钮授权覆盖 - 移除这个，让分享按钮正常工作 -->
			</div>
		</div>
	</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';

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

// 响应式数据
const collectionNumber = ref('123456789')
const recordId = ref('') // 添加记录ID的响应式变量
const detailData = ref({
	content: '',
	gmtCreate: '',
	owner: false,
	imgUrl: '',
	nickname: '',
	avatar: '',
	collection: false,
	bizNo: '',
	state: null
})

// 配置对象
const config = xingmaLabDetailConfig


// 格式化时间
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).then(() => {
		// 授权成功后，根据点击的按钮执行相应功能
		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 = () => {
	// 使用 open-type="share" 时，点击事件可以为空
	// 分享内容通过页面配置自动设置
	console.log('分享按钮被点击')
	//TODO:埋点
	md.sensorComponentLogTake({
		xcxComponentClick: "true",
		pageName: "星妈lab-藏品详情页",
		componentName: "藏品详情",
		componentContent: "分享"
	});

	// 手动触发分享（如果需要的话）
	// uni.showShareMenu({
	// 	withShareTicket: true,
	// 	menus: ['shareAppMessage'] // 仅分享给好友，禁用朋友圈
	// })
}


// 返回上一页
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`
		})
	}
}

// 生命周期
onMounted(async (options) => {

	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]
	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', options, currentPage.options)
		// uni.showToast({
		// 	title: '参数错误',
		// 	icon: 'none'
		// })
		// uni.redirectTo({
		// 	url: `/pages/xingmaLab/xingmaLab`
		// })
	}

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

// 定义分享函数
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}`
	}
}

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

</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 被调用')
	// 	// 朋友圈分享功能已禁用
	// 	return null
	// }
}
</script>

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