<template>
	<view v-if="isShow">
		<view class="con">
			<view class="tits ddflex"><image src="../static/images/bag.png"></image>二维码收款</view>
			<view class="code-box">
				<view class="tips">无需添加好友，扫二维码向我付钱</view>
				<image :src="codeUrl" class="code"></image>
				<view class="save" @click="saveImage()">保存收款码</view>
			</view>
			<navigator url="/payment/receiveList/receiveList" hover-class="none" class="skjl ddflex">
				<image src="../static/images/zhang.png" class="ico"></image>
				<view class="fflex">收款记录</view>
				<image src="../static/images/crico1.png" class="rico"></image>
			</navigator>
		</view>
		<canvas canvas-id="invite" class="canvas" style="width:1080px;height:1466px;"></canvas>
	</view>
</template>

<script>
	const req = require('../../utils/request.js');
	const api = require('../../utils/api.js');
	const util = require('../../utils/util.js');
	const app = getApp();
	export default {
		data() {
			return {
				isShow: false,
				codeUrl: '',
				merchant: '',
				title: ''
			};
		},
		async onLoad(options) {
			let userInfo = req.getStorage('userInfo');
			if(userInfo.listMerchant && userInfo.listMerchant.length > 0){
				this.merchant = userInfo.listMerchant[0]
			}
			await this.getConfig()
			await this.getDetail();
			await this.generatePoster();
		},
		onShow() {
		},

		methods: {
			getConfig() {
				var _this = this;
				return new Promise((resolve, reject) => {
				req.getRequest('/api/config', {}, function(res) {
					_this.title = res.CONFIG_PROJECT_TITLE;
					resolve();
					});
				})
			},
			getDetail() {
				let id = '';
				if(this.merchant&&this.merchant.id){
					id = this.merchant.id
				}
				return new Promise((resolve, reject) => {
					req.getRequest('/api/QrCode/collectionQr', {merchantId: id}, res => {
						this.isShow = true;
						this.codeUrl = res;
						resolve();
					});
				})
			},
			generatePoster() {
				let that = this;
				that.generate(imgUrl => {
					that.setData({
						imgUrl: imgUrl
					});
				});
			},
			
			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) {
						// console.log("图片地址=====" + that.imgUrl);
						uni.saveImageToPhotosAlbum({
							filePath: that.imgUrl,
			
							success(res) {
								uni.showToast({
									title: '图片保存成功',
									icon: 'none',
			
									success() {},
			
									fail() {
										uni.showToast({
											title: '图片保存失败'
										});
									}
			
								});
							}
			
						});
					}
				});
			},
			
			getImageInfo(url) {
				return new Promise((resolve, reject) => {
					if (!url) {
						resolve();
						return false;
					}
			
					uni.getImageInfo({
						src: url,
						success: resolve,
						fail: reject
					});
				});
			},
			
			generate(success) {
				// 获取商品图片 
				let userInfo = req.getStorage('userInfo');
				const avatarPromise = this.getImageInfo(userInfo.avatar); // 获取小程序码图
				
				const codePromise = this.getImageInfo(this.codeUrl);
				console.log('codePromise')
				let that = this;
				Promise.all([avatarPromise,codePromise]).then(([avatar,code]) => {
					// 创建绘图上下文
					const ctx = uni.createCanvasContext('invite', this); // 绘制背景，填充满整个canvas画布
			
					let width = 1080,
						height = 1466; //默认背景
					
					ctx.setFillStyle('#00a3ff');
					ctx.fillRect(0, 0, width, height);
					
					
					ctx.save();
					that.roundRect(ctx, 30, 200, 1020, 1180, 10);
					ctx.restore();
					
					
					
					//白色背景
					ctx.drawImage(code.path, 235, 515, 605, 689);
					ctx.textAlign = 'center'
					ctx.fillStyle = '#333';
					ctx.font = "60px PingFang SC";
					ctx.fillText(that.title, 540, 400); //logo
					ctx.fillStyle = '#666';
					ctx.font = "42px PingFang SC";
					ctx.fillText(that.merchant.title ? that.merchant.title + ' ' + userInfo.nickName : userInfo.nickName, 540, 470); //logo
					
					ctx.fillStyle = '#000';
					ctx.font = "40px PingFang SC font";
					ctx.fillText('扫码付款', 540, 1300); //logo
			
					ctx.save();
					ctx.beginPath();
					ctx.arc(540, 200, 100, 0, 2 * Math.PI, true); //画一个圆形裁剪区域
					ctx.clip(); //裁剪
					ctx.drawImage(avatar && avatar.path ? avatar.path : "/static/pages/images/logo.png", 440, 100, 200, 200); //绘制图片
					// 完成作画
			
					ctx.draw(false, function() {
						uni.canvasToTempFilePath({
							canvasId: 'invite',
							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();
			},
			// saveImg() {
			// 	uni.getImageInfo({
			// 		src: this.codeUrl,
			// 		success: function (res) {
			// 			console.log('success==' + JSON.stringify(res))
			// 			uni.saveImageToPhotosAlbum({
			// 				filePath: res.path,
			// 				success: function() {
			// 					uni.showToast({
			// 						title: '图片保存成功',
			// 						icon: 'none',
			// 						duration: 2200
			// 					});
			// 				},
			// 				fail: function(suc) {
			// 					uni.showToast({
			// 						title: '图片保存失败',
			// 						icon: 'none',
			// 						duration: 2200
			// 					});
			// 				}
			// 			});
			// 		},
			// 		fail(res){
			// 			console.log('fail==' + JSON.stringify(res))
			// 		}
			// 	});
			// },
		}
	};
</script>

<style>
	@import "./receiveCode.css";
</style>
