<template>
	<view>
		<!--promote/invite/invite.wxml-->
		<image
			:src="posterList[currentTab] + '?x-oss-process=style/w750-auto'"
			mode="widthFix" class="bgimg"></image>
		<!-- <view class="invite">
			<view class="logo dflex">
				<image :src="config.CONFIG_PROJECT_LOGO" mode="aspectFit" class="logoimg"></image>
				<view class="flex">{{config.CONFIG_PROJECT_TITLE}}</view>
			</view>
		</view> -->
		<view class="bot">
			<view class="code">
				<image :src="codeUrl"></image>
			</view>
			<!-- <view class="btn">
				<view class="share" @tap="saveImage">保存到相册</view>
			</view> -->
		</view>
		<view class="bott">
			<view class="poster-list">
				<scroll-view scroll-x="true">
					<view :class="'li' + (currentTab==index?' active':'')" v-for="(item,index) in posterList" :key="index" @click="switchTab(index)">
						<image :src="item" mode="widthFix"></image>
					</view>
				</scroll-view>
			</view>
		</view>
		<canvas canvas-id="invite" class="canvas" style="width:414px;height:795px;"></canvas>
		<view class="share" @tap="saveImage"><image src="../static/promote/images/download.png"></image></view>
	</view>
</template>

<script>
	// promote/invite/invite.js
	const app = getApp();
	const utils = require("../../utils/util.js");
	const req = require("../../utils/request.js");

	export default {
		data() {
			return {
				config: {},
				codeUrl: '',
				imgUrl: '',
				posterList: [
					req.public.picUrls + 'scrm/poster_pic0.jpg',
					req.public.picUrls + 'scrm/poster_pic1.jpg',
					req.public.picUrls + 'scrm/poster_pic2.jpg'
				],
				currentTab: 0
			};
		},

		components: {},
		props: {},
		onLoad: async function(options) {
			await this.getConfig();
			await this.getCodeUrl();
			await this.generatePoster();
		},
		methods: {
			switchTab(index){
				if(this.currentTab == index) return false;
				this.currentTab = index;
				this.generatePoster();
			},
			getConfig() {
				var _this = this;

				return new Promise((resolve, reject) => {
					req.g('/api/config', res => {
						// console.log('配置数据====' + JSON.stringify(res));

						_this.setData({
							config: res
						});

						resolve();
					}, true);
				});
			},

			getCodeUrl() {
				let that = this; //获取小程序码
				let page = 'pages/index/index'
				const params = {
					page: page,
					// page: 'pages/authorize/authorize',
					scene: req.getStorage('userInfo').id// + '_' + 'isPromote'
				};
				if(req.getStorage('appId')) params.scene += '_'+ req.getStorage('appId');
				return new Promise((resolve, reject) => {
					req.getRequest('/api/program/codev', params, url => {
						// console.log(url);
						that.setData({
							codeUrl: url
						});
						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) {
				// 获取商品图片 
				const picPromise = this.getImageInfo(this.posterList[this.currentTab]);
				// const picPromise = this.getImageInfo(this.config.Distribution_Poster_Background);
				const avatarPromise = this.getImageInfo(this.config.CONFIG_PROJECT_LOGO); // 获取小程序码图

				const codePromise = this.getImageInfo(this.codeUrl);
				let that = this;
				Promise.all([picPromise, avatarPromise, codePromise]).then(([pic, avatar, code]) => {
					// 创建绘图上下文
					const ctx = uni.createCanvasContext('invite', this); // 绘制背景，填充满整个canvas画布

					let width = 414,
						height = 795; //默认背景

					ctx.drawImage(pic ? pic.path : "/promote/static/promote/images/fenxiaobg.jpg", 0, 0, width,
						height); //白色背景

					ctx.save();
					that.roundRect(ctx, 139, 415, 135, 135, 0);
					ctx.restore();
					ctx.drawImage(code.path, 139, 415, 135, 135);
					// ctx.fillStyle = '#fff';
					// ctx.font = "16px PingFang SC";
					// ctx.fillText(that.config.CONFIG_PROJECT_TITLE, 65, 40); //logo

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

					// ctx.clip(); //裁剪

					// ctx.drawImage(avatar.path, 15, 15, 40, 40); //绘制图片
					// 完成作画

					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();
			}
		}
	};
</script>
<style>
	@import "./invite.css";
</style>
