<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:'',
			}
		},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'):{}
			
			 
			 
		},
		onReady(){
			this.init()
		},
		mounted() {
			
			 uni.setNavigationBarTitle({
			   title: this.pageTitle,
			 });
		},
		methods: {
			init(){
				uni.showNavigationBarLoading();
				this.request2(
				 {
					url: '/api/AppletUser/GetFenXiaoPoster',
					data: {}
				 },	
			  (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;
			  }
			  console.log('pages/index/index?user_id=' + that.UserInfo.UserId+'&SmallShopId='+ SmallShopId)
			  	that.request2(
			  	 {
			  		url: '/api/AppletUser/GetWeiXinQRCodeForApplet',
			  		data: {
						Path:'pages/index/index?user_id=' + that.UserInfo.UserId+'&SmallShopId='+ SmallShopId,
						With:that.qrcode.QrCodeSize,
					}
			  	 },	
			    (res) => {
			  	uni.hideNavigationBarLoading()
			  	that.fenxqrcode = that.host2+res.data;
				// that.fenxqrcode = 'https://mallapi.oytour.com/upfile/temporary/864369a3-8da8-4735-bcc8-a2dfe5c6f357.jpg'
				console.log(that.fenxqrcode)
				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.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);//绘制头像
				  			        ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
				  			        
				  			    
				  	   	
						
						if(that.qrcode.IsShowQrCode==0){ //二维码
						console.log('绘制二维码')
							  uni.getImageInfo({
								// src: that.UserInfo.Photo,
								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)	
						}
				  	  },
				  	});
				  }else{
					  
					  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)	
					  }
				  }
				

			    },
			  });	
			
			  
			  
		  },
	
		  drawTitle(ctx){
			  let that = this
			  let text = that.UserInfo.Name;
			  ctx.setFillStyle = that.qrcode.NickColor; 
			  ctx.setFontSize(that.qrcode.NickSize)
			  ctx.fillText(text, that.qrcode.NickPaddingLeft, that.qrcode.NickPaddingTop);
			  ctx.restore();
		  },
		  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-top: 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>
