<template>
	<view>
		<uni-nav-bar @clickLeft="goto(1, 1)" left-icon="back"  :border="false" :shadow="false" :fixed="true" title="Invite" backgroundColor="#fff"></uni-nav-bar>
		<canvas canvas-id="poster" class="poster_canvas"></canvas>
		<view class="minebg">
			<view class="v1">
				CODE: {{invite_code}} 
				<image src="/static/images/copy1.png" class="i" @click="copy(invite_code)" mode="cover"></image>
			</view>
			<view style="text-align: center; width: 260rpx; margin: 20rpx auto;">
				<tki-qrcode 
					ref="qrcode" 
					:val="qrcode" 
					:size="size" 
					:unit="unit" 
					:onval="onval" 
					:load-make="load_make" 
					:show-loading="show_loading" 
					:lv="lv" 
					:background="background" 
					:foreground="foreground" 
					:pdground="pdground" 
					:icon='icon' 
					@result="qrResult"
					style="margin: 10rpx auto; text-align: center;"/>
			</view>
			<view style="padding: 0rpx 10%;">
				<button type="primary" class="b1" @click="onSaveImg">
					<uni-icons type="download" size="20" color="#fff"></uni-icons>
					<text style="margin-left: 10rpx;">{{$t('invite.text1')}}</text>
				</button>
				<button type="primary" class="b2" @click="copy()">
					<uni-icons type="undo" size="20" color="#000"></uni-icons>
					<text style="margin-left: 10rpx;">{{$t('invite.text2')}}</text>
				</button>
			</view>
		</view>
		<!-- #ifdef H5 -->
		<view class="h5_press_save" v-if="h5SaveImg" @click="h5SaveImg = ''">
			<image :src="h5SaveImg" mode="widthFix"></image>
			<button class="download"><uni-icons type="download" size="20" color="#fff"></uni-icons>
			{{$t('invite.text3')}}</button>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import tkiQrcode from "tki-qrcode"
	import {
		mapState,
		mapMutations
	} from 'vuex';
	let settingWritePhotosAlbum = false;
	export default {
		components: {
			tkiQrcode
		},
		data() {
			return {
				invite_code: '',
				init: {},
				nickName: '',
				promoteBgImgs: ["/static/images/13.png"],
				promoteCodeImg: "https://qn.kemean.cn/upload/202007/03/1593744239803mgajzyjk.png",
				swiperIndex: 0,
				posterImgs: [],
				shareInfo: {
					shareContent: "",
					shareImg: "http://qn.kemean.cn/upload/202004/08/15863540965488mlv1qgj.png",
					shareTitle: "",
					shareUrl: ""
				},
				h5SaveImg: "",
				
				qrcode: '', //二维码的内容链接
				size: 260, //二维码的大小
				unit: 'upx', //大小单位 !!! rpx单位有误
				load_make: true, //组件加载完成后自动生成二维码
				show_loading: false, //是否添加loading
				onval: true, //val值变化时自动重新生成二维码
				background: '#ffffff', //背景色
				foreground: '#000',//点色
				pdground: '#000', //角标色
				icon: '', //二维码图标
				iconsize: 30, //二维码图标大小
				lv: 3, //二维码容错级别
				loadingText: 'Loading', //loading内容,
				result: ''
			}
		},
		computed: {
			...mapState(['userInfo'])
		},
		onLoad(e){
			this.$http.get('/api/common/init?lang='+this.$i18n.locale).then(res => {
				this.qrcode = res.data.client_download_url;
			});
		},
		//第一次加载
		onShow(e) {
			this.$http.get('/api/team/index?lang='+this.$i18n.locale).then(res => {
				if(res.code == 0){
					this.invite_code = res.data.user.invite_code;
				}
			});
		},
		methods: {
			copy() {
			    this.$copyText(this.qrcode).then(res => {
					uni.showToast({title: this.$t('copySuccess'), icon: 'none'});
			    });
			},
			goto(url, type) {
			    if (type == 2) {
			        return uni.switchTab({ url: url })
			    }
			    if (type == 1) {
			        return uni.navigateBack({ delta: url });
			    }
			    uni.navigateTo({
			        url: url
			    })
			},
			qrResult(e) {
				this.result = e;
			},
			// 创建海报
			createPoster() {
				return new Promise((resolve, reject) => {
					if (this.posterImgs[this.swiperIndex]) {
						resolve(this.posterImgs[this.swiperIndex]);
					} else {
						uni.showLoading({
							title: 'Poster generation in progress'
						});
						const ctx = uni.createCanvasContext('poster');
						ctx.setFillStyle('#2651ef');
						ctx.fillRect(0, 0, 375, 667);
						ctx.drawImage(this.promoteBgImgs[this.swiperIndex], 0, 0, 375, 360);
						ctx.drawImage(this.result, 108, 440, 160, 160);
						// 绘制圆角矩形的参数
						var x = 80; // 矩形左上角的x坐标
						var y = 370; // 矩形左上角的y坐标
						var width = 220; // 矩形的宽度
						var height = 50; // 矩形的高度
						var radius = 25; // 圆角半径
						var fillColor = '#000'; // 填充颜色
						var strokeColor = '#000'; // 边框颜色	
						// 开始绘制路径
						ctx.beginPath();
						ctx.moveTo(x + radius, y); // 起始点
						ctx.arcTo(x + width, y, x + width, y + height, radius); // 右上圆角
						ctx.lineTo(x + width, y + height - radius);
						ctx.arcTo(x + width, y + height, x, y + height, radius); // 右下圆角
						ctx.lineTo(x + radius, y + height);
						ctx.arcTo(x, y + height, x, y, radius); // 左下圆角
						ctx.lineTo(x, y + radius);
						ctx.arcTo(x, y, x + width, y, radius); // 左上圆角
						ctx.closePath();	
						// 设置填充颜色并填充
						ctx.setFillStyle(fillColor);
						ctx.fill();	
						// 设置边框颜色并描边
						ctx.setStrokeStyle(strokeColor);
						ctx.stroke();
						ctx.setFontSize(18);
						ctx.setFillStyle('#fff');
						ctx.fillText("CODE：" + this.invite_code, 100, 402);
						ctx.draw(true, () => {
							uni.canvasToTempFilePath({
								canvasId: 'poster',
								width: 375,
								height: 667,
								success: res => {
									if(this.posterImgs[this.swiperIndex]){
										this.posterImgs[this.swiperIndex].temporary = res.tempFilePath;
									}else{
										this.posterImgs[this.swiperIndex] = {};
										this.posterImgs[this.swiperIndex].temporary = res.tempFilePath;
									}
									resolve(res.tempFilePath);
								},
								fail: () => {
									uni.hideLoading();
									reject();
								}
							});
						});
					}
				});
			},
			// 保存图片
			async onSaveImg() {
				let imgUrl = "";
				if(this.posterImgs[this.swiperIndex] && this.posterImgs[this.swiperIndex].temporary){
					imgUrl = await this.posterImgs[this.swiperIndex].temporary;
				}else{
					imgUrl = await this.createPoster();
				}
				// #ifdef H5
				this.h5SaveImg = imgUrl;
				uni.hideLoading();
				// #endif
				// #ifdef MP-WEIXIN
				uni.showLoading({
					title: 'Poster download in progress'
				});
				if (settingWritePhotosAlbum) {
					uni.getSetting({
						success: res => {
							if (res.authSetting['scope.writePhotosAlbum']) {
								uni.saveImageToPhotosAlbum({
									filePath: imgUrl,
									success: () => {
										uni.hideLoading();
										uni.showToast({
											title: 'Successfully saved'
										});
									}
								});
							} else {
								uni.showModal({
									title: 'prompt',
									content: 'Please first open the “Save Album” permission on the settings page',
									confirmText: 'Go set it up',
									cancelText: 'cancel',
									success: data => {
										if (data.confirm) {
											uni.hideLoading();
											uni.openSetting();
										}
									}
								});
							}
						}
					});
				} else {
					settingWritePhotosAlbum = true;
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success: () => {
							uni.saveImageToPhotosAlbum({
								filePath: imgUrl,
								success: () => {
									uni.hideLoading();
									uni.showToast({
										title: 'Successfully'
									});
								}
							});
						}
					});
				}
				// #endif
				// #ifdef APP-PLUS
				uni.showLoading({
					title: this.$t('invite.text4')
				});
				uni.saveImageToPhotosAlbum({
					filePath: imgUrl,
					success: () => {
						uni.hideLoading();
						uni.showToast({
							title: 'Successfully saved'
						});
					}
				});
				// #endif
			},
		}
	}
</script>

<style scoped>
	.poster_canvas {
		width: 100vw;
		height: 100vh;
		position: fixed;
		top: -100vh;
		left: 0rpx;
	}
	.page{min-height: 100vh;position: relative; background-color: #2A54FF;}
	.minebg{
		width: 100vw;
		min-height: 100vh;
		background: url('/static/images/13.png') #2651ef;
		background-size: 100%;
		background-repeat: repeat-x;
		font-family: Poppins, Poppins;
		padding: 94% 0rpx 0rpx 0rpx;
	}
	.minebg .v1{
		margin: auto; width: 60%; border-radius: 40rpx; 
		background-color: #000; font-size: 36rpx; 
		height: 100rpx; color: #fff; 
		text-align: center; line-height: 100rpx;
	}
	.minebg .v1 .i{
		width: 40rpx; height: 40rpx; margin-right: 30rpx; float: right; margin-top: 30rpx;
	}
	.minebg .b1{
		background-color: #000; color: #fff; float: left; border-radius: 40rpx;
		 width: 47%;
	}
	.minebg .b2{
		background-color: #fff; color: #000; float: left; 
		border-radius: 40rpx; margin-left: 6%; width: 47%;
	}
	.h5_press_save {
		background-color: #000;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		z-index: 100;
		image {
			width: 100%;
		}
		.download {
			font-size: 24rpx;
			color: #ffffff;
			background-color: rgba(0,0,0,0.5);
			display: flex;
			align-items: center;
			flex-direction: row;
			justify-content: center;
			position: absolute;
			padding: 0rpx 30rpx;
			border-radius: 40rpx;
			bottom: 20rpx;
			left: 50%;
			transform: translateX(-50%);
			&:before {
				content: '';
				@include bis('@/static/demo/icon_download.png');
				width: 24rpx;
				height: 24rpx;
				margin-right: 15rpx;
			}
		}
	}
</style>
