<template>
	<view>
		<view class="ceng" :hidden="hideToast" @tap="cancelPopup"></view>
		<view class="sharePop" :hidden="hideToast">
			<!-- <view class="share-tit">分享到</view> -->
			<view class="share-btn">
				<button class="friend" open-type="share" v-if="!isVideoScene">
					<image src="/static/pages/images/wechat.png"></image>
					微信好友
				</button>
				<view class="poster" @tap="generatePoster" v-if="codeUrl">
					<image src="/static/pages/images/poster.png"></image>
					生成海报
				</view> 
			</view>
			<view class="cancel" @tap="cancelPopup">取消</view>
		</view>

		<canvas class="canvas" style="width:400px;height:460px;" canvas-id="share"></canvas>
		<!-- 分享弹窗 -->
		<view class="ceng" :hidden="hidePoster" @tap="showPoster"></view>
		<view class="beshare" :hidden="hidePoster">
			<view class="beshares">
				<image src="/static/pages/images/close.png" class="close" @tap="showPoster"></image>
				<view class="binfos">
					<view class="bimgbox">
						<image :src="product.fileUrl?product.fileUrl:product.pic" mode="aspectFit" class="bimg"></image>
					</view>
					<view class="texts">
						<view class="binfo">
							<view class="btit">{{product.title}}</view>
							<view class="bprice dflex">
								<text>会员码</text>{{userInfo.userCode}}
							</view>
						</view>
						<view class="code">
							<image :src="codeUrl"></image>
						</view>
					</view>
				</view>
			</view>
			<view class="save" @tap="saveImage">保存图片</view>
		</view>
	</view>
</template>

<script>
	const req = require("../../utils/request.js");

	export default {
		data() {
			return {
				// canvasW: 0,
				// canvasH: 0,
				picUrlss: req.public.picUrls,
				imgUrl: '',
				userInfo: {},
				isVideoScene: false
			};
		},

		components: {},
		props: {
			hideToast: {
				type: Boolean,
				default: true
			},
			hidePoster: {
				type: Boolean,
				default: true
			},
			product: Object,
			codeUrl: String,
			bgUrl: String,
			aType: Number,
			canvasW: Number,
			canvasH: Number,
			address: {
				type: String,
				default: '湖南省娄底市经济技术开发区大埠桥办事处南阳村'
			},
		},
		onReady() {
			// console.log(this.hideToast)
		},
		onHide() {
			// console.log(this.hideToast)
		},
		mounted() {
			this.isVideoScene = req.getStorage('isVideoScene')
			// console.log(this.hideToast,888888888)
		},
		methods: {
			generatePoster() {
				let that = this;
				let isShowLoading = false;
				let userInfo = req.getStorage('userInfo');
				this.setData({
					userInfo: userInfo
				});

				if (!isShowLoading) {
					uni.showLoading({
						title: '生成中…',
						mask: true
					});
					isShowLoading = true;
				}

				this.generate(imgUrl => {
					// console.log(isShowLoading);

					if (isShowLoading) {
						uni.hideLoading();
						isShowLoading = false;
					}

					that.setData({
						imgUrl: imgUrl,
						hideToast: true,
						hidePoster: false
					});
				});
			},

			showPoster() {
				//隐藏海报
				this.setData({
					hidePoster: true
				});
				this.$emit('onFather', this.hideToast)
			},

			cancelPopup() {
				this.setData({
					hideToast: true
				});
				this.$emit('onFather', this.hideToast)
			},

			isAuth(fun) {
				if (!uni.saveImageToPhotosAlbum) {
					uni.showModal({
						title: '提示',
						content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
					});
					return;
				}

				; //可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope  
				// #ifndef H5
				uni.getSetting({
					success(res) {
						// console.log(res);

						if (!res.authSetting['scope.writePhotosAlbum']) {
							// 接口调用询问  
							uni.authorize({
								scope: 'scope.writePhotosAlbum',

								success() {
									// console.log("2-授权《保存图片》权限成功");
									fun(true);
								},

								fail() {
									fun(false);
								}

							});
						} else {
							// 拒绝授权
							fun(true);
						}
					},

					fail(res) {
						fun(false);
					}

				});
				// #endif
			},

			saveImage() {
				let that = this;
				that.isAuth(success => {
					if (success) {
						uni.saveImageToPhotosAlbum({
							filePath: that.imgUrl,

							success(res) {
								uni.showToast({
									title: '图片保存成功',
									icon: 'none',

									success() { // that.generate(imgUrl => {
										//   that.setData({
										//     imgUrl: imgUrl
										//   })
										// })
									},

									fail() {
										uni.showToast({
											title: '图片保存失败'
										});
									}

								});
							}

						});
					}
				});
			},

			getImageInfo(url) {
				// console.log(url);
				return new Promise((resolve, reject) => {
					if (!url) {
						resolve();
						return false;
					}

					uni.getImageInfo({
						src: url,
						success: resolve,
						fail: reject
					});
				});
			},

			generate(success) {
				// console.log(this);
				let picPromise = '';
				let picUrl = this.product.fileUrl?this.product.fileUrl:this.product.pic;
				picPromise = this.getImageInfo(picUrl);

				let codePromise;
				if (!this.codeUrl) {
					return req.msg('二维码生成失败');
				} else {
					codePromise = this.getImageInfo(this.codeUrl);
				}
				let that = this;
				Promise.all([picPromise, codePromise]).then(([pic, code]) => {
					// console.log(pic, avatar, code); // 创建绘图上下文

					const ctx = uni.createCanvasContext('share', this); // 绘制背景，填充满整个canvas画布

					let width = 400,
						height = 460; //默认背景

					ctx.setFillStyle('#fff');
					ctx.fillRect(0, 0, width, height); // 拼团背景
					
					
					//白色背景
					// ctx.save();
					// that.roundRect(ctx, 0, 0, 400, 460, 10);
					// ctx.restore();
					const picW = 400;
					ctx.drawImage(pic.path, 0, 0, 400, 313);
					// let lv;

					// if (pic.height >= pic.width) {
					// 	lv = pic.width / pic.height;
					// 	ctx.drawImage(pic.path, (400 - picW * lv) / 2, 0, picW * lv, picW);
					// } else {
					// 	lv = pic.height / pic.width;
					// 	ctx.drawImage(pic.path, 0, (400 - picW * lv) / 2, picW, picW * lv);
					// }

					ctx.drawImage(code.path, 265, 328, 120, 120);
					ctx.fillStyle = '#000';
					ctx.font = "18px PingFang SC";
					let title = that.product.title;
					// console.log(title);
					if (title) {
						for (let i = 0; i <= title.length / 16 && i < 2; i++) {
							ctx.restore();
							if (i == 1) {
								if (title.length > 31) {
									console.log('...===',title.substring(i * 15, (i + 1) * 15) + '...')
									ctx.fillStyle = '#000';
									ctx.font = "16px PingFang SC";
									ctx.fillText(title.substring(i * 15, (i + 1) * 15) + '...', 15, 368 + i * 22);
								} else {
									console.log('...===27',title.substring(i * 15, (i + 1) * 15))
									ctx.fillStyle = '#000';
									ctx.font = "16px PingFang SC";
									ctx.fillText(title.substring(i * 15, (i + 1) * 15), 15, 368 + i * 22);
								}
							} else {
								console.log('...===0',title.substring(i * 16, (i + 1) * 15),i)
								ctx.fillStyle = '#000';
								ctx.font = "16px PingFang SC";
								ctx.fillText(title.substring(i * 16, (i + 1) * 15), 15, 368 + i * 22);
							}
						}
					}
					
					ctx.fillStyle = '#999';
					ctx.font = "14px PingFang SC";
					ctx.fillText('会员码', 15, 422);
					
					ctx.fillStyle = '#333';
					ctx.font = "14px PingFang SC";
					ctx.fillText(that.userInfo.userCode, 65, 422);

					ctx.save();
					// ctx.beginPath();
					// ctx.arc(40, 40, 25, 0, 2 * Math.PI, true); //画一个圆形裁剪区域

					// ctx.clip(); //裁剪
					// let config = JSON.parse(req.getStorage('configRes'))
					// ctx.drawImage(avatar && avatar.path ? avatar.path : config.CONFIG_PROJECT_LOGO, 15, 15, 50, 50); //绘制图片
					ctx.stroke()
					// 完成作画

					ctx.draw(false, function() {
						uni.canvasToTempFilePath({
							canvasId: 'share',
							success: function(res) {
								success.call(this, res.tempFilePath);
							},
							fail: function(res) {
								// console.log(res);
							}
						}, that);
					});
				});
			},

			/**
			 * 
			 * @param {CanvasContext} ctx canvas上下文
			 * @param {number} x 圆角矩形选区的左上角 x坐标
			 * @param {number} y 圆角矩形选区的左上角 y坐标
			 * @param {number} w 圆角矩形选区的宽度
			 * @param {number} h 圆角矩形选区的高度
			 * @param {number} r 圆角的半径
			 */
			roundRect: function(ctx, x, y, w, h, r) {
				// 开始绘制
				ctx.beginPath(); // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
				// 这里是使用 fill 还是 stroke都可以，二选一即可

				ctx.setFillStyle('white'); // ctx.setStrokeStyle('transparent')
				// 左上角

				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); // border-top

				ctx.moveTo(x + r, y);
				ctx.lineTo(x + w - r, y);
				ctx.lineTo(x + w, y + r); // 右上角

				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2); // border-right

				ctx.lineTo(x + w, y + h - r);
				ctx.lineTo(x + w - r, y + h); // 右下角

				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5); // border-bottom

				ctx.lineTo(x + r, y + h);
				ctx.lineTo(x, y + h - r); // 左下角

				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI); // border-left

				ctx.lineTo(x, y + r);
				ctx.lineTo(x + r, y); // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应

				ctx.fill(); // ctx.stroke()

				ctx.closePath(); // 剪切

				ctx.clip();
			}
		}
	};
</script>
<style>
	@import "./share.css";
</style>
