<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:595px;" canvas-id="share"></canvas>
		<!-- 分享弹窗 -->
		<view class="ceng" :hidden="hidePoster" @tap="showPoster"></view>
		<view class="beshare" :hidden="hidePoster">
			<view class="beshares">
				<image src="/activity/static/activity/images/share_pintuan.jpg" mode="widthFix" class="sharebg" v-if="aType==3"></image>
				<image src="/static/pages/images/close.png" class="close" @tap="showPoster"></image>
				<view class="user dflex">
					<image :src="userInfo.avatar" mode="aspectFit" class="toux"></image>
					<view class="flex">
						<view :class="aType==3 ? 'colorfff' : ''">{{userInfo.nickName}}</view>
						<view v-if="product.pic">
							<text v-if="aType==1">邀请您参与社区团购</text>
							<text v-if="aType==2">邀请您参与限时秒杀</text>
							<text v-if="aType==3" class="colorfff">邀请您参与拼团</text>
							<text v-if="aType==4">邀请您参与新客特价</text>
							<text v-if="aType==5">邀请您参与砍价</text>
							<text v-if="aType==0">给你推荐了一个好东西</text>
						</view>
						<view v-if="product.share_img">
							<text>邀请您观看直播</text>
							<image src="/static/pages/images/live1.png" class="live"></image>
						</view>
					</view>
				</view>
				<view class="binfos">
					<view class="bimgbox">
						<image :src="product.images[0]" mode="aspectFit" class="bimg" v-if="product.images && product.images.length > 0"></image>
						<block v-else>
							<image :src="product.pic" mode="aspectFit" class="bimg" v-if="product.pic"></image>
						</block>
						<image :src="product.share_img" mode="aspectFit" class="bimg" v-if="product.share_img"></image>
					</view>
					<view class="texts">
						<view class="binfo" v-if="product.pic">
							<view class="bprice dflex">
								<block v-if="product.mode==2">
									<text>{{product.integral?product.integral:0}}积分</text>
									<text class="money" v-if="product.salePrice">+￥{{product.salePrice}}</text>
									<text class="del" v-if="product.salePrice == product.actualPrice && product.marketPrice > 0">￥{{product.marketPrice}}</text>
								</block>
								<block v-else>
									<text>￥</text>{{product.salePrice?product.salePrice:'0'}}
									<view class="del">￥{{product.marketPrice?product.marketPrice:'0'}}</view>
								</block>
							</view>
							<view class="btit">{{product.title}}</view>
						</view>
						<view class="binfo" v-if="product.share_img">
							<view class="blive dflex">
								<text>{{product.anchor_name}}的直播间</text>
							</view>
							<view class="btit">{{product.month}}{{product.hour}}开播</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,
				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 = '';
				
				if(this.product.images && this.product.images.length > 0){
					picPromise = this.getImageInfo(this.product.images[0]);
				}else{
					if (this.product.pic != undefined) {
						// 获取商品图片 
						picPromise = this.getImageInfo(this.product.pic);
						// console.log(picPromise);
					}
				}

				if (this.product.share_img != undefined) {
					//获取直播界面图片
					picPromise = this.getImageInfo(this.product.share_img);
				} // console.log(this.data.product.share_img)
				// console.log(this.data.product.pic != undefined, this.data.product.share_img != undefined)
				// console.log(this.data.product.share_img)
				// 头像


				const avatarPromise = this.getImageInfo(this.userInfo.avatar); // 获取小程序码图

				let codePromise;

				if (!this.codeUrl) {
					return req.msg('二维码生成失败');
				} else {
					codePromise = this.getImageInfo(this.codeUrl);
				} //获取背景图
				// const  bgPromise=this.getImageInfo(this.data.bgUrl)
				// console.log(this.data.userInfo.avatar)
				// console.log(this.data.codeUrl)
				// console.log(this.data.bgUrl)

				let that = this;
				Promise.all([picPromise, avatarPromise, codePromise]).then(([pic, avatar, code]) => {
					// console.log(pic, avatar, code); // 创建绘图上下文

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

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

					ctx.setFillStyle('#f6f6f6');
					ctx.fillRect(0, 0, width, height); // 拼团背景

					if (this.aType == 3) {
						// ctx.drawImage('/pages/images/live1.png', 333, 30,50,28) //绘制图片
						ctx.drawImage("/activity/static/activity/images/share_pintuan.jpg", 0, 0, 400, 595);
					}

					if (that.product.share_img != undefined) {
						ctx.drawImage("/static/pages/images/live1.png", 333, 30, 50, 28); //绘制图片
						// ctx.drawImage('/activity/images/share_pintuan.jpg', 400, 595, 0, 0);
					} // 用户信息


					ctx.fillStyle = '#333';
					ctx.font = "18px PingFang SC";

					if (this.aType == 3) {
						ctx.fillStyle = '#fff';
					}

					ctx.fillText(that.userInfo.nickName, 80, 35);
					ctx.fillStyle = '#999';
					ctx.font = "14px PingFang SC";

					if (this.aType == 1) {
						ctx.fillText('邀请您参与社区团购', 80, 58);
					}

					if (this.aType == 2) {
						ctx.fillText('邀请您参与限时秒杀', 80, 58);
					}

					if (this.aType == 3) {
						ctx.fillStyle = '#fff';
						ctx.fillText('邀请您参与拼团', 80, 58);
					}

					if (this.aType == 4) {
						ctx.fillText('邀请您参与新客特价', 80, 58);
					}

					if (this.aType == 5) {
						ctx.fillText('邀请您参与砍价', 80, 58);
					}

					if (this.product.share_img != undefined && this.aType == 6) {
						ctx.fillText('邀请您观看直播', 80, 58);
					}

					if (this.aType == 0) {
						ctx.fillText('给你推荐了一个好东西', 80, 58);
					} //白色背景


					ctx.save();
					that.roundRect(ctx, 15, 80, 370, 500, 10);
					ctx.restore();
					const picW = 340;
					let lv;

					if (pic.height >= pic.width) {
						lv = pic.width / pic.height;
						ctx.drawImage(pic.path, (340 - picW * lv) / 2 + 30, 95, picW * lv, picW);
					} else {
						lv = pic.height / pic.width;
						ctx.drawImage(pic.path, 30, (340 - picW * lv) / 2 + 95, picW, picW * lv);
					}

					ctx.drawImage(code.path, 250, 445, 120, 120);
					let tlength = '';
					if (that.product.mode == 2) {
						ctx.fillStyle = '#FD3B31';
						ctx.font = "20px PingFang SC";
						ctx.fillText(that.product.integral?that.product.integral:'0', 30, 470);
						if ((that.product.integral?that.product.integral:'0').toString().length > 2) {
							ctx.fillStyle = '#FD3B31';
							ctx.font = "14px PingFang SC";
							ctx.fillText('积分', 80, 470);
							if(that.product.salePrice){
								ctx.fillStyle = '#FD3B31';
								ctx.font = "14px PingFang SC";
								ctx.fillText('+￥', 90, 470);
								ctx.fillStyle = '#FD3B31';
								ctx.font = "20px PingFang SC";
								ctx.fillText(that.product.salePrice?that.product.salePrice:'0', 100, 470);
							}
						} else {
							ctx.fillStyle = '#FD3B31';
							ctx.font = "14px PingFang SC";
							ctx.fillText('积分', 58, 470);
							if(that.product.salePrice){
							ctx.fillStyle = '#FD3B31';
							ctx.font = "14px PingFang SC";
							ctx.fillText('+￥', 85, 470);
							ctx.fillStyle = '#FD3B31';
							ctx.font = "20px PingFang SC";
							ctx.fillText(that.product.salePrice?that.product.salePrice:'0', 110, 470);	
							}
							
						}
						

					}
					if (that.product.salePrice  && that.product.mode != 2) {
						ctx.fillStyle = '#FD3B31';
						ctx.font = "16px PingFang SC";
						ctx.fillText('￥', 30, 470);
						ctx.fillStyle = '#FD3B31';
						ctx.font = "20px PingFang SC";
						ctx.fillText(that.product.salePrice, 50, 470);
						ctx.fillStyle = '#999';
						ctx.font = "14px PingFang SC"; // console.log(that.data.product.salePrice.toString().length)

						if (that.product.salePrice.toString().length > 2) {
							ctx.fillStyle = '#999';
							ctx.font = "14px PingFang SC";
							ctx.fillText('￥' + that.product.marketPrice, 100, 470);
							let text = '￥' + that.product.marketPrice;
							tlength = text.length;
							ctx.beginPath();
							ctx.moveTo(100, 465);
							ctx.lineTo(100 + tlength * 11, 465);
						} else {
							ctx.fillStyle = '#999';
							ctx.font = "14px PingFang SC";
							ctx.fillText('￥' + that.product.marketPrice, 80, 470);
							let text = '￥' + that.product.marketPrice;
							tlength = text.length;
							ctx.beginPath();
							ctx.moveTo(80, 465);
							ctx.lineTo(80 + tlength * 11, 465);
						}

					ctx.lineWidth = 1; //线的宽度

					ctx.strokeStyle = '#999'; //线的颜色

					ctx.stroke();
					}
					ctx.fillStyle = '#333';
					ctx.font = "16px PingFang SC";
					let title = that.product.title;
					// console.log(title);

					if (title) {
						for (let i = 0; i < title.length / 14 && i < 2; i++) {
							ctx.restore();

							if (i == 1) {
								if (title.length > 27) {
									ctx.fillStyle = '#333';
									ctx.font = "16px PingFang SC";
									ctx.fillText(title.substring(i * 14, (i + 1) * 13) + '...', 30, 505 + i * 22);
								} else {
									ctx.fillStyle = '#333';
									ctx.font = "16px PingFang SC";
									ctx.fillText(title.substring(i * 14, (i + 1) * 13), 30, 505 + i * 22);
								}
							} else {
								ctx.fillStyle = '#333';
								ctx.font = "16px PingFang SC";
								ctx.fillText(title.substring(i * 14, (i + 1) * 13), 30, 505 + i * 22);
							}
						}
					}

					if (that.product.share_img != undefined && this.aType == 6) {
						ctx.font = "20px PingFang SC";
						ctx.fillStyle = '#333333';
						let title = that.product.anchor_name + '的直播间';

						if (title) {
							for (let i = 0; i < title.length / 14 && i < 2; i++) {
								ctx.restore();
								ctx.fillText(title.substring(i * 14, (i + 1) * 13), 30, 470 + i * 22);
							}
						}

						ctx.fillStyle = '#333';
						ctx.font = "15px PingFang SC";
						ctx.fillText(that.product.month + that.product.hour + '开播', 30, 500);
					} //用户头像


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

					ctx.clip(); //裁剪

					ctx.drawImage(avatar && avatar.path ? avatar.path : "/static/pages/images/userimg.png", 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>
