<template>
	<view class="qrcodeStyle" :style="{'height':contentHeight}">
		<u-top-tips ref="uTips"></u-top-tips>
		<img :src="tempPic" mode="widthFix" style="width: 320px;margin-top: 20px;" />
		<canvas canvas-id="firstCanvas" class="sty-box" @error="canvasIdErrorCallback"></canvas>
		<view class="btn" :style="{background:mainColor}" @click="preservation">
			<Text>保存图片分享</Text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pageTitle: "活动海报",
				contentHeight: 0,
				mainColor: '',
				qrcode: '',
				fenxqrcode: '',
				UserInfo: '',
				tempPic: '',
				cover: '',
				id:0,
				
			}
		},
		created() {
			this.contentHeight = this.$utils.calcContentHeight(-40) + 'px';
			this.mainColor = this.$uiConfig.mainColor;
			this.secondary = this.$uiConfig.secondary;
			this.UserInfo = uni.getStorageSync('mall_UserInfo') ? uni.getStorageSync('mall_UserInfo') : {}
		},
		onLoad(options) {
			
			if (options ) {
				this.cover = options.cover
				this.title = options.title
				this.id = options.id
				this.init()
			}
			uni.setNavigationBarTitle({
				title: this.pageTitle,
			});
		},
		
		onReady() {

		},
		mounted() {

		},
		methods: {
			init() {
				uni.showNavigationBarLoading();
				this.request2({
						url: '/api/AppletUser/GetFenXiaoPoster',
						data: {
							IsOpenSchool: 2
						}
					},
					(res) => {
						uni.hideNavigationBarLoading()
						this.qrcode = res.data;
						this.getWeiXinQRCode()
					}
				);
			},
			getWeiXinQRCode() {
				let that = this
				uni.showNavigationBarLoading();
				let SmallShopId = that.UserInfo.SmallShopId ? that.UserInfo.SmallShopId : 0;
				if (SmallShopId == 0) {
					SmallShopId = that.UserInfo.UserSmallShopId ? that.UserInfo.UserSmallShopId : 0;
				}
				
				that.request2({
						url: '/api/AppletUser/GetWeiXinQRCodeForApplet',
						data: {
							Path: '/pages/index/index?user_id=' + that.UserInfo.UserId + '&SmallShopId=' + SmallShopId +'&id='+this.id+'&JumpType=10',
							With: that.qrcode.QrCodeSize,
						}
					},
					(res) => {
						uni.hideNavigationBarLoading()
						that.fenxqrcode = that.host2 + res.data;
						console.log(that.fenxqrcode)
						// that.fenxqrcode = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn1.hdfimg.com%2Fg8%2FM07%2FF3%2F55%2FtoYBAGBN-8GAFhCxAAAD9f6VmJ4867.png%3F_ms_%3D0f94&refer=http%3A%2F%2Fn1.hdfimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619574314&t=a6504efa99293d74cac2714e7ba8340f'
						
						let tmpTimeout = setTimeout(() => {
							that.drawCtx();
							clearTimeout(tmpTimeout)
						}, 100)
					}
				);
				
			},
			drawCtx() {
				uni.showLoading({
					title: "正在生成",
				});
				let ctx = uni.createCanvasContext("firstCanvas", this);
				let that = this;
				uni.getImageInfo({
					src: that.qrcode.PosterBgImg,
					success: function(image) {
						console.log('绘制')
						ctx.drawImage(image.path, 0, 0, 750, 1344); //绘制图	
						if (that.qrcode.IsShowNick == 0) {
							console.log('绘制用户名称')
							that.drawTitle(ctx); //用户名称
						}
						if (that.qrcode.IsShowTitle == 0) {
							console.log('绘制标题')
							that.drawTitle_t(ctx); //绘制标题
						}
						ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
						if(that.qrcode.IsShowCover==0){
							uni.getImageInfo({
								src:that.cover,
								success:function(image){
									console.log('活动封面图')
									ctx.drawImage(image.path, that.qrcode.CoverPaddingLeft, that.qrcode.CoverPaddingTop, that.qrcode.CoverWidth,
										that.qrcode.CoverHeight); //绘制分享图
									that.getqrcode(ctx)
								}
							})
						}else{
							that.getqrcode(ctx)
						}
						
						
					},
				});
			},
			
			getqrcode(ctx){
				let that = this
				if (that.qrcode.IsShowHead == 0) {
					console.log('绘制头像')
					uni.getImageInfo({ //头像
						src: that.UserInfo.Photo,
						success: function(image) {
							ctx.save(); // 先保存状态 已便于画完圆再用
							ctx.beginPath(); //开始绘制
							//先画个圆
							ctx.arc(that.qrcode.HeadSize / 2 + that.qrcode.HeadPaddingLeft, that.qrcode.HeadSize / 2 + that.qrcode.HeadPaddingTop,
								that.qrcode.HeadSize / 2, 0, Math.PI * 2, false);
							ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
							ctx.drawImage(image.path, that.qrcode.HeadPaddingLeft, that.qrcode.HeadPaddingTop, that.qrcode.HeadSize,
								that.qrcode.HeadSize); //绘制头像
							setTimeout(()=>{
								that.createqrcode(ctx)//生成二维码
							},100)
						
						},
					});
				} else {
					setTimeout(()=>{
						that.createqrcode(ctx)//生成二维码
					},100)
				}
			},
			drawTitle(ctx) {//用户名称处理
				let that = this
				let text = that.UserInfo.Name;
				ctx.fillStyle = that.qrcode.NickColor;
				ctx.setFontSize(that.qrcode.NickSize)
				ctx.fillText(text, that.qrcode.NickPaddingLeft, that.qrcode.NickPaddingTop);
				
			},
			drawTitle_t(ctx){//标题处理
				let that = this
				let text = that.title;
				ctx.fillStyle = that.qrcode.TitleColor;
				that.dealWords({
				  ctx: ctx,//画布上下文
				  fontSize: that.qrcode.TitleSize,//字体大小
				  word: text,//需要处理的文字
				  maxWidth: that.qrcode.TitleWidth,//一行文字最大宽度
				  x: that.qrcode.TitlePaddingLeft,//文字在x轴要显示的位置
				  y: that.qrcode.TitlePaddingTop,//文字在y轴要显示的位置
				  maxLine: that.qrcode.TitleRow//文字最多显示的行数
				})
			
			},
		
			//处理文字多出省略号显示
			  dealWords: function (options) {
			    options.ctx.setFontSize(options.fontSize);//设置字体大小
			    var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);//实际总共能分多少行
			    var count = allRow >= options.maxLine ? options.maxLine : allRow;//实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
			    var endPos = 0;//当前字符串的截断点
			    for (var j = 0; j < count; j++) {
			      var nowStr = options.word.slice(endPos);//当前剩余的字符串
			      var rowWid = 0;//每一行当前宽度  
			      if (options.ctx.measureText(nowStr).width > options.maxWidth) {//如果当前的字符串宽度大于最大宽度，然后开始截取
			        for (var m = 0; m < nowStr.length; m++) {
			          rowWid += options.ctx.measureText(nowStr[m]).width;//当前字符串总宽度
			          if (rowWid > options.maxWidth) {            
			            if (j === options.maxLine - 1) { //如果是最后一行
			              options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * (options.fontSize+6));  //(j+1)*18这是每一行的高度    
			            } else {
			              options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * (options.fontSize+6));
			            }
			            endPos += m;//下次截断点
			            break;
			          }
			        }
			      } else {//如果当前的字符串宽度小于最大宽度就直接输出
			        options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * (options.fontSize+6));
			      }
			    }
			  },
			createqrcode(ctx){
				let that = this
				ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
				if (that.qrcode.IsShowQrCode == 0) {
					console.log('绘制二维码')
					uni.getImageInfo({ //二维码
						src: that.fenxqrcode,
						success: function(image) {
							if (that.qrcode.QrCodeType == 0) {
								ctx.arc(that.qrcode.QrCodeSize / 2 + that.qrcode.QrCodePaddingLeft, that.qrcode.QrCodeSize / 2 + that.qrcode
									.QrCodePaddingTop, that.qrcode.QrCodeSize / 2, 0, Math.PI * 2, false);
								ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内		
							}
							ctx.drawImage(image.path, that.qrcode.QrCodePaddingLeft, that.qrcode.QrCodePaddingTop, that.qrcode.QrCodeSize,
								that.qrcode.QrCodeSize); //绘制二维码
							that.drawQrCode(ctx)
						},
					});
				} else {
					that.drawQrCode(ctx)
				}
			},
			drawQrCode(ctx) {
				let that = this;
				console.log('生成海报12')
				setTimeout(() => {
					ctx.draw(false, () => {
						uni.canvasToTempFilePath({
								x: 0,
								y: 0,
								width: 750,
								height: 1344,
								destWidth: 750.0,
								destHeight: 1344.0,
								canvasId: "firstCanvas",
								success: (res) => {
									uni.hideLoading();
									that.tempPic = res.tempFilePath;
								},
								fail(e) {
									console.log(e);
								},
							},
							that
						);
					});
				}, 200)
			},
			preservation() {
				uni.showLoading({
					title: "正在生成",
				});
				let that = this;
				uni.canvasToTempFilePath({
						canvasId: "firstCanvas",
						success: (res) => {
							uni.hideLoading();
							uni.showLoading({
								title: "正在保存",
							});
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									uni.showToast({
										title: "保存成功",
									});
								},
								fail: function(err) {
									if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
										uni.authorize({
											scope: 'scope.writePhotosAlbum',
											success: (res) => {
												console.log('11111');
											},
											fail: (res) => {
												uni.showModal({
													content: '检测到您没打开保存到相册权限，是否去设置打开？',
													confirmText: "确认",
													cancelText: '取消',
													success: (res) => {
														if (res.confirm) {
															uni.openSetting({
																success: (res) => {
																	console.log(res);
																	if (res.authSetting['scope.writePhotosAlbum']) {
																		that.preservation()
																	}
																}
															})
														} else {
															console.log('取消');
														}
													}
												})
											}
										})
									} else {
										that.$refs.uTips.show({
											title: "保存失败，请稍后重试",
											type: "error",
											duration: "2300",
										});
									}
								},
								complete: function() {
									uni.hideLoading();
								},
							});
						},
						fail: function(e) {
							console.log(e);
							that.$refs.uTips.show({
								title: "生成失败，请稍后重试",
								type: "error",
								duration: "2300",
							});
						},
					},
					this
				);
			}
		}
	}
</script>

<style>
	.qrcodeStyle {
		background: #f3f4f6;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.qrcodeStyle .btn {
		width: 80%;
		height: 50px;
		border-radius: 25px;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 20px;
	}

	.qrcodeStyle .imgbox {
		width: 70%;
		height: 515px;
		margin-left: 15%;
		position: relative;
		background-repeat: no-repeat;
		background-size: 100% 515px;
	}

	.qrcodeStyle .sty-box {
		width: 750px;
		height: 1344px;
		position: absolute;
		top: -1344px;
		left: -750px;
	}
</style>