<template>
	<view class="qrcodeLiveStyle" :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: "",
				bgPic: "",
				qrCodeConfig: {}, //二维码配置
				qrCodeSize: 126, //二维码宽高
				qrCodeLeft: 595, //二维码左边距
				qrCodeTop: 1200, //二维码上边距
				halfCode: 63, //二维码一半高度
				type: 0, //二维码形状(0-圆形，1-方形)
			};
		},
		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(option) {
			this.bgPic =
				option.pic ? option.pic:
				"https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1597312414000_253.jpg";
			if (option.left) {
				this.qrCodeLeft = parseInt(option.left);
			}
			if (option.top) {
				this.qrCodeTop = parseInt(option.top);
			}
			if (option.size) {
				this.qrCodeSize = parseInt(option.size);
				this.halfCode = parseInt(option.size / 2);
			}
			if (option.type) {
				this.type = parseInt(option.type);
			}
		},
		onReady() {
			this.init();
		},
		mounted() {
			uni.setNavigationBarTitle({
				title: this.pageTitle,
			});
		},
		methods: {
			init() {
				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;
				}
				let Up = uni.getStorageSync("mall_UserInfo") ? uni.getStorageSync("mall_UserInfo").UserPageType : 0;
				that.request2({
						url: "/api/AppletUser/GetWeiXinQRCodeForApplet",
						data: {
							// Path: "pages/live/index?user_id=" + that.UserInfo.UserId+'&SmallShopId='+ SmallShopId,
							Path: "/pages/index/index?user_id=" + that.UserInfo.UserId + '&SmallShopId=' + SmallShopId + '&JumpType=2' +
								"&Up=" + Up,
							With: that.qrcode.QrCodeSize,
						},
					},
					(res) => {
						uni.hideNavigationBarLoading();
						that.fenxqrcode = that.host2 + res.data;
						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.bgPic,
					success: function(image) {
						ctx.drawImage(image.path, 0, 0, 750, 1344); //绘制图
						uni.getImageInfo({
							//头像
							src: that.fenxqrcode,
							success: function(image) {
								ctx.save();
								ctx.beginPath();
								if (that.type == 0) {
									ctx.arc(that.qrCodeLeft + that.halfCode, that.qrCodeTop + that.halfCode, that.halfCode, 0, Math.PI * 2);
									ctx.clip();
								}
								ctx.setFillStyle("#ffffff");
								ctx.fill();
								// ctx.drawImage(image.path, 595, 1200, 126, 126); //绘制头像
								ctx.drawImage(image.path, that.qrCodeLeft, that.qrCodeTop, that.qrCodeSize, that.qrCodeSize); //绘制头像
								that.drawQrCode(ctx);
							},
						});
						//   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) {
						//               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("绘制二维码");

						//     } 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;
				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) => {},
											fail: (res) => {
												uni.showModal({
													content: "检测到您没打开保存到相册权限，是否去设置打开？",
													confirmText: "确认",
													cancelText: "取消",
													success: (res) => {
														if (res.confirm) {
															uni.openSetting({
																success: (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>
	.qrcodeLiveStyle {
		background: #f3f4f6;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

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

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

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