<template>
	<u-popup 
	:show="show" 
	mode="center" 
	@close="close" 
	@open="open"
	bgColor="rgba(0,0,0,0)"
	>
		<view class="promotion-code">
			<!-- #ifdef MP -->
			<view class="promotion-code-info">
				<canvas canvas-id="canvas" class="canvas"></canvas>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<view class="promotion-code-info">
				<canvas v-if="!posterSrc" canvas-id="canvas" class="canvas promotion-canvas"></canvas>
				<image class="promotion-code-info-img" mode="scaleToFill" v-else :src="posterSrc"></image>
			</view>
			<!-- #endif -->
			<view class="promotion-code-but" @click="saveImage()">
				保存至相册
			</view>
			<view class="promotion-code-but" @click="copyText()">
				复制链接
			</view>
			<view v-if="!posterShow" class="promotion-code-clear" @click="show=false">
				<u-icon name="close-circle-fill" color="var(--gd-bgm-color)" size="28"></u-icon>
			</view>
		</view>
	</u-popup>
</template>

<script>
import { nextTick } from "vue"
import { commonConfig } from '@/common/config.js';
	export default {
		data() {
			return {
				show: false,
				
				shareShow:false,
				posterShow:false,
				posterSrc:'',
				posterSrcType:null,
				linkText: null,
				performInfo:{
					posterImg: 'https://img1.baidu.com/it/u=3302184040,3713353210&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703178000&t=3902211e35b62703882329c63cf27129',//'../../static/customPromotionCode/bgm1.png', // 剧目背景
					appletQrcode: 'https://t7.baidu.com/it/u=1127963623,72784497&fm=218&app=126&size=f242,150&n=0&f=JPEG&fmt=auto?s=361C1DC71A5A34D6877C593B0300C002&sec=1703178000&t=cc1d7c4413380f1e8769bae6ac5a66af', // '../../static/customPromotionCode/bgm2.png', // 二维码
				},//节目详情
				// firstGet:0,
			}
		},
		methods: {
			initData(data) {
				console.log(data)
				this.show = true
				this.performInfo.posterImg = data.posterImg
				this.performInfo.appletQrcode = data.url
				this.posterSrc = ''
				this.$nextTick(()=>{
					this.getCanvasInfo()
				})
			},
			open() {
				// console.log('open');
			},
			close() {
				this.show = false
				// console.log('close');
			},
			getCanvasInfo(){
				let that = this
				//.box获取class为box的元素，如果使用的id= 'box' 则使用'#box'
				const query = uni.createSelectorQuery();
				query.select('.promotion-canvas').boundingClientRect(data => {
				  that.getPoster(data.width,data.height)
				}).exec();
			},
			// 海报相关开始
			getPoster(w,h) {
				console.log(w,h)
				this.posterShow = true;
				this.shareShow = false;

				//前端生成海报
				uni.showLoading({
					title: '生成海报中'
				});
				
				// 前端生成海报开始
				let that = this;
				const ctx = uni.createCanvasContext('canvas', this);
				// 加载海报背景图
				uni.getImageInfo({
					src: this.performInfo.posterImg,
					success: res1 => {
						console.log("res1===",res1)
						const img1 = res1.path;

						// 加载海报二维码
						uni.getImageInfo({
							src: this.performInfo.appletQrcode,
							success: res2 => {
								console.log("res2===",res2)
								const img2 = res2.path;

								// 绘制海报背景图
								ctx.drawImage(img1, 0, 0, w, h);

								// 绘制海报二维码
								ctx.drawImage(img2, w/2-40, h/2+40, 70, 70);

								// 绘制完成后导出图片并显示
								ctx.draw(false, () => {
									uni.canvasToTempFilePath({
										canvasId: 'canvas',
										success: res3 => {
											this.posterShow = false
											this.posterSrc = res3.tempFilePath;
											this.posterSrcType = 'local';
										},
										fail: err => {
											this.posterShow = false
											console.error(err);
										},
									}, this);
								});
							},
							fail: err2 => {
								this.posterShow = false
								console.error(err2);
							},
						});
					},
					fail: err1 => {
						this.posterShow = false
						console.error("err1===",err1);
					},
					complete: () => {
						this.posterShow = false
						uni.hideLoading()
					}
				});
				// 前端生成海报结束
			},
			saveImage() {
				let that = this;
				uni.showLoading({
					title: '保存中'
				});
				// if (this.posterSrcType == 'local') {
				// 	let params = {
				// 		tempFilePath: that.posterSrc
				// 	}
				// 	that.saveImageToPhotosAlbum(params);
				// 	return
				// }
				uni.downloadFile({
					url: this.posterSrc,
					success(res) {
						if (res.statusCode === 200) {
							const systemInfo = uni.getSystemInfoSync(); // 调用 getSystemInfoSync() 函数获取系统信息
							console.log(systemInfo); // 打印输出系统信息对象
							if (systemInfo.ua.indexOf('MicroMessenger') != -1 ) {
							    uni.showToast({
							    	title: "微信浏览器不可下载，可长按图片保存",
							    	icon: 'none',
									duration: 4000
							    })
								return
							}
							// #ifdef MP
								that.saveImageToPhotosAlbum(res)
							// #endif
							// #ifdef H5
								var alink = document.createElement("a");
								alink.href = res.tempFilePath;
								alink.download = "pic"; //图片名
								alink.click();
								uni.showToast({
									title: '下载成功',
									icon: 'none'
								});
							// #endif
						} else {
							uni.showToast({
								title: '下载图片失败',
								icon: 'none'
							});
						}
					},
					fail(e) {
						console.log('下载图片失败', e);
						uni.hideLoading();
						uni.showToast({
							title: '下载图片失败',
							icon: 'none'
						});
						
					}
				});
			},
			saveImageToPhotosAlbum(res) {
				let that = this;
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success() {
						uni.showToast({
							title: '保存到相册成功',
							icon: 'success'
						});
					},
					fail(err) {
						console.log('保存图片失败', err);
						if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
							uni.getSetting({
								success(res) {
									if (!res.authSetting['scope.writePhotosAlbum']) {
										uni.showModal({
											title: '提示',
											content: '您还没有授权访问相册，请前往设置页面打开权限。',
											confirmText: '去设置',
											success(res) {
												if (res.confirm) {
													uni.openSetting();
												}
											}
										});
									} else {
										uni.showToast({
											title: '保存图片失败',
											icon: 'none'
										});
									}
								}
							});
						} else {
							uni.showToast({
								title: '保存图片失败',
								icon: 'none'
							});
						}
					},
					complete() {
						uni.hideLoading();
						that.posterShow = false;
					}
				});
			},
		
			copyText() {
			    uni.setClipboardData({
			        data: commonConfig.linkUrl + '?personsId='+this.distribution_user_info.userId,
			        success: function () {
			          uni.showToast({
			            title: '复制成功',
			            icon: 'success',
			            duration: 2000
			          });
			        }
			    });
			}
		}
	}
</script>

<style lang="scss" scoped>
	.promotion-code {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		.promotion-code-info {
			width: 548rpx;
			height: 784rpx;
			flex-shrink: 0;
			box-sizing: border-box;
			.canvas {
				width: 100%;
				height: 100%;
			}
			.promotion-code-info-img {
				width: 100%;
				height: 100%;
			}
		}
		.promotion-code-but {
			margin-top: 40rpx;
			width: 422rpx;
			height: 80rpx;
			background: var(--gd-but-color);
			border-radius: 40rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			font-size: 28rpx;
			font-family: SourceHanSansCN, SourceHanSansCN;
			font-weight: 500;
		}
		.promotion-code-clear {
			position: absolute;
			top: -10rpx;
			right: -10rpx;
		}
	}
</style>