<template>
	<CustomPopup v-model="show" mode="center" width="680rpx" bgColor="transparent" :maskClosable="true">
		<view class="poster-popup-content">

			<!-- Canvas (Hidden) -->
			<canvas canvas-id="posterCanvas" class="poster-canvas"
				:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>

			<!-- Generated Image -->
			<view class="image-container" v-if="posterImage">
				<image :src="posterImage" mode="widthFix" class="poster-img" @longpress="savePoster"></image>
				<view class="tips">长按保存图片到相册</view>
			</view>
			<view class="loading-box" v-else>
				<u-loading mode="circle" size="60" color="#fff"></u-loading>
				<text class="loading-text">海报生成中...</text>
			</view>
		</view>
	</CustomPopup>
</template>

<script>
import CustomPopup from '@/components/custom-popup.vue';

export default {
	name: 'PosterPopup',
	components: {
		CustomPopup
	},
	props: {
		product: {
			type: Object,
			default: () => ({})
		},
		userInfo: {
			type: Object,
			default: () => ({})
		},
		qrcodeUrl: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			show: false,
			posterImage: '',
			canvasWidth: 350, // px
			canvasHeight: 530, // px
			ctx: null
		};
	},
	methods: {
		open() {
			this.show = true;
			if (!this.posterImage) {
				this.generatePoster();
			}
		},
		close() {
			this.show = false;
		},
		async generatePoster() {
			uni.showLoading({ title: '生成中...' });
			try {
				// 确保Canvas元素已渲染
				await new Promise(resolve => setTimeout(resolve, 100));

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

				// Setup dimensions
				const sysInfo = uni.getSystemInfoSync();
				const baseScale = (sysInfo.windowWidth || 375) / 750;
				// 清晰度与稳定性折中：按设备像素比绘制，但最多放大到 2 倍
				const renderRatio = Math.min(Math.max(sysInfo.pixelRatio || 1, 1), 2);
				const scale = baseScale * renderRatio;

				// User request: Canvas 340px, Padding 10px.
				// Mapping to rpx: 340px -> 680rpx, 10px -> 20rpx.
				const width = Math.floor(680 * scale);
				const height = Math.floor(1140 * scale);
				const padding = 20 * scale;

				// 确保Canvas尺寸在合理范围内
				const maxCanvasSize = 2000; // 保守上限，兼顾清晰度与稳定性
				if (width > maxCanvasSize || height > maxCanvasSize) {
					// 缩放Canvas尺寸到合理范围
					const scaleRatio = Math.min(maxCanvasSize / width, maxCanvasSize / height, 1);
					const scaledWidth = Math.floor(width * scaleRatio);
					const scaledHeight = Math.floor(height * scaleRatio);
					this.canvasWidth = scaledWidth;
					this.canvasHeight = scaledHeight;
				} else {
					this.canvasWidth = width;
					this.canvasHeight = height;
				}

				// 1. Draw Background (Gradient, Rounded)
				// linear-gradient(0deg, #FBFFFF 0%, #BFFCFE 100%) -> Bottom to Top
				const grd = ctx.createLinearGradient(0, this.canvasHeight, 0, 0);
				grd.addColorStop(0, '#FBFFFF');
				grd.addColorStop(1, '#BFFCFE');

				this.roundRect(ctx, 0, 0, this.canvasWidth, this.canvasHeight, 36 * scale, grd);

				// 2. Draw Product Cover
				const coverPath = await this.getImageInfo(this.product.cover || '/static/img/1.png', '/static/img/1.png');
				// Image width = Canvas width - 2 * padding
				const imgWidth = this.canvasWidth - (2 * padding);
				const coverHeight = imgWidth; // Square cover
				const coverX = padding;
				const coverY = padding;

				ctx.save();
				// Rounded corners for the cover image itself? 
				// Prototype usually has rounded corners for the cover too.
				this.roundRectPath(ctx, coverX, coverY, imgWidth, coverHeight, 24 * scale, true, true, true, true);
				ctx.clip();
				try {
					if (coverPath) {
						ctx.drawImage(coverPath, coverX, coverY, imgWidth, coverHeight);
					} else {
						throw new Error('coverPath is empty');
					}
				} catch (e) {
					console.error('Draw cover image error:', e);
					// 绘制失败时使用默认颜色块
					ctx.setFillStyle('#f0f0f0');
					ctx.fillRect(coverX, coverY, imgWidth, coverHeight);
				}
				ctx.restore();

				// 3. Draw User Info
				const moveDownY = 20 * scale;
				const contentPadding = 30 * scale;

				const avatarSize = 80 * scale;
				const avatarX = padding;
				const avatarY = coverY + coverHeight - (avatarSize / 2) + moveDownY;

				// Avatar Border/Background
				ctx.beginPath();
				ctx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2 + 2 * scale, 0, 2 * Math.PI);
				ctx.setFillStyle('#FFFFFF');
				ctx.fill();

				// Avatar Image
				const avatarUrl = this.userInfo.imgPath || 'https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/logo3.png';
				const avatarPath = await this.getImageInfo(avatarUrl, avatarUrl);
				ctx.save();
				ctx.beginPath();
				ctx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2, 0, 2 * Math.PI);
				ctx.clip();
				try {
					if (avatarPath) {
						ctx.drawImage(avatarPath, avatarX, avatarY, avatarSize, avatarSize);
					} else {
						throw new Error('avatarPath is empty');
					}
				} catch (e) {
					console.error('Draw avatar error:', e);
					// 绘制失败时使用默认颜色块
					ctx.setFillStyle('#f0f0f0');
					ctx.fillRect(avatarX, avatarY, avatarSize, avatarSize);
				}
				ctx.restore();

				// User Name & Recomm Text
				// Align with avatar
				const userInfoY = coverY + coverHeight + 25 * scale + moveDownY;
				const textLeftX = avatarX + avatarSize + 16 * scale;

				ctx.setFillStyle('#1D1D1D');
				ctx.setFontSize(28 * scale);
				ctx.setTextAlign('left');
				ctx.fillText(this.userInfo.nickName || '微信用户', textLeftX, userInfoY);

				ctx.setFillStyle('#666666');
				ctx.setFontSize(26 * scale);
				ctx.setTextAlign('right');
				// Align to right padding edge
				ctx.fillText('推荐您一本好书', this.canvasWidth - padding, userInfoY);
				ctx.setTextAlign('left'); // Reset

				// 4. Product Info
				let currentY = coverY + coverHeight + 110 * scale + moveDownY;

				// Title
				ctx.setFillStyle('#1D1D1D');
				const titleFontSize = 34 * scale;
				ctx.setFontSize(titleFontSize);
				const title = this.product.bookName || '未知书名';
				// Width constraint: Canvas width - 2*contentPadding
				const lastTitleY = this.drawText(ctx, title, contentPadding, currentY, this.canvasWidth - 2 * contentPadding, titleFontSize * 1.5);
				currentY = lastTitleY + 60 * scale;

				// Author
				ctx.setFillStyle('#666666');
				const authorFontSize = 26 * scale;
				ctx.setFontSize(authorFontSize);
				ctx.fillText(`作者: ${this.product.author || '未知'}`, contentPadding, currentY);
				currentY += 70 * scale;

				// Price
				ctx.setFillStyle('#D81A00');
				const priceFontSize = 44 * scale;
				ctx.setFontSize(priceFontSize);
				const price = `¥ ${this.product.sellPrice || '0.00'}`;
				const priceWidth = ctx.measureText(price).width;
				ctx.fillText(price, contentPadding, currentY);

				// Original Price
				ctx.setFillStyle('#999999');
				ctx.setFontSize(26 * scale);
				const origPrice = `原价: ¥ ${this.product.price || '0.00'}`;
				ctx.fillText(origPrice, contentPadding + priceWidth + 20 * scale, currentY);

				// Divider
				const footerHeight = 180 * scale;
				const dividerY = this.canvasHeight - footerHeight;

				ctx.setStrokeStyle('#dddddd');
				if (typeof ctx.setLineDash === 'function') {
					ctx.setLineDash([8, 8]);
				}
				ctx.beginPath();
				ctx.moveTo(padding, dividerY);
				ctx.lineTo(this.canvasWidth - padding, dividerY);
				ctx.stroke();
				if (typeof ctx.setLineDash === 'function') {
					ctx.setLineDash([]);
				}

				// 5. Footer (Store & QR)
				const footerContentY = dividerY + 50 * scale;

				// Store Name
				ctx.setFillStyle('#1D1D1D');
				ctx.setFontSize(32 * scale);
				const storeName = '书嗨循环书店';
				const storeNameWidth = ctx.measureText(storeName).width;
				ctx.fillText(storeName, padding, footerContentY + 10 * scale);

				// Mascot Icon (Behind Store Name)
				const iconSize = 70 * scale;
				const iconX = padding + storeNameWidth + 40 * scale;
				// Align vertically with text (text baseline is at footerContentY + 10*scale)
				// Center icon relative to text cap height
				const iconY = footerContentY + 10 * scale - (30 * scale) / 2 - iconSize / 2 + 40;
				try {
					const iconPath = await this.getImageInfo('/pages-sell/static/goods/icon-shuhai.png', '/pages-sell/static/goods/icon-shuhai.png');
					if (iconPath) {
						ctx.drawImage(iconPath, iconX, iconY, iconSize, iconSize);
					}
				} catch (e) {
					console.error('Draw icon error:', e);
				}

				ctx.setFillStyle('#666666');
				ctx.setFontSize(22 * scale);
				ctx.fillText('不辜负每一个爱书的人', padding, footerContentY + 54 * scale);

				// QR Code
				const qrSize = 130 * scale;
				const qrX = this.canvasWidth - padding - qrSize;
				const qrY = footerContentY - 20 * scale;

				// Use gzh.png as the QR code (Figure 2)
				try {
					if (this.qrcodeUrl) {
						const qrPath = await this.getImageInfo(this.qrcodeUrl);
						if (qrPath) {
							ctx.drawImage(qrPath, qrX, qrY, qrSize, qrSize);
						}
					}
				} catch (e) {
					console.error('Draw QR code error:', e);
				}
				// 如果二维码获取失败，不影响海报创建，继续后续绘制

				// 使用Promise包装draw方法，确保绘制完成
				await new Promise((resolve) => {
					ctx.draw(false, () => {
						// 延长等待时间，确保绘制完成
						setTimeout(() => {
							resolve();
						}, 500);
					});
				});

				// 转换Canvas为图片（增加重试，兼容部分机型导出时机问题）
				const tempFilePath = await this.canvasToTempFilePathWithRetry({
					canvasId: 'posterCanvas',
					// 直接导出实际绘制尺寸，避免“导出阶段再放大”导致模糊
					destWidth: this.canvasWidth,
					destHeight: this.canvasHeight,
					fileType: 'png',
					quality: 0.9
				}, 3);
				this.posterImage = tempFilePath;
				uni.hideLoading();

			} catch (e) {
				console.error('Generate poster error:', e);
				uni.hideLoading();
				uni.showToast({ title: '生成出错', icon: 'none' });
			}
		},
		canvasToTempFilePathWithRetry(options, retries = 2) {
			return new Promise((resolve, reject) => {
				const attempt = (left) => {
					uni.canvasToTempFilePath({
						...options,
						success: (res) => resolve(res.tempFilePath),
						fail: (err) => {
							if (left > 0) {
								setTimeout(() => attempt(left - 1), 180);
								return;
							}
							reject(err);
						}
					}, this);
				};
				attempt(retries);
			});
		},
		getImageInfo(url, fallback = '') {
			return new Promise((resolve) => {
				const safeFallback = fallback || '/static/img/1.png';
				const src = typeof url === 'string' ? url : '';
				if (!src) {
					resolve(safeFallback);
					return;
				}
				// 本地资源直接返回
				if (src.startsWith('/') || src.startsWith('static/')) {
					resolve(src);
					return;
				}
				// 优先使用 getImageInfo，兼容更多端图片解码
				uni.getImageInfo({
					src,
					success: (res) => {
						resolve(res.path || res.tempFilePath || safeFallback);
					},
					fail: () => {
						// 降级下载，失败时不抛异常，避免中断整张海报生成
						uni.downloadFile({
							url: src,
							success: (downloadRes) => {
								if (downloadRes.statusCode === 200 && downloadRes.tempFilePath) {
									resolve(downloadRes.tempFilePath);
									return;
								}
								resolve(safeFallback);
							},
							fail: () => resolve(safeFallback)
						});
					}
				});
			});
		},
		roundRect(ctx, x, y, w, h, r, fillStyle) {
			ctx.beginPath();
			ctx.moveTo(x + r, y);
			ctx.arcTo(x + w, y, x + w, y + h, r);
			ctx.arcTo(x + w, y + h, x, y + h, r);
			ctx.arcTo(x, y + h, x, y, r);
			ctx.arcTo(x, y, x + w, y, r);
			ctx.closePath();
			if (fillStyle) {
				ctx.setFillStyle(fillStyle);
				ctx.fill();
			}
		},
		roundRectPath(ctx, x, y, w, h, r, tl, tr, br, bl) {
			ctx.beginPath();
			ctx.moveTo(x + r, y);
			if (tr) ctx.arcTo(x + w, y, x + w, y + h, r);
			else ctx.lineTo(x + w, y);

			if (br) ctx.arcTo(x + w, y + h, x, y + h, r);
			else ctx.lineTo(x + w, y + h);

			if (bl) ctx.arcTo(x, y + h, x, y, r);
			else ctx.lineTo(x, y + h);

			if (tl) ctx.arcTo(x, y, x + w, y, r);
			else ctx.lineTo(x, y);

			ctx.closePath();
		},
		drawText(ctx, str, x, y, maxWidth, lineHeight) {
			if (!str) return y;
			let line = '';
			let currentY = y;
			for (let i = 0; i < str.length; i++) {
				const testLine = line + str[i];
				const metrics = ctx.measureText(testLine);
				if (metrics.width > maxWidth && i > 0) {
					ctx.fillText(line, x, currentY);
					line = str[i];
					currentY += lineHeight;
				} else {
					line = testLine;
				}
			}
			ctx.fillText(line, x, currentY);
			return currentY;
		},
		savePoster() {
			if (!this.posterImage) return;
			uni.saveImageToPhotosAlbum({
				filePath: this.posterImage,
				success: () => {
					uni.showToast({ title: '保存成功', icon: 'success' });
				},
				fail: (err) => {
					console.log(err);
					// Handle auth denial
					uni.showModal({
						title: '提示',
						content: '需要保存到相册权限',
						success: (res) => {
							if (res.confirm) {
								uni.openSetting();
							}
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.poster-popup-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
	padding: 0; // Remove padding
	background: transparent;
}

.poster-canvas {
	position: fixed;
	left: 10000px; // Hide canvas off-screen
}

.image-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 680rpx; // Match canvas width

	.poster-img {
		width: 100%;
		height: auto;
		border-radius: 36rpx;
	}

	.tips {
		margin-top: 20rpx;
		color: #fff;
		font-size: 24rpx;
	}
}

.loading-box {
	width: 680rpx;
	height: 1300rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background: linear-gradient(0deg, #FBFFFF 0%, #BFFCFE 100%);
	border-radius: 36rpx;

	.loading-text {
		margin-top: 20rpx;
		color: #666;
	}
}
</style>
