<template>
	<view class="page">
		<view class="page-info">
			<view class="banner">
				<view class="title">{{tableData.schemeTitle}}</view>
				<view class="banner-info-top">
					<view>{{tableData.createDate}}</view>
					<!-- <view><u-icon name="eye"></u-icon>{{tableData.viewsNumber}}人</view> -->
				</view>
				<view class="banner-info-item">
					<!-- <image :src="tableData.coverImage" style="width: 100%; height: 100vw; border-radius: 10rpx; margin-top: 30rpx;"></image> -->
					<u-image width="100%" :src="imgurl+tableData.coverImage" border-radius="10" mode="widthFix"
						style="margin-top:8px;margin-right:8px;"></u-image>
				</view>
				<view class="">
					<view class="title">宣传内容</view>
					<rich-text v-if="tableData.promotionContent" :nodes="tableData.promotionContent"></rich-text>
				</view>
			</view>

		</view>
		<view class="page-footer" v-if="tableData.state=='5'">
			<view class="footer-service">
				<view class="fenxiang" @click="shareMsg">
					<u-icon name="zhuanfa" size="30"></u-icon>
					<text style="margin-left: 10px;">分享</text>
				</view>
			</view>
		</view>
		<!-- 分享背景遮罩层 -->
		<view v-if="showShareModal" class="share-mask" @click="closeShareModal">
			<view v-if="showShareModal" class="share-modal" :class="{ 'share-modal-animate': showShareModal }">
				<view class="share-option" @click="generatePoster">生成海报</view>
				<button class="share-option" open-type="share">分享微信</button>
				<view class="share-option" @click="closeShareModal">取消</view>
			</view>
		</view>
		<!-- 海报遮罩层 -->
		<view v-if="showPosterMask" class="poster-mask">
			<view class="poster-container">
				<view style="text-align: center;font-weight: bold;">宣传海报</view>
				<canvas canvas-id="mergeCanvas" id="mergeCanvas"
					:style="{ width: `${canvasWidth}px`, height: `${canvasHeight}px`, margin: '10px 0' }"></canvas>
				<view class="close-btn" @click="closePosterMask">×</view>
				<!-- 新增的保存按钮 -->
				<button class="save-btn"
					style="padding: 8px 0;border-radius: 15px;background-color: #3f9b6a;color: #fff;"
					@click="saveImage">保存到本地</button>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				tableData: {},
				joinShow: false,
				form: {
					name: '',
					pahone: '',
				},
				pagesize: {
					id: '',
					pageNumber: 0,
					pageSize: 10,
				},
				imgurl: '',
				showShareModal: false, // 分享拉起框是否显示
				showPosterMask: false, // 海报遮罩层是否显示
				posterUrl: '', // 海报图片地址
				mergedImageSrc: '',
				canvasWidth: '',
				canvasHeight: '',
				imgUrls: []
			};
		},
		onLoad(option) {
			this.imgurl = this.$img
			if (option.id) {
				this.pagesize.id = option.id
			}

			this.$http.sendRequest('/cerePromotion/queryByPage', 'POST', this.pagesize, 1).then(res => {
				this.tableData = res.data.data.content[0]
				this.imgUrls.push(this.imgurl + this.tableData.coverImage)
			})
		},
		onReady() {},
		mounted() {


		},
		methods: {
			// 点击分享按钮
			shareMsg() {
				this.showShareModal = true;
			},
			// 关闭分享拉起框
			closeShareModal() {
				this.showShareModal = false;
			},
			// 生成海报
			generatePoster() {
				this.closeShareModal()
				this.$http.sendRequest(`/cerePromotion/getSharePic/${this.tableData.id}`, 'GET', '', 1).then(res => {
					this.posterUrl = this.imgurl + res.data.data
					this.imgUrls.push(this.imgurl + res.data.data)
					this.mergeImages()
					this.showPosterMask = true;
				})

				// setTimeout(() => {
				//   this.posterUrl = 'https://dummyimage.com/800x600/ff0000/ffffff'; // 替换为真实的海报图片地址
				//   this.showPosterMask = true;
				// }, 1000);
			},
			getImageInfo(src) {
				return new Promise((resolve, reject) => {
					wx.getImageInfo({
						src,
						success: (res) => resolve(res),
						fail: (res) => reject(res)
					})
				});
			},

			mergeImages(imgs) {

				const imgUrls = this.imgUrls
				const imgPromises = imgUrls.map((url) => {
					return new Promise((resolve, reject) => {
						uni.getImageInfo({
							src: url,
							success: (res) => {
								// 直接传递图片路径，无需创建 Image 对象
								resolve({
									path: res.path,
									width: res.width,
									height: res.height
								});
							},
							fail: (err) => {
								console.error('获取图片信息失败:', err);
								reject(err);
							}
						});
					});
				});

				Promise.all(imgPromises)
					.then((imgInfos) => {
						let maxHeight = 400;
						let totalWidth = 300;
						let scaledWidth = 0
						let scaledHeight = 0
						imgInfos.forEach((imgInfo, index) => {
							if (index === 0) {
								const imgInfo = imgInfos[index];
								const imgRatio = imgInfo.width / imgInfo.height; // 图片的宽高比例
								const canvasRatio = totalWidth / maxHeight; // 画布的宽高比例
								if (imgRatio > canvasRatio) {
									// 图片更宽，按宽度缩放
									scaledWidth = totalWidth;
									scaledHeight = maxHeight / imgRatio;
								} else {
									// 图片更高，按高度缩放
									scaledHeight = maxHeight;
									scaledWidth = totalWidth * imgRatio;
								}

								// 设置画布的宽度和高度为缩放后的图片宽度和高度
								this.canvasWidth = scaledWidth;
								this.canvasHeight = scaledHeight;
							}
							maxHeight = Math.max(maxHeight, imgInfo.height);
							totalWidth += imgInfo.width;
						});

						if (totalWidth === 0 || maxHeight === 0) {
							console.error('计算得到的画布尺寸为0');
							return;
						}

						const ctx = uni.createCanvasContext('mergeCanvas');
						uni.getSystemInfo({
							success: (systemInfo) => {
								// 处理第一张图片，按窗口宽高比例缩放
								const firstImgInfo = imgInfos[0];
								// 清空画布并设置缩放
								ctx.setFillStyle('white');
								ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

								// 绘制第一张图片作为背景
								ctx.drawImage(
									firstImgInfo.path,
									0,
									0,
									this.canvasWidth,
									this.canvasHeight,
								);
								const secondImgInfo = imgInfos[1];
								// 绘制第二张图片在第一张图片上层右下角
								ctx.drawImage(
									secondImgInfo.path,
									this.canvasWidth-100,
									this.canvasHeight-100,
									100,
									100
								);
								setTimeout(() => {
									// 绘制完成后生成图片
									ctx.draw(false, () => {
										uni.canvasToTempFilePath({
											canvasId: 'mergeCanvas',
											success: (res) => {
												console.log('生成临时文件成功，路径:', res
													.tempFilePath);
												this.mergedImageSrc = res
													.tempFilePath;
											},
											fail: (err) => {
												console.error('生成临时文件失败', err);
											}
										});
									});
								}, 1000)

							},
							fail: (err) => {
								console.error('获取设备信息失败', err);
							}
						});
					})
					.catch((err) => {
						console.error('获取图片信息失败或图片加载失败', err);
					})
			},

			// 关闭海报遮罩层
			closePosterMask() {
				this.showPosterMask = false;
				this.mergedImageSrc = '';
			},
			onShareAppMessage() {
				return {
					title: this.tableData.schemeTitle,
					imageUrl: this.imgurl + this.tableData.coverImage,
					path: `/pagesA/projectManagement/projectDetails?id=${this.tableData.id}`,
					success(res) {
						uni.showToast({
							icon: 'none',
							title: '分享成功'
						})
					},
					fail(err) {
						console.log('分享失败', err);
					}
				};
			},
			saveImage() {
				// 获取图片信息
				uni.getImageInfo({
					src: this.mergedImageSrc,
					success: (res) => {
						const tempFilePath = res.path
						// 检查保存相册权限
						uni.getSetting({
							success: (settingRes) => {
								if (!settingRes.authSetting['scope.writePhotosAlbum']) {
									// 没有权限，请求权限
									uni.authorize({
										scope: 'scope.writePhotosAlbum',
										success: () => {
											// 授权成功，保存图片
											this.saveImageToAlbum(tempFilePath);
										},
										fail: () => {
											// 授权失败，提示用户手动开启权限
											uni.showModal({
												title: '提示',
												content: '请在设置中开启保存相册权限',
												success: (modalRes) => {
													if (modalRes.confirm) {
														uni.openSetting();
													}
												}
											});
										}
									});
								} else {
									// 已有权限，保存图片
									this.saveImageToAlbum(tempFilePath);
								}
							}
						});
					},
					fail: (err) => {
						console.error('获取图片信息失败:', err);
						uni.showToast({
							title: '获取图片信息失败',
							icon: 'none'
						});
					}
				});
			},
			saveImageToAlbum(tempFilePath) {
				uni.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						uni.showToast({
							title: '图片保存成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						console.error('保存图片到相册失败:', err);
						uni.showToast({
							title: '保存图片到相册失败',
							icon: 'none'
						});
					}
				});
			},
		}
	};
</script>

<style scoped lang="scss">
	.page {
		position: relative;
		width: 100%;
		min-height: 94vh;
		overflow-x: hidden;
		// overflow-y: auto;
	}

	.page-info {
		width: 100%;
		padding: 24rpx;
	}

	// 活动详情
	.banner {
		width: 100%;
		margin-top: 10rpx;
		border-radius: 30rpx;
		background-color: #fff;
		padding: 24rpx 30rpx;
		color: #888D9C;

		.title {
			font-weight: 700;
			color: #3D3D3D;
			font-size: 30rpx;
			margin-bottom: 30rpx;
		}

		.banner-info-top {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 30rpx;
		}
	}

	// 活动信息
	.info-box {
		margin-top: 30rpx;

		.title {
			font-weight: 700;
			color: #3D3D3D;
			font-size: 28rpx;
			margin-bottom: 10rpx;
		}

		.info-item {
			font-size: 26rpx;
			line-height: 50rpx;
		}
	}

	/* 底部 */
	.page-footer {
		position: fixed;
		left: 0;
		bottom: 0;
		display: flex;
		justify-content: space-evenly;
		// align-items: center;
		// justify-content: center;
		width: 100%;
		height: 120rpx;
		background-color: #FFFFFF;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.footer-btn {
			padding: 0 20px;
			margin-top: 20rpx;
		}

		.footer-service {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 90%;
			height: 100%;

			text {
				margin-top: 6rpx;
				line-height: 42rpx;
			}

			.fenxiang {
				text-align: center;
				background-color: #3f9b6a;
				width: 100%;
				padding: 7px 0;
				border-radius: 10px;
				color: #fff;
				// display: flex;
				font-size: 16px;
				align-items: center;
			}
		}
	}

	.share-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		z-index: 99;
	}

	.share-modal {
		position: fixed;
		bottom: -200px;
		/* 初始位置在屏幕外 */
		left: 0;
		right: 0;
		background-color: #fff;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
		// padding: 10px;
		z-index: 100;
		transition: bottom 0.3s ease;
		/* 添加过渡效果 */
	}

	.share-modal-animate {
		bottom: 0;
		/* 动画结束位置 */
	}

	.share-option {
		padding: 15px;
		text-align: center;
		border-bottom: 1px solid #eee;
		background-color: #fff;

	}

	.poster-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 101;

	}

	.poster-container {
		position: relative;
		background-color: #fff;
		padding: 10px;
		border-radius: 10px;
		// height: 400px;
		width: 90%;
	}

	.close-btn {
		position: absolute;
		top: 10px;
		right: 10px;
		font-size: 20px;
		cursor: pointer;
	}

	button {
		padding: 0;
		margin: 0;
		border: 1px solid transparent;
		line-height: 1;
		font-size: 14px;
	}

	button::after {
		border: none;
	}
</style>