<template>
	<view class="common_page adffc" :style="{'height':h+'px', 'padding-top':mt+'px'}">
		<!-- 页面头部和主要内容 (保持不变) -->
		<cus-header title="我的成就" bgColor="transparent"></cus-header>
		<image src="https://oss.familydaf.cn/sxsnfile/20251218/14dde55f252a4df4a67886c57e083c6d.png" class="top_bg_img" mode="widthFix"></image>
		<view class="info">
			<view class="info-top adfac">
				<image class="avatar" :src="userInfo?.avatarPath||'https://oss.familydaf.cn/sxsnfile/20251218/ad5a1a788b6944358b0bc93e2506bf17.png'"></image>
				<view class="name">Hi~ {{userInfo?.realName||''}}</view>
				<view class="level adfac"><text>LV</text><text>{{userInfo?.userLevel||0}}</text></view>
			</view>
			<view class="info-num">收获勋章：{{numInfo?.myMedals||0}} <text>枚</text></view>
			<view class="info-memo">共参与<text>{{numInfo?.activityCount||0}}</text>次公益活动，累计义工时长<text>{{numInfo?.volunteerHours||0}}</text>小时</view>
		</view>
		<view class="tab adfacjc">
			<view class="tab-pre" :class="{'active':queryParams.obtained===1}" @click="changeTab(1)">全部</view>
			<view class="tab-pre" :class="{'active':queryParams.obtained===''}" @click="changeTab('')">未获得</view>
		</view>
		<view class="list" v-if="list.length">
			<view class="list-pre adffcac" v-for="(item,index) in list" :key="index" @click="showSz(item)">
				<image :src="item.imageUrl||''"></image>
				<view class="p">{{item?.medalName||''}}</view>
				<view class="p tip" v-if="item?.lightUp">{{item?.lightUpDate2||''}}点亮</view>
				<view class="p tip" v-else>未获得</view>
			</view>
		</view>
		<view class="dataEmpty" v-else>
			<page-empty text="暂无勋章"></page-empty>
		</view>

		<!-- 分享按钮 -->
		<view class="btn" @click="showSave">晒出我的成就</view>
		
		<!-- 勋章详情弹窗 (保持不变) -->
		<view class="dialog adffcac" :style="{'height':'calc(100vh - '+mt+')px', 'top':mt+'px'}" v-if="xzShow">
			<view class="title">"恭喜您获得荣誉勋章"</view>
			<view class="img adfacjc">
				<image :src="xzInfo.imageUrl"></image>
			</view>
			<view class="name adfac">
				<image src="https://oss.familydaf.cn/sxsnfile/20251218/3f1a0b7c92ed479c908b705936cefa45.png"></image>
				<text>{{xzInfo.medalName}}</text>
				<image src="https://oss.familydaf.cn/sxsnfile/20251218/1768e4e2e276413fb3c59b17e4242501.png"></image>
			</view>
			<view class="date">{{xzInfo.lightUpDate}}获得</view>
			<view class="btn adfacjc" @click="shareMedal">
				<image src="https://oss.familydaf.cn/sxsnfile/20251218/3e76bc6c59144bb7995975063a250435.png"></image>
				<text>炫耀一下</text>
			</view>
			<image class="close" @click="xzShow=false;xzInfo=null" src="https://oss.familydaf.cn/sxsnfile/20251218/78386a7b48674761b0e33fc9c621cc3f.png"></image>
		</view>

		<!-- 分享弹窗：显示生成的图片 -->
		<view class="save adffcacjc" :style="{'height':'calc(100vh - '+mt+')px', 'top':mt+'px'}" v-if="saveShow">
			<view class="share_box">
				<image 
					:src="generatedImagePath" 
					class="share_image" 
					mode="widthFix"
					@longpress="saveImageToAlbum"
				></image>
				<image 
					class="share_close_btn" 
					@click="saveShow=false" 
					src="https://oss.familydaf.cn/sxsnfile/20251218/098d0e537ce34d4f8ca3d0523452a025.png"
				></image>
			</view>
			<view class="text">长按图片，保存到手机</view>
		</view>

		<!-- 用于绘制分享图的 Canvas -->
		<canvas canvas-id="shareCanvas" id="shareCanvas" :style="{width: canvasWidth + 'px', height: canvasHeight + 'px', position: 'fixed', top: '-99999px', left: '-99999px'}"></canvas>

	</view>
</template>

<script setup name="">
	import CusHeader from '@/components/CusHeader/index.vue'
	import PageEmpty from '@/components/pageEmpty/index.vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { ref, getCurrentInstance } from 'vue'
	const { proxy } = getCurrentInstance()
	
	const userInfo = ref(null)
	const numInfo = ref(null)
	const queryParams = ref({
		page:1,
		limit:-1,
		userId:'',
		obtained:1
	})
	const list = ref([])
	const xzShow = ref(false)
	const xzInfo = ref(null)
	
	const saveShow = ref(false)
	const generatedImagePath = ref('')
	const isGenerating = ref(false)
	const canvasWidth = ref(0)
	const canvasHeight = ref(0)
	
	const changeTab = type => {
		queryParams.value.obtained = type;
		getList()
	}
	
	const showSz = item => {
		if(!item.lightUpDate) return
		xzInfo.value = item;
		xzShow.value = true;
	}
	
	const showSave = async () => {
		const xzImgList = list.value.filter(l => l.lightUpDate).map(l => l.imageUrl) || [];
		if (xzImgList.length === 0) {
			return proxy.$showToast('您还没有已获得的勋章可以分享哦');
		}
		if (isGenerating.value) return;

		isGenerating.value = true;
		uni.showLoading({ title: '分享图生成中...', mask: true });

		try {
			const imagePath = await generateShareImage(xzImgList);
			generatedImagePath.value = imagePath;
			saveShow.value = true;
		} catch (error) {
			proxy.$showToast(error.errMsg || '图片生成失败，请稍后重试');
			console.error('Share image generation failed:', error);
		} finally {
			uni.hideLoading();
			isGenerating.value = false;
		}
	}
	
	const saveImageToAlbum = () => {
		if (!generatedImagePath.value) return;
		uni.saveImageToPhotosAlbum({
			filePath: generatedImagePath.value,
			success: () => {
				proxy.$showToast('图片已保存到相册');
			},
			fail: (err) => {
				if (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied')) {
					uni.showModal({
						title: '保存失败',
						content: '您未授权保存图片到相册，请前往设置页开启权限。',
						showCancel: true,
						success: (res) => { if (res.confirm) { uni.openSetting(); } }
					})
				} else {
					proxy.$showToast('图片保存失败');
				}
			}
		})
	}
	
	const shareMedal = () => {
		if (!xzInfo.value || !xzInfo.value.imageUrl) {
			proxy.$showToast('勋章信息不完整，无法分享');
			return;
		}
		
		// 1. 使用 uni.previewImage 预览图片
		// 用户在预览界面可以长按图片，选择“发送给朋友”或“保存图片”
		uni.previewImage({
			urls: [xzInfo.value.imageUrl], // 需要预览的图片链接列表
			current: xzInfo.value.imageUrl, // 当前显示图片的链接
			success: () => {
				// 预览成功后，给用户一个提示
				proxy.$showToast('长按图片可保存或分享给好友', 3000); 
				// 提示后可以关闭弹窗，也可以不关，取决于产品需求
				// xzShow.value = false; 
			},
			fail: (err) => {
				console.error('预览图片失败', err);
				proxy.$showToast('预览图片失败，请稍后再试');
				
				// 预览失败的备用方案：尝试直接保存图片到相册
				uni.getImageInfo({
					src: xzInfo.value.imageUrl,
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.path,
							success: () => {
								proxy.$showToast('勋章图片已保存到相册，请前往微信选择分享给好友');
							},
							fail: (saveErr) => {
								proxy.$showToast('图片保存失败，请检查相册权限');
								console.error('保存图片失败', saveErr);
							}
						});
					},
					fail: (infoErr) => {
						proxy.$showToast('获取图片信息失败，无法保存');
						console.error('获取图片信息失败', infoErr);
					}
				});
			}
		});
	};

	/**
	 * @description 【核心】使用 Canvas 绘制分享图，并返回图片临时路径
	 * @param {Array} xzImgList - 已获得的勋章图片URL列表
	 * @returns {Promise<string>} 返回生成的图片临时路径
	 */
	const generateShareImage = (xzImgList) => {
		return new Promise(async (resolve, reject) => {
			try {
				const systemInfo = uni.getSystemInfoSync();
				const screenWidth = systemInfo.screenWidth;
				const upx2px = (rpx) => rpx / 2;

				const boxWidth = upx2px(622);
				const boxHeight = upx2px(720);
				
				canvasWidth.value = boxWidth;
				canvasHeight.value = boxHeight;
				
				const ctx = uni.createCanvasContext('shareCanvas', proxy);

				const imageUrls = {
					bg: 'https://oss.familydaf.cn/sxsnfile/20251218/1e4ec3ed6384416980ec32a49de49223.png',
					avatar: userInfo.value?.avatarPath || 'https://oss.familydaf.cn/sxsnfile/20251218/255ec4b8760b4dada7ffbcf1bf6b2928.png',
					qrCode: 'https://oss.familydaf.cn/sxsnfile/20251218/7d2336f662ac41b9811a863772263290.jpg',
				};
				xzImgList.forEach((url, index) => { imageUrls[`medal_${index}`] = url; });

				const imageInfos = await preloadImages(imageUrls);

				ctx.drawImage(imageInfos.bg.path, 0, 0, boxWidth, boxHeight);
				ctx.save(); 
				
				const paddingX = upx2px(36);
				const paddingTop = upx2px(34);
				
				// --- 1. 顶部信息 ---
				const avatarSize = upx2px(90);
				ctx.save();
				ctx.beginPath();
				ctx.arc(paddingX + avatarSize / 2, paddingTop + avatarSize / 2, avatarSize / 2, 0, 2 * Math.PI);
				ctx.clip();
				ctx.drawImage(imageInfos.avatar.path, paddingX, paddingTop, avatarSize, avatarSize);
				ctx.restore();

				ctx.fillStyle = '#FAE5B9';
				ctx.font = `bold ${upx2px(32)}px "PingFang-SC", sans-serif`;
				ctx.textBaseline = 'middle';
				ctx.fillText(`${userInfo.value?.realName || ''}的公益勋章墙`, paddingX + avatarSize + upx2px(18), paddingTop + avatarSize / 2);

				// --- 2. 勋章数量 (已根据反馈修复对齐和间距) ---
				const numTop = paddingTop + avatarSize + upx2px(10);
				const numLineBaseY = numTop + upx2px(40); // 设定一个公共的文字基线
				
				// 绘制数字部分
				ctx.font = `bold ${upx2px(40)}px "PingFang-SC", sans-serif`;
				ctx.fillStyle = '#FAE5B9';
				ctx.textBaseline = 'alphabetic'; // 使用字母基线对齐
				const medalsNumText = `${numInfo.value?.myMedals || 0}`;
				ctx.fillText(medalsNumText, paddingX, numLineBaseY);
				
				// 绘制文字部分
				const numTextMetrics = ctx.measureText(medalsNumText);
				ctx.font = `400 ${upx2px(28)}px "PingFang-SC", sans-serif`;
				ctx.fillStyle = '#FFFFFF';
				ctx.textBaseline = 'alphabetic'; // 使用相同的基线
				// 使用修复后的间距
				ctx.fillText('枚公益勋章', paddingX + numTextMetrics.width + upx2px(8), numLineBaseY);

				// --- 勋章墙 (逻辑不变) ---
				const numLineHeight = upx2px(56); // 按CSS中大的line-height计算
				const xzImgsTop = numTop + numLineHeight + upx2px(48);
				const xzImgsHeight = upx2px(328);
				const xzImgsBgRadius = upx2px(16);
				drawRoundRect(ctx, paddingX, xzImgsTop, boxWidth - 2 * paddingX, xzImgsHeight, xzImgsBgRadius, '#222632');
				
				const xzBoxPadding = upx2px(26);
				const medalSize = upx2px(111);
				const medalMargin = upx2px(23);
				xzImgList.forEach((url, index) => {
					const medalX = paddingX + xzBoxPadding + index * (medalSize + medalMargin);
					const medalY = xzImgsTop + (xzImgsHeight - medalSize) / 2;
					ctx.drawImage(imageInfos[`medal_${index}`].path, medalX, medalY, medalSize, medalSize);
				});

				// --- 3. 底部信息 (已根据反馈修复对齐和间距) ---
				const bottomTop = xzImgsTop + xzImgsHeight + upx2px(26);
				const qrSize = upx2px(100);
				ctx.save();
				ctx.beginPath();
				ctx.arc(paddingX + qrSize / 2, bottomTop + qrSize / 2, qrSize / 2, 0, 2 * Math.PI);
				ctx.clip();
				ctx.drawImage(imageInfos.qrCode.path, paddingX, bottomTop, qrSize, qrSize);
				ctx.restore();

				// 绘制二维码右侧文字 (修复垂直居中)
				const qrTextX = paddingX + qrSize + upx2px(24);
				const textLine1Height = upx2px(20);
				const textLineMargin = upx2px(20);
				const totalTextBlockHeight = textLine1Height * 2 + textLineMargin;
				const textBlockStartY = bottomTop + (qrSize - totalTextBlockHeight) / 2;

				ctx.fillStyle = '#FFFFFF';
				ctx.font = `400 ${upx2px(20)}px "PingFang-SC", sans-serif`;
				ctx.textBaseline = 'top';
				ctx.textAlign = 'left'; // 重置对齐
				ctx.fillText('扫描二维码', qrTextX, textBlockStartY);
				ctx.fillText('查看你的公益勋章', qrTextX, textBlockStartY + textLine1Height + textLineMargin);

				// --- 4. 绘制右下角 "善行少年" (已根据反馈修复对齐) ---
				ctx.fillStyle = '#FFFFFF';
				ctx.font = `italic 400 ${upx2px(22)}px "kuaikanshijieti", sans-serif`;
				ctx.textAlign = 'right';
				ctx.textBaseline = 'middle';
				// 添加微调值以改善自定义字体垂直居中效果
				const yOffset = upx2px(4); 
				ctx.fillText('善行少年', boxWidth - paddingX - upx2px(10), bottomTop + qrSize / 2 + yOffset);
				
				ctx.restore();
				// 绘制完成，导出图片
				ctx.draw(true, () => {
					uni.canvasToTempFilePath({
						canvasId: 'shareCanvas',
						success: (res) => resolve(res.tempFilePath),
						fail: (err) => reject(err)
					}, proxy);
				});

			} catch (error) {
				reject(error);
			}
		});
	}
	
	const preloadImages = (urls) => {
		const promises = Object.entries(urls).map(([key, url]) => {
			return new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: url,
					success: (res) => resolve({ key, ...res }),
					fail: reject
				});
			});
		});

		return Promise.all(promises).then(results => {
			return results.reduce((acc, res) => {
				acc[res.key] = res;
				return acc;
			}, {});
		});
	}

	const drawRoundRect = (ctx, x, y, width, height, radius, fillColor) => {
		ctx.save(); ctx.beginPath();
		ctx.moveTo(x + radius, y);
		ctx.arcTo(x + width, y, x + width, y + height, radius);
		ctx.arcTo(x + width, y + height, x, y + height, radius);
		ctx.arcTo(x, y + height, x, y, radius);
		ctx.arcTo(x, y, x + width, y, radius);
		ctx.closePath();
		if (fillColor) { ctx.fillStyle = fillColor; ctx.fill(); }
		ctx.restore();
	}
	
	const getList = () => {
		proxy.$api.get('/core/love/value/record/obtainedMedalList',queryParams.value).then(({data:res})=>{
			if(res.code!==0) return proxy.$showToast(res.msg)
			list.value = queryParams.value.obtained?res.data.list:res.data.list.filter(d=>!d.lightUpDate)
			list.value.forEach(l=>l.lightUpDate2 = new Date(l.lightUpDate).Format('yyyy-MM-dd'));
		})
	}
	
	onLoad((options)=>{
		try{
			userInfo.value = JSON.parse(uni.getStorageSync('userInfo'));
			numInfo.value = options.numInfo&&JSON.parse(options.numInfo);
			queryParams.value.userId = userInfo.value&&userInfo.value.id;
			getList()
		}catch(e){
			//TODO handle the exception
		}
	})
</script>

<style scoped lang="scss">
	/* --- 样式部分完全保持不变 --- */
	.scroll-view_H { white-space: nowrap; width: 100%; }
	.scroll-view-item_H { display: inline-block; width: 111rpx; height: 100%; margin-left: 23rpx; &:first-child{ margin-left: 0; } }
	.common_page { background: #FFFFFF; overflow: hidden; }
	.info { position: relative; margin-top: 31rpx; }
	.info-top { .avatar{ width: 98rpx; height: 98rpx;border-radius: 50%; } .name{ font-family: PingFang-SC, PingFang-SC; font-weight: bold; font-size: 32rpx; color: #252525; line-height: 54rpx; margin-left: 15rpx; } .level{ width: 137rpx; height: 42rpx; background: url('https://oss.familydaf.cn/sxsnfile/20251218/685ccddc71104cd4b1c6520e79cb9648.png') no-repeat; background-size: 100% 100%; margin-left: 20rpx; text{ font-family: PingFangSC, PingFang SC; font-weight: 600; font-size: 26rpx; color: #FFFFFF; line-height: 26rpx; margin-left: 16rpx; } } }
	.info-num { font-family: PingFang-SC, PingFang-SC; font-weight: bold; font-size: 44rpx; color: #252525; line-height: 48rpx; margin-top: 24rpx; text{ font-weight: 400; font-size: 24rpx; line-height: 40rpx; } }
	.info-memo { margin-top: 29rpx; font-family: PingFangSC, PingFang SC; font-weight: 400; font-size: 28rpx; color: #252525; line-height: 28rpx; text{ font-weight: bold; margin: 0 10rpx; } }
	.tab { position: relative; margin-top: 92rpx; }
	.tab-pre { padding: 0 65rpx; font-family: PingFangSC, PingFang SC; font-weight: 400; font-size: 32rpx; color: #676775; line-height: 48rpx; position: relative; &.active{ font-weight: bold; font-size: 36rpx; color: #252525; &::after{ content: ''; width: 42rpx; height: 6rpx; background: #77F99B; border-radius: 3rpx; position: absolute; left: 50%; margin-left: -21rpx; bottom: -15rpx; } } }
	.list { margin-left: -60rpx; overflow: hidden; flex: 1; overflow-y: auto; }
	.list-pre { width: calc(100% / 3 - 60rpx); margin-top: 48rpx; float: left; margin-left: 60rpx; image{ width: 180rpx; height: 176rpx; } .p{ font-family: PingFang-SC, PingFang-SC; font-weight: bold; font-size: 28rpx; color: #252525; line-height: 28rpx; text-align: center; margin-top: 24rpx; &.tip{ font-weight: 400; font-size: 24rpx; color: #676775; line-height: 24rpx; } } }
	.btn { width: 100%; 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; margin-top: 60rpx; }
	.dialog { position: fixed; left: 0; right: 0; top: 0; bottom: 0; background: #252525; .title{ font-family: FZZCHJW--GB1, FZZCHJW--GB1; font-weight: normal; font-size: 36rpx; color: #FDE2B2; line-height: 44rpx; text-align: center; margin-top: 113rpx; } .img{ width: 567rpx; height: 496rpx; background: url('https://oss.familydaf.cn/sxsnfile/20251218/c55f852845f147d09aea676a187531e6.png') no-repeat; background-size: 100% 100%; margin-top: 27rpx; image{ width: 279rpx; height: 275rpx; } } .name{ margin-top: 18rpx; image{ width: 53rpx; height: 67rpx; } text{ font-family: FZZCHJW--GB1, FZZCHJW--GB1; font-weight: normal; font-size: 64rpx; color: #FDE2B2; line-height: 77rpx; text-align: center; } } .date{ font-family: PingFangSC, PingFang SC; font-weight: 400; font-size: 26rpx; color: #B2AB95; line-height: 37rpx; text-align: center; margin-top: 23rpx; } .btn{ width: 368rpx; height: 88rpx; background: linear-gradient( 270deg, #F8D7AC 0%, #FEFAD9 100%); border-radius: 44rpx; margin-top: 89rpx; image{ width: 30rpx; height: 25rpx; } text{ font-family: PingFang-SC, PingFang-SC; font-weight: bold; font-size: 32rpx; color: #252525; line-height: 45rpx; margin-left: 14rpx; } } .close{ width: 48rpx; height: 48rpx; margin-top: 73rpx; } }
	
	.save {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, .8);
		
		.share_box {
			position: relative;
			width: calc(100% - 128rpx);

			.share_image {
				width: 100%;
				display: block;
			}

			.share_close_btn {
				width: 48rpx;
				height: 48rpx;
				position: absolute;
				top: 0;
				right: 0;
			}
		}

		.text {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #FFFFFF;
			line-height: 40rpx;
			text-align: center;
			margin-top: 44rpx;
		}
	}
</style>