<template>
	<view class="common_page adffc" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<!-- Canvas组件，用于后台绘制海报，通过绝对定位移出屏幕外 -->
		<canvas canvas-id="posterCanvas"
			:style="{width: canvasWidth + 'px', height: canvasHeight + 'px', position: 'fixed', top: '-99999px', left: '0'}" />
			
		<cus-header title="公益活动详情" bgColor="transparent"></cus-header>
		<image src="https://oss.familydaf.cn/sxsnfile/20251218/811a8863a74d4ed9b86f68284eaff0c9.png" class="top_bg_img" mode="widthFix"></image>
		<view class="lunbo">
			<up-swiper
				:list="imgList"
				@change="e => current = e.current"
				:autoplay="true"
				:interval="2000"
				:duration="200"
				:circular="true"
				imgMode="scaleToFill"
				height="440rpx"
			>
				<template #indicator>
					<view class="indicator adf">
						<view class="indicator__dot" v-for="(item, index) in imgList" :key="index"
							:class="[index === current && 'indicator__dot--active']">
						</view>
					</view>
				</template>
			</up-swiper>
		</view>
		<view class="box box1">
			<view class="box1-top">
				<text class="box1-top-status" :class="{'end':activityInfo?.activeState==3}">{{statusCfg[activityInfo?.activeState]||'未知'}}</text>
				<text class="box1-top-title">{{activityInfo?.activityName||''}}</text>
			</view>
			<view class="box1-line" style="margin-top: 36rpx;"></view>
			<view class="box1-place adfacjb">
				<view class="box1-place-left adffcjb">
					<text>活动地点</text>
					<view class="addr">{{activityInfo?.provinceName||''}}{{activityInfo?.cityName||''}}{{activityInfo?.address||''}}</view>
				</view>
				<view class="box1-place-right">
					<image src="https://oss.familydaf.cn/sxsnfile/20251218/dc3034ff405549059cc52eac7479f0e0.png"></image>
				</view>
			</view>
			<view class="box1-line" style="margin-top: 24rpx;"></view>
			<view class="box1-member adfacjb">
				<view class="box1-member-left adffc">
					<text>招募人数</text>
					<view class="num"><text>{{activityInfo?.recruitmentNow}}</text> /{{activityInfo?.recruitmentMax||'不限'}}</view>
				</view>
				<view class="box1-member-right adffc" @tap="handleReviewMembers">
					<view class="review adfac">
						<text>查看报名人员</text>
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/d22838b7cdae42b5a8e6ebfa01d06445.png"></image>
					</view>
					<view class="avatars">
						<up-avatar-group :urls="avatars" size="30" gap="0.4" :maxCount="3"></up-avatar-group>
					</view>
				</view>
			</view>
			<view class="box1-line" style="margin-top: 33rpx;"></view>
			<view class="box1-time adffc">
				<text>活动时间</text>
				<view class="text">{{activityInfo?.activityStartTime}} - {{activityInfo?.activityEndTime}}</view>
			</view>
			<view class="box1-line" style="margin-top: 30rpx;"></view>
			<view class="box1-need adffc">
				<text>报名要求</text>
				<template v-if="activityInfo?.activityLimit==1">
					<view class="text"><text>{{activityInfo?.valueLimit||0}}</text>爱心值</view>
					<view class="tip">{{activityInfo?.loveValueContent||''}}</view>
				</template>
				<template v-else-if="activityInfo?.activityLimit==2">
					<view class="text"><text>{{activityInfo?.valueLimit||0}}</text>张专享券</view>
					<view class="tip">{{activityInfo?.loveValueContent||''}}</view>
				</template>
				<template v-else-if="activityInfo?.activityLimit==3">
					<view class="text"><text class="mf">免费</text></view>
					<view class="tip"></view>
				</template>
				<div class="box1-need-level">
					<div class="box1-need-level-title">报名等级</div>
					<div class="box1-need-level-num" :class="{'bxz':!activityInfo?.userLevel}">{{activityInfo?.userLevel?('Lv'+activityInfo?.userLevel):'不限制'}}</div>
				</div>
			</view>
			<view class="box1-line" style="margin-top: 30rpx;"></view>
			<view class="box1-info adfacjb">
				<view class="box1-info-pre">
					<text>年龄限制</text>
					<view class="text" v-if="activityInfo?.userAgeMax">{{activityInfo?.userAgeMin}}岁 到 {{activityInfo?.userAgeMax}}岁</view>
					<view class="text" v-else>不限制</view>
				</view>
				<view class="box1-info-pre line">
					<text>可获得义工时长</text>
					<!-- typeId=='1977564860095348737'为义工活动，义工时长只有义工活动才有 -->
					<view class="hour" v-if="activityInfo?.typeId=='1977564860095348737'"><text>{{activityInfo?.serviceHours||0}}</text> 小时</view>
					<view class="hour" v-else>无</view>
				</view>
			</view>
			<view class="box1-line" style="margin-top: 30rpx;"></view>
			<view class="box1-info adfacjb">
				<view class="box1-info-pre">
					<text>联系人</text>
					<view class="text">{{activityInfo?.contact||''}}/{{activityInfo?.contactPhone||''}}</view>
				</view>
				<view class="box1-info-pre line">
					<text>公益合作</text>
					<view class="text">{{activityInfo?.channelName||''}}</view>
				</view>
			</view>
		</view>
		<view class="box box2">
			<view class="box-title">活动详情</view>
			<view class="box2-detail" v-if="activityInfo&&activityInfo.activityDetails">
				<up-read-more :toggle="true" showHeight="374rpx" :shadowStyle="shadowStyle" color="#989998" fontSize="24rpx" openText="收起" closeText="展开" ref="uReadMore">
				    <!-- <rich-text :nodes="activityInfo.activityDetails"></rich-text> -->
					<u-parse :content="activityInfo.activityDetails" @load="load"></u-parse>
				</up-read-more>
			</view>
		</view>
		<view class="bottom">
			<view class="time">
				报名时间：{{activityInfo?.signupStartTime}} - {{activityInfo?.signupEndTime}} 
			</view>
			<view class="btns adfacjb">
				<view class="left adffcacjc" @tap="showShareOptions">
					<up-icon name="share-square" color="#252525" size="48rpx"></up-icon>
					<text>分享</text>
				</view>
				<view class="right" @click="handleApply" v-if="activityInfo?.activeState==1&&activityInfo?.signupState==0">立即报名</view>
				
				<view class="right" @click="handleCancel" v-else-if="activityInfo?.activeState==1&&activityInfo?.signupState==1">取消报名</view>
				<view class="right" @click="handleSignup" v-else-if="activityInfo?.activeState==2&&activityInfo?.signupState==1">我要签到</view>
				<view class="right" @click="handleFill" v-else-if="activityInfo?.activeState==3&&activityInfo?.signupState==1">填写公益档案</view>
				
				<view class="right end" v-else-if="activityInfo?.activeState==-1">活动已取消</view>
				<view class="right end" v-else-if="activityInfo?.activeState==0">活动未开始</view>
				<view class="right end" v-else-if="activityInfo?.activeState==1&&activityInfo?.signupState==2">活动已签到</view>
				<view class="right end" v-else-if="activityInfo?.activeState==2&&activityInfo?.signupState==2">活动已签到</view>
				<view class="right end" v-else-if="activityInfo?.activeState==2&&activityInfo?.signupState==0">活动进行中不可报名</view>
				<view class="right end" v-else-if="activityInfo?.activeState==3">活动已结束</view>
				<view class="right end" v-else-if="activityInfo?.activeState==4">已报满暂无活动名额</view>
			</view>
		</view>
		<view class="fail" v-if="fail">
			<view class="fbox adffcac">
				<image class="clock" src="https://oss.familydaf.cn/sxsnfile/20251218/4a47278697174d04bf54b8b691587a9c.png"></image>
				<image class="close" src="https://oss.familydaf.cn/sxsnfile/20251218/5e39649ad9d0433c96a491bd040413eb.png" @click="fail=false"></image>
				<image class="alert" src="https://oss.familydaf.cn/sxsnfile/20251218/39c584e1f7214b32aab2418272bb8678.png" mode="widthFix"></image>
				<view class="texts adffcacjc">
					<view class="text">您当前{{activityLimitCfg[activityInfo?.activityLimit]}}不足，无法报名活动</view>
					<view class="tip">欢迎联系专属客服，了解更多公益活动，积攒{{activityLimitCfg[activityInfo?.activityLimit]}}</view>
				</view>
				<image class="down" src="https://oss.familydaf.cn/sxsnfile/20251218/445791524423424da07755060a6d50ad.png"></image>
				<view class="user adfacjc">
					"善行少年"咨询微信
				</view>
				<view class="finfo adffcac">
					<view class="finfo-code adffcacjc">
						<image :src="imageUrl" :show-menu-by-longpress="true"></image>
					</view>
					<view class="finfo-title">长按识别二维码</view>
					<view class="finfo-tip">添加您的专属公益向导</view>
					<view class="finfo-btn" @click="toWebView">了解善行少年</view>
					<view class="finfo-zblj" @click="fail=false">暂不了解</view>
				</view>
			</view>
		</view>
		<view class="share" v-if="share">
			<view class="sbox">
				<view class="sbox-title">分享给好友</view>
				<image class="close" src="https://oss.familydaf.cn/sxsnfile/20251218/bbf9472f744741bf9fcf2a2d4c5c0f11.png" @click="share=false"></image>
				<view class="sbox-items adfac">
					<view class="sbox-items-pre adffcac">
						<button class="share-btn" open-type="share">
							<image src="https://oss.familydaf.cn/sxsnfile/20251218/9b409327172b42b5a165e1d4da631753.png"></image>
							<text>分享页面</text>
						</button>
					</view>
					<view class="sbox-items-pre adffcac" @click="generatePoster">
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/8f7e9292eb054271a03cf5f7d63a6b25.png"></image>
						<text>生成海报</text>
					</view>
					<view class="sbox-items-pre adffcac" @click="shareToTimeline">
						<image src="https://oss.familydaf.cn/sxsnfile/20251218/b29cf7f4b77e44458c5abc01ca2ff56e.png"></image>
						<text>分享到朋友圈</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 海报展示弹窗 -->
		<view class="posterbox adffcacjc" v-if="posterShow">
			<!-- 加载状态 -->
			<u-loading-icon v-if="posterLoading" text="海报生成中..." size="28" textSize="18" inactiveColor="#ffffff" color="#ffffff"></u-loading-icon>
			
			<!-- 海报生成后的内容 -->
			<template v-else>
				<!-- 此处不再使用HTML结构，而是直接显示生成的图片 -->
				<div class="posterbox-card adffcac">
					<image :src="posterUrl" mode="widthFix" class="poster-image"></image>
				</div>
				
				<div class="posterbox-menu adfacjb">
					<div class="posterbox-menu-pre adffcac" v-for="(item,index) in menuList" :key="index" @click="handleMenuClick(item.type)">
						<template v-if="index===0">
							<button class="share-btn" open-type="share">
								<image :src="item.img"></image>
								<text>{{item.title}}</text>
							</button>
						</template>
						<template v-else>
							<image :src="item.img"></image>
							<text>{{item.title}}</text>
						</template>
					</div>
				</div>
				<div class="posterbox-close adfacjc">
					<image src="https://oss.familydaf.cn/sxsnfile/20251218/44d55c9cb46a404d9dfc0e4ed106c69d.png" @click="posterShow=false"></image>
				</div>
			</template>
		</view>
	</view>
</template>

<script setup name="">
	import CusHeader from '@/components/CusHeader/index.vue'
	import { onLoad } from '@dcloudio/uni-app';
	import { ref, reactive, onMounted, getCurrentInstance ,nextTick } from 'vue'
	import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app' 
	const { proxy } = getCurrentInstance()
	
	const id = ref('')
	const activityInfo = ref(null)
	const statusCfg = ref({
		'-1':'已取消',
		0:'未开始',
		1:'报名中',
		4:'报名中',
		2:'进行中',
		3:'已结束'
	})
	const activityLimitCfg = ref({
		1:'爱心值',
		2:'专享券',
		3:'免费'
	})
	const imgList = ref([])
	const current = ref(0)
	const detail = ref('')
	const avatars = ref([])
	const fail = ref(false)
	const share = ref(false)
	const uReadMore = ref()
	const shadowStyle = ref({
		backgroundImage: "none",
		paddingTop: "0",
		marginTop: "20rpx"
	})

	// --- 海报生成相关 ---
	const posterShow = ref(false) // 控制海报弹窗显示
	const posterLoading = ref(false) // 控制海报生成时的加载状态
	const posterUrl = ref('') // 存储生成的海报图片临时路径
	const canvasWidth = ref(0) // Canvas 宽度
	const canvasHeight = ref(0) // Canvas 高度

	// 海报上所需的动态数据
	const posterData = reactive({
		mainImg: 'https://sxsn.ringzle.com/happytree-admin/profile/2025/12/12/e8218de1-d059-4197-b677-f9d2e446971e.png',
		title: '《环保知识知多少》让孩子成为健康公益大使',
		time: '06.01-12:00 ~ 06.02-12:00',
		timeIcon: 'https://oss.familydaf.cn/sxsnfile/20251218/762878799914422d835e505291b9d4c6.png',
		address: '深圳市南山区南山街道丰潭路',
		addressIcon: 'https://oss.familydaf.cn/sxsnfile/20251218/57539643ab974aef9401d76818e1bf3b.png',
		organizer: '锦鲤俱乐部',
		organizerIcon: 'https://oss.familydaf.cn/sxsnfile/20251218/47953738adfc46d8b959d7cead7a186e.png',
		qrCode: 'https://oss.familydaf.cn/sxsnfile/20251218/4eeb3cf6799141c9853349533c33e529.jpg'
	})

	const imageUrl = ref('https://oss.familydaf.cn/sxsnfile/20251218/b25745272a52435194dbc3987d5645f2.png')
	const menuList = ref([
		{ img:'https://oss.familydaf.cn/sxsnfile/20251218/533e0ec5511043c6853c4a05b720dadf.png',title:'发送给朋友', type:'shareApp' },
		{ img:'https://oss.familydaf.cn/sxsnfile/20251218/43a1bf3fc87240a2b33359f10d9d4d19.png',title:'分享到朋友圈', type:'shareTimeline' },
		{ img:'https://oss.familydaf.cn/sxsnfile/20251218/875a7d2a8f9e47cb813246879b2b0714.png',title:'收藏', type:'favorite' },
		{ img:'https://oss.familydaf.cn/sxsnfile/20251218/125b3da887974ae2b600ce2ec72c1fbe.png',title:'保存图片', type:'save' },
	])
	
	const load = () => {
		nextTick(()=>{
			proxy.$refs.uReadMore.init();
		})
	}
	
	const handleReviewMembers = () => {
		uni.navigateTo({
			url:'/pagesHome/recruitsNumber?activityId='+activityInfo.value?.id+'&recruitmentMax='+activityInfo.value?.recruitmentMax+'&recruitmentMin='+activityInfo.value?.recruitmentMin
		})
	}
	
	//立即报名
	const handleApply = async () => {
		let level = JSON.parse(uni.getStorageSync('userInfo'))?.userLevel;
		if(level<activityInfo.value.userLevel) return proxy.$showModal(`很抱歉，当前活动限制报名等级为${activityInfo.value.userLevel}级，您当前等级为${level}级，不满足报名条件。`)
		
		let { loveValue, couponIds } = await getUserLoveTicket();
		let url = `/pagesHome/activityApply?activity=${encodeURIComponent(JSON.stringify(activityInfo.value))}`;
		
		if((activityInfo.value?.activityLimit==1&&loveValue<activityInfo?.value.valueLimit)
		||(activityInfo.value?.activityLimit==2&&couponIds?.length<activityInfo?.value.valueLimit)){
			fail.value = true;
			return 
		}
		uni.navigateTo({ url })
	}
	//取消报名
	const handleCancel = () => {
		uni.reLaunch({
			url:'/pages/nonprofit?type=1'
		})
	}
	//我要签到
	const handleSignup = () => {
		uni.reLaunch({
			url:'/pages/nonprofit?type=2'
		})
	}
	//填写公益档案
	const handleFill = () => {
		uni.reLaunch({
			url:'/pages/nonprofit?type=3'
		})
	}
	
	const getUserLoveTicket = () => {
		return new Promise(resolve=>{
			let userId = JSON.parse(uni.getStorageSync('userInfo'))?.id;
			proxy.$api.get(`/core/activity/signup/userAsset/${userId}/${activityInfo.value?.id}`).then(({data:res})=>{
				if(res.code!==0) return proxy.$showToast(res.msg)
				resolve({loveValue:res.data?.loveValue||0,couponIds:res.data?.couponIds||0})
			})
		}) 
	}
	
	onShareAppMessage((res) => {
		// 如果是点击海报菜单的“发送给朋友”按钮
		if (res.from === 'button' && res.target.id === 'posterShareBtn') {
			return {
				title: posterData.title,
				path: `/pagesHome/activityDetail?shareADId=${id.value}`,
				imageUrl: posterUrl.value // 使用生成的海报作为分享图
			};
		}
		// 默认页面右上角分享
		const sharerId = JSON.parse(uni.getStorageSync('userInfo'))?.id;
		return {
		  title: activityInfo.value?.activityName || '发现一个好物，分享给你！',
		  path: `/pagesHome/activityDetail?shareADId=${activityInfo.value?.id}&shareUserId=${sharerId}`,
		  imageUrl: activityInfo.value?.coverFile
		};
	})
	
	onShareTimeline((res) => {
		const sharerId = JSON.parse(uni.getStorageSync('userInfo'))?.id;
		return {
		  title: activityInfo.value?.activityName || '发现一个好物，分享给你！',
		  query: `shareADId=${activityInfo.value?.id}&shareUserId=${sharerId}`,
		  imageUrl: activityInfo.value?.coverFile
		};
	})
	
	const showShareOptions = () => {
		share.value = true;
	}
	
	// 分享到朋友圈(旧逻辑)
	const shareToTimeline = () => {
		uni.showModal({
			title:'温馨提示',
			content:'分享到朋友圈请点击页面右上方的“···”标志后选择“分享到朋友圈”进行分享'
		})
	}

	// --- Canvas海报生成核心逻辑 ---

	// 1. 触发生成
	const generatePoster = async () => {
		share.value = false;
		posterShow.value = true;
		posterLoading.value = true;
		posterUrl.value = ''; // 清空旧海报

		try {
			// 获取设备信息，用于rpx转px
			const systemInfo = uni.getSystemInfoSync();
			const screenWidth = systemInfo.screenWidth;
			const rpxRatio = screenWidth / 750;

			// --- 定义尺寸和坐标 (单位: px) ---
			// 卡片总宽度为 100% - 220rpx
			const cardWidth = screenWidth - 220 * rpxRatio;
			const cardPadding = 20 * rpxRatio;
			const contentWidth = cardWidth - cardPadding * 2;
			
			const mainImgHeight = 368 * rpxRatio;
			const infoTopMargin = 14 * rpxRatio;
			
			const qrCodeWidth = 123 * rpxRatio;
			const qrCodeHeight = 123 * rpxRatio;
			const rightPartWidth = 163 * rpxRatio;
			const leftPartWidth = contentWidth - rightPartWidth;

			// 计算总高度
			const titleHeight = calculateWrappedTextHeight(posterData.title, 24 * rpxRatio, contentWidth, 36 * rpxRatio);
			const infoBlockHeight = 160 * rpxRatio; // 估算下方信息区域高度
			const cardHeight = cardPadding * 2 + mainImgHeight + infoTopMargin + infoBlockHeight;

			canvasWidth.value = cardWidth;
			canvasHeight.value = cardHeight;
			
			// 等待一帧，确保canvas尺寸设置生效
			await new Promise(resolve => setTimeout(resolve, 50));

			const ctx = uni.createCanvasContext('posterCanvas', proxy);

			// --- 下载所有需要的图片 ---
			const [mainImg, timeIcon, addressIcon, orgIcon, qrCode] = await Promise.all([
				uni.getImageInfo({ src: posterData.mainImg }),
				uni.getImageInfo({ src: posterData.timeIcon }),
				uni.getImageInfo({ src: posterData.addressIcon }),
				uni.getImageInfo({ src: posterData.organizerIcon }),
				uni.getImageInfo({ src: posterData.qrCode }),
			]);

			// --- 开始绘制 ---
			
			// 1. 绘制白色背景
			ctx.fillStyle = '#FFFFFF';
			ctx.fillRect(0, 0, cardWidth, cardHeight);

			// 2. 绘制主图 (带圆角)
			ctx.save(); // 保存当前画布状态
			const borderRadius = 16 * rpxRatio; // 16rpx
			
			// 创建圆角矩形路径
			ctx.beginPath();
			ctx.moveTo(cardPadding + borderRadius, cardPadding);
			ctx.lineTo(cardPadding + contentWidth - borderRadius, cardPadding);
			ctx.arcTo(cardPadding + contentWidth, cardPadding, cardPadding + contentWidth, cardPadding + borderRadius, borderRadius);
			ctx.lineTo(cardPadding + contentWidth, cardPadding + mainImgHeight - borderRadius);
			ctx.arcTo(cardPadding + contentWidth, cardPadding + mainImgHeight, cardPadding + contentWidth - borderRadius, cardPadding + mainImgHeight, borderRadius);
			ctx.lineTo(cardPadding + borderRadius, cardPadding + mainImgHeight);
			ctx.arcTo(cardPadding, cardPadding + mainImgHeight, cardPadding, cardPadding + mainImgHeight - borderRadius, borderRadius);
			ctx.lineTo(cardPadding, cardPadding + borderRadius);
			ctx.arcTo(cardPadding, cardPadding, cardPadding + borderRadius, cardPadding, borderRadius);
			ctx.closePath();
			ctx.clip(); // 裁剪后续绘图到此路径
			
			ctx.drawImage(mainImg.path, cardPadding, cardPadding, contentWidth, mainImgHeight);
			ctx.restore(); // 恢复画布状态 (移除裁剪路径)

			let currentY = cardPadding + mainImgHeight + infoTopMargin;

			// 3. 绘制左侧信息
			const leftX = cardPadding;
			// 3.1 绘制标题 (自动换行)
			ctx.font = `bold ${Math.round(24 * rpxRatio)}px "PingFang-SC", sans-serif`;
			ctx.fillStyle = '#252525';
			currentY += drawWrappedText(ctx, posterData.title, leftX, currentY + 24 * rpxRatio, leftPartWidth, 36 * rpxRatio, 1);
			
			currentY += 12 * rpxRatio; // 标题和下方内容的间距
			
			// 3.2 绘制时间
			const iconSize = 24 * rpxRatio;
			const textLeftMargin = 10 * rpxRatio;
			const infoLineHeight = 36 * rpxRatio;
			ctx.drawImage(timeIcon.path, leftX, currentY + (infoLineHeight - iconSize) / 2, iconSize, iconSize);
			ctx.font = `bold ${Math.round(20 * rpxRatio)}px "PingFang-SC", sans-serif`;
			ctx.fillStyle = '#8B8B8B';
			ctx.fillText(posterData.time, leftX + iconSize + textLeftMargin, currentY + 25 * rpxRatio);
			currentY += infoLineHeight;

			// 3.3 绘制地点
			ctx.drawImage(addressIcon.path, leftX, currentY + (infoLineHeight - iconSize) / 2, iconSize, iconSize);
			ctx.fillText(posterData.address, leftX + iconSize + textLeftMargin, currentY + 25 * rpxRatio);
			currentY += infoLineHeight;
			
			// 3.4 绘制俱乐部
			const orgIconSize = 30 * rpxRatio;
			ctx.drawImage(orgIcon.path, leftX, currentY + (infoLineHeight - orgIconSize) / 2, orgIconSize, orgIconSize);
			ctx.fillText(posterData.organizer, leftX + orgIconSize + textLeftMargin, currentY + 25 * rpxRatio);


			// 4. 绘制右侧二维码
			const rightX = cardPadding + leftPartWidth;
			const qrY = cardPadding + mainImgHeight + infoTopMargin;
			ctx.drawImage(qrCode.path, rightX + (rightPartWidth - qrCodeWidth) / 2, qrY, qrCodeWidth, qrCodeHeight);
			
			// 4.1 绘制二维码下方文字
			ctx.textAlign = 'center';
			ctx.font = `bold ${Math.round(20 * rpxRatio)}px "PingFang-SC", sans-serif`;
			ctx.fillStyle = '#8B8B8B';
			ctx.fillText('微信扫一扫', rightX + rightPartWidth / 2, qrY + qrCodeHeight + 30 * rpxRatio);
			ctx.textAlign = 'left'; // 恢复默认

			// --- 生成图片 ---
			ctx.draw(false, () => {
				uni.canvasToTempFilePath({
					canvasId: 'posterCanvas',
					success: (res) => {
						posterUrl.value = res.tempFilePath;
						posterLoading.value = false;
					},
					fail: (err) => {
						console.error('canvasToTempFilePath failed:', err);
						proxy.$showToast('海报生成失败，请稍后再试');
						posterLoading.value = false;
						posterShow.value = false;
					}
				}, proxy);
			});

		} catch (error) {
			console.error('generatePoster failed:', error);
			proxy.$showToast('图片资源加载失败，无法生成海报');
			posterLoading.value = false;
			posterShow.value = false;
		}
	}
	
	// Canvas 文本换行绘制函数
	// ctx: canvas context, text: 文本, x,y: 起始坐标, maxWidth: 最大宽度, lineHeight: 行高, maxLines: 最大行数
	function drawWrappedText(ctx, text, x, y, maxWidth, lineHeight, maxLines = 2) {
		let lines = [];
		let currentLine = '';
		let totalHeight = 0;

		for (let i = 0; i < text.length; i++) {
			let char = text[i];
			let testLine = currentLine + char;
			let metrics = ctx.measureText(testLine);
			let testWidth = metrics.width;
			if (testWidth > maxWidth && i > 0) {
				lines.push(currentLine);
				currentLine = char;
			} else {
				currentLine = testLine;
			}
		}
		lines.push(currentLine);

		if (lines.length > maxLines) {
			lines = lines.slice(0, maxLines);
			lines[maxLines - 1] += '...';
		}

		for (let j = 0; j < lines.length; j++) {
			ctx.fillText(lines[j], x, y + j * lineHeight);
			totalHeight += lineHeight;
		}
		return totalHeight;
	}

	// 辅助函数，用于估算换行后的文本高度
	function calculateWrappedTextHeight(text, fontSize, maxWidth, lineHeight) {
		// 这是一个简化的估算，实际应使用canvas.measureText
		const charsPerLine = Math.floor(maxWidth / (fontSize * 1.1));
		const lines = Math.ceil(text.length / charsPerLine);
		return lines * lineHeight;
	}


	// --- 海报下方菜单点击事件 ---
	const handleMenuClick = (type) => {
		switch(type) {
			case 'shareApp':
				break;
			case 'shareTimeline':
				// 同上，提示用户
				uni.showToast({ title: '请点击右上角“···”分享到朋友圈', icon: 'none' });
				break;
			case 'favorite':
				 uni.showModal({
					title: '收藏提示',
					content: "请点击右上角 '...' 按钮，然后选择 '添加到我的小程序' 或 '收藏'，即可方便下次访问哦！",
					showCancel: false, // 通常只保留一个“我知道了”按钮
					confirmText: '我知道了'
				});
				break;
			case 'save':
				// 保存图片到相册
				savePosterToAlbum();
				break;
		}
	}

	// 保存海报到相册
	const savePosterToAlbum = () => {
		if (!posterUrl.value) {
			proxy.$showToast('海报图片不存在');
			return;
		}
		uni.saveImageToPhotosAlbum({
			filePath: posterUrl.value,
			success: () => {
				proxy.$showToast('海报已保存到相册');
			},
			fail: (err) => {
				if (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied')) {
					uni.showModal({
						title: '授权提示',
						content: '需要您授权保存图片到相册',
						showCancel: false,
						success: () => {
							uni.openSetting(); //引导用户去设置页
						}
					})
				} else {
					proxy.$showToast('保存失败，请稍后再试');
				}
			}
		})
	}

	const toWebView = () => {
		uni.navigateTo({
			url:'/pages/webView?src=https://mp.weixin.qq.com/s/-oQlSBucYU_ifgd1j6eL3A?scene=1&click_id=2'
		})
	}
	  
	const getActivityDetail = (id) => {
		proxy.$api.get(`/core/activity/${id}`).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			activityInfo.value = res.data;
			// 更新海报数据
			posterData.title = activityInfo.value?.activityName || posterData.title;
			posterData.time = `${new Date(activityInfo.value?.activityStartTime).Format('MM.dd-hh:mm') } ~ ${new Date(activityInfo.value?.activityEndTime).Format('MM.dd-hh:mm')}` || posterData.time;
			posterData.address = `${activityInfo.value?.provinceName||''}${activityInfo.value?.cityName||''}${activityInfo.value?.address||''}` || posterData.address;
			posterData.organizer = activityInfo.value?.channelName || posterData.organizer;
			if(activityInfo.value?.coverFile) posterData.mainImg = activityInfo.value?.coverFile;

			if(activityInfo.value.signupState==0
			&&activityInfo.value.activeState===1
			&&activityInfo.value.recruitmentNow==(activityInfo.value.recruitmentMax||99999)){
				activityInfo.value.activeState = 4;//已报满暂无活动名额
			}
			imgList.value = activityInfo.value?.imageFiles&&(activityInfo.value?.imageFiles.split(',')||[])
			for(let i=0;i<activityInfo.value.recruitmentNow;i++){
				avatars.value.push('https://oss.familydaf.cn/sxsnfile/20251218/3821654e080945998d464f3c3aa64122.png')
			}
		})
	}
	
	onLoad(options=>{
		id.value = options?.id||options?.shareADId||'';
		if(id.value) {
			getActivityDetail(id.value)
		}
	})
</script>

<style scoped lang="scss">
	::v-deep .u-navbar>view{
		background: url('https://oss.familydaf.cn/sxsnfile/20251223/d07237024c5e4f00a63b9089abbf5a3c.png') no-repeat;
		background-size: 100% 100%;
	}
	
	::v-deep .indicator__dot{
		width: 48rpx;
		height: 4rpx;
		background: #E2E5E9;
		border-radius: 2rpx;
		margin: 0 8rpx;
	}
	::v-deep .indicator__dot--active{
		width: 48rpx;
		height: 4rpx;
		background: #00AE57;
		border-radius: 2rpx;
	}
	::v-deep .u-swiper__wrapper__item__wrapper__image{
		border-radius: 24rpx !important;
	}
	::v-deep .u-read-more__toggle{
		margin: 20rpx 0 0 0 !important;
	}
	
	/* 按钮分享样式 */
	.share-btn {
		background-color: transparent;
		border: none;
		padding: 0;
		margin: 0;
		line-height: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		&::after {
			border: none;
		}
	}
	
	.common_page{
		padding-bottom: 276rpx;
		
		.lunbo{
			width: 100%;
			height: 440rpx;
			margin-top: 20rpx;
			position: relative;
		}
		
		.box{
			background: linear-gradient(45deg,#FFFFFF 70%,#F2FFE8 100%);
			border-radius: 24rpx;
			padding: 36rpx 24rpx 30rpx;
			margin-top: 20rpx;
			position: relative;
			&-title{
				width: 170rpx;
				height: 44rpx;
				padding-left: 2rpx;
				font-family: PingFang-SC, PingFang-SC;
				font-weight: 800;
				font-size: 36rpx;
				color: #151B29;
				line-height: 36rpx;
				background-image: url('https://oss.familydaf.cn/sxsnfile/20251218/6198fa26a7ff4fc1bce530fbdfaa20db.png');
				background-size: 170rpx 31rpx;
				background-position: 0 20rpx;
				background-repeat: no-repeat;
			}
		}
		
		.box1{
			&-top{
				&-status{
					padding: 10rpx 20rpx;
					background: url('https://oss.familydaf.cn/sxsnfile/20251218/5b591d1c173943dca6e33f950714e5e2.png') no-repeat;
					background-size: 100% 100%;
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 24rpx;
					color: #151B29;
					line-height: 33rpx;
					&.end{
						background: linear-gradient( 270deg, #FD8A8A 0%, #FE6161 100%);
						border-radius: 16px 4px 16px 4px;
						color: #FFFFFF;
					}
				}
				&-title{
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 36rpx;
					color: #151B29;
					line-height: 54rpx;
					margin-left: 10rpx;
				}
			}
			&-line{
				width: 100%;
				height: 1rpx;
				background: #E7E7E7;
			}
			&-place{
				&-left{
					width: calc(100% - 228rpx);
					text{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #989998;
						line-height: 26rpx;
					}
					.addr{
						width: 100%;
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 26rpx;
						color: #151B29;
						line-height: 26rpx;
						margin-top: 24rpx;
					}
				}
				&-right{
					width: 188rpx;
					height: 115rpx;
					image{
						width: 100%;
						height: 100%;
					}
				}
			}
			&-member{
				margin-top: 37rpx;
				&-left{
					&>text{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #989998;
						line-height: 26rpx;
					}
					.num{
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 26rpx;
						color: #676775;
						line-height: 48rpx;
						margin-top: 25rpx;
						text{
							font-size: 36rpx;
							color: #151B29;
						}
					}
				}
				&-right{
					.review{
						text{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 24rpx;
							color: #989998;
							line-height: 26rpx;
						}
						image{
							width: 28rpx;
							height: 28rpx;
							margin-left: 8rpx;
						}
					}
					.avatars{
						margin-top: 27rpx;
						display: flex;
						justify-content: flex-end;
					}
				}
			}
			&-time{
				margin-top: 30rpx;
				text{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #989998;
					line-height: 26rpx;
				}
				.text{
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 26rpx;
					color: #151B29;
					line-height: 26rpx;
					margin-top: 24rpx;
				}
			}
			&-need{
				margin-top: 30rpx;
				position: relative;
				&>text{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #989998;
					line-height: 26rpx;
				}
				.text{
					margin-top: 30rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #676775;
					line-height: 26rpx;
					text{
						font-weight: bold;
						font-size: 36rpx;
						color: #151B29;
						&.mf{
							font-size: 26rpx;
						}
					}
				}
				.tip{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #C9A771;
					line-height: 26rpx;
					margin-top: 20rpx;
				}
				&-level{
					position: absolute;
					left: 50%;
					padding-left: 25rpx;
					&-title{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #989998;
						line-height: 26rpx;
					}
					&-num{
						margin-top: 30rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: bold;
						font-size: 36rpx;
						color: #151B29;
						line-height: 26rpx;
						&.bxz{
							font-size: 26rpx;
						}
					}
				}
			}
			&-info{
				margin-top: 30rpx;
				&-pre{
					width: 50%;
					&.line{
						border-left: 1rpx solid #E7E7E7;
						padding-left: 24rpx;
						box-sizing: border-box;
					}
					&>text{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #989998;
						line-height: 26rpx;
					}
					.text{
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 26rpx;
						color: #151B29;
						line-height: 26rpx;
						margin-top: 24rpx;
					}
					.hour{
						margin-top: 24rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #676775;
						line-height: 26rpx;
						text{
							font-weight: bold;
							font-size: 36rpx;
							color: #151B29;
						}
					}
				}
			}
		}
		
		.box2{
			&-detail{
				margin-top: 40rpx;
			}
		}
		
		.bottom{
			width: 100%;
			height: 256rpx;
			background: #FFFFFF;
			box-shadow: 0rpx -2rpx 8rpx 0rpx rgba(178,178,178,0.1);
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			padding: 30rpx 24rpx 0;
			box-sizing: border-box;
			.time{
				padding: 19rpx 24rpx 12rpx;
				background: #F8F8F9;
				border-radius: 32rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #4B545C;
				line-height: 33rpx;
			}
			.btns{
				margin-top: 24rpx;
				.left{
					margin-left: 30rpx;
					text{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 26rpx;
						color: #151B29;
						line-height: 26rpx;
						margin-top: 17rpx;
					}
				}
				.right{
					width: 540rpx;
					height: 90rpx;
					background: #B7F358;
					border-radius: 45rpx;
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #151B29;
					line-height: 90rpx;
					text-align: center;
					letter-spacing: 2rpx;
					&.end{
						background: #F7F7F7;
					}
				}
			}
		}
	
		.fail{
			position: fixed;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			background: rgba(0,0,0,0.4);
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
			.fbox{
				background: #FFFFFF;
				background-image: url('https://oss.familydaf.cn/sxsnfile/20251218/f168e863e60b423588821f8aa0388e27.png');
				background-repeat: no-repeat;
				background-position: top left;
				background-size: 100% 399rpx;
				border-radius: 24rpx 24rpx 0 0;
				position: relative;
				padding: 40rpx 30rpx 123rpx;
				
				.clock{
					width: 219rpx;
					height: 143rpx;
					position: absolute;
					left: 51rpx;
					top: -37rpx;
				}
				.close{
					width: 40rpx;
					height: 40rpx;
					position: absolute;
					top: 40rpx;
					right: 36rpx;
				}
				.alert{
					width: 212rpx;
				}
				.texts{
					width: 100%;
					margin-top: 69rpx;
					background: #FFFFFF;
					border-radius: 24rpx;
					border: 1rpx dotted #979797;
					padding: 36rpx 0;
					.text{
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 36rpx;
						color: #252525;
						line-height: 36rpx;
					}
					.tip{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #676775;
						line-height: 26rpx;
						margin-top: 24rpx;
					}
				}
				.down{
					width: 514rpx;
					height: 34rpx;
					margin-top: 20rpx;
				}
				.user{
					width: 100%;
					margin-top: 50rpx;
					box-sizing: border-box;
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #252525;
					line-height: 32rpx;
				}
				.finfo{
					width: 100%;
					margin-top: 36rpx;
					&-code{
						width: 310rpx;
						height: 310rpx;
						background: #FFFFFF;
						border: 3rpx solid #C5E3FE;
						image{
							width: 244rpx;
							height: 244rpx;
						}
					}
					&-title{
						margin-top: 24rpx;
						font-size: 28rpx;
						color: #252525;
						line-height: 40rpx;
					}
					&-tip{
						margin-top: 10rpx;
						font-size: 24rpx;
						color: #656775;
						line-height: 40rpx;
					}
					&-btn{
						width: calc(100% - 20rpx);
						height: 90rpx;
						background: #B7F358;
						border-radius: 45rpx;
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						font-size: 32rpx;
						color: #151B29;
						line-height: 90rpx;
						text-align: center;
						margin-top: 48rpx;
					}
					&-zblj{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #989998;
						line-height: 40rpx;
						margin-top: 48rpx;
						padding-bottom: 5rpx;
						border-bottom: 1rpx solid #989998;
					}
				}
			}
		}
		
		.share{
			position: fixed;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			z-index: 1000;
			background: rgba(0,0,0,0.4);
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
			.sbox{
				position: relative;
				background: #FFFFFF;
				border-radius: 24rpx 24rpx 0rpx 0rpx;
				padding: 50rpx 30rpx 148rpx;
				&-title{
					font-family: PingFang-SC, PingFang-SC;
					font-weight: bold;
					font-size: 36rpx;
					color: #151B29;
					line-height: 36rpx;
					text-align: center;
				}
				.close{
					width: 27rpx;
					height: 27rpx;
					position: absolute;
					top: 50rpx;
					right: 40rpx;
				}
				&-items{
					margin-top: 88rpx;
					&-pre{
						width: calc(100% / 3);
						image{
							width: 94rpx;
							height: 94rpx;
						}
						text{
							font-family: PingFangSC, PingFang SC;
							font-weight: 400;
							font-size: 26rpx;
							color: #252525;
							line-height: 26rpx;
							text-align: center;
							margin-top: 24rpx;
						}
					}
				}
			}
		}
	
		.posterbox{
			position: fixed;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			z-index: 1001;
			background: rgba(0,0,0,0.7);
			
			.posterbox-card{
				width: calc(100% - 220rpx);
				.poster-image {
					width: 100%;
					border-radius: 8px; // 给生成的图片也加个圆角，更美观
				}
			}
			
			&-menu{
				width: 100%;
				margin-top: 239rpx;
				&-pre{
					width: 25%;
					image{
						width: 103rpx;
						height: 104rpx;
					}
					text{
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: rgba(255,255,255,0.6);
						line-height: 33rpx;
						margin-top: 32rpx;
					}
				}
			}
			
			&-close{
				margin-top: 58rpx;
				image{
					width: 64rpx;
					height: 64rpx;
				}
			}
		}
	}
</style>