<template>
	<view class="container">
		<canvas :style="{ width:  '750rpx', height: '1624rpx',}" canvas-id="myCanvas" id="myCanvas" class="hb"></canvas>
		<!-- #ifndef MP -->
		<div class="preserve">
			<div class="line"></div>
			<div class="tip">长按保存图片</div>
			<div class="line"></div>
		</div>
		<!-- #endif -->

		<!-- #ifdef MP -->
		<view class='keep' @click='saveShareQrcode' v-if="!loading">保存海报</view>
		<!-- #endif -->

	</view>
</template>

<script>
	import {
		spreadBanner,
		getWxmpInviteQrcode
	} from '@/api/user.js';
	import {
		qrcode
	} from '@/api/user.js';
	import {
		mapState
	} from 'vuex';
	export default {
		// #ifdef MP
		onShareAppMessage: function(res) {
			// if (res.from === 'button') {

			// 保存邀请人
			let path = '/pages/index/index?' + 'spread=' + this.userInfo.uid;
			console.log('path', path)
			let data = {
				path: path,
				imageUrl: this.poster,
				title: this.userInfo.nickname + '邀请您进入母婴界严选'
			};
			console.log('---data---', data)
			return data;
			// }
		},
		// #endif
		data() {
			return {
				bgimg: '',
				qrimg: '',
				shareList: [],
				swiperIndex: 0,
				poster: '', // 当前海报
				loading: true
			}
		},
		onLoad(option) {
			// console.log('---option---',option)
			// let path = '/pages/index/index?' + 'spread=' + this.userInfo.uid;
			// console.log('path',path)
			// if(option.scene){
			// 	// 存储邀请人
			// 	this.spread = opt.pid;
			// 	uni.setStorageSync('spread', opt.pid);
			// }
			this.loadData();
		},
		computed: {
			...mapState(['userInfo']),
		},
		methods: {
			bindchange(e) {
				let shareList = this.shareList;
				this.swiperIndex = e.detail.current;
				// #ifdef MP
				this.poster = shareList[this.swiperIndex].poster;
				// #endif 

				// // #ifndef MP
				// this.poster = shareList[this.swiperIndex].wap_poster;
				// // #endif 

				console.log(this.poster)
			},

			// 保存海报
			savePosterPath: function() {
				let that = this;
				if (that.poster == '') {
					// that.poster = that.shareList[0].poster;
					that.poster = this.bgimg
				}
				uni.downloadFile({
					url: that.poster,
					success(resFile) {
						if (resFile.statusCode === 200) {
							uni.getSetting({
								success(res) {
									if (!res.authSetting['scope.writePhotosAlbum']) {
										uni.authorize({
											scope: 'scope.writePhotosAlbum',
											success() {
												uni.saveImageToPhotosAlbum({
													filePath: resFile.tempFilePath,
													success: function(res) {
														return that.$api.msg(
															'保存成功');
													},
													fail: function(res) {
														return that.$api.msg(res
															.errMsg);
													},
													complete: function(res) {},
												})
											},
											fail() {
												uni.showModal({
													title: '您已拒绝获取相册权限',
													content: '是否进入权限管理，调整授权？',
													success(res) {
														if (res.confirm) {
															uni.openSetting({
																success: function(
																	res) {
																	console
																		.log(
																			res
																			.authSetting
																			)
																}
															});
														} else if (res.cancel) {
															return that.$api.msg(
																'已取消！');
														}
													}
												})
											}
										})
									} else {
										uni.saveImageToPhotosAlbum({
											filePath: resFile.tempFilePath,
											success: function(res) {
												return that.$api.msg('保存成功');
											},
											fail: function(res) {
												return that.$api.msg(res.errMsg);
											},
											complete: function(res) {},
										})
									}
								},
								fail(res) {

								}
							})
						} else {
							return that.$api.msg(resFile.errMsg);
						}
					},
					fail(res) {
						return that.$api.msg(res.errMsg);
					}
				})
			},

			// #ifdef MP-WEIXIN
			// 保存画图图片到本地
			seav(url) {
				uni.showLoading({
					title: '生成中...',
					mask: true
				});
				uni.saveImageToPhotosAlbum({
					filePath: this.poster,
					complete(result) {
						uni.hideLoading();
						console.log(result);
						uni.showToast({
							title: '保存图片成功！',
							duration: 2000,
							icon: 'none'
						});
					}
				});
			},
			// #endif

			// 获取海报
			loadData() {
				let obj = this;
				uni.showLoading({
					title: '获取中',
					mask: true,
				});
				// spreadBanner({
				// 	// #ifdef H5
				// 	type: 2,
				// 	// #endif
				// 	// #ifdef MP
				// 	type: 1
				// 	// #endif
				// }).then(res =>{
				// 	uni.hideLoading();
				// 	obj.shareList = res.data;
				// 	console.log('obj.shareList',obj.shareList);
				// }).catch(err => {
				// 	uni.hideLoading();
				// });
				getWxmpInviteQrcode().then(res => {
					console.log(res)
					obj.bgimg = res.data.bgimg
					obj.qrcode = res.data.qrcode
					uni.hideLoading();
					obj.createPoster()
					
				})
			},
			async createPoster() {
				let that = this
				// 获取设备信息，主要获取宽度，赋值给canvasW 也就是宽度：100%
				this.SystemInfo = await this.getSystemInfo();
				// 获取商品主图，二维码信息，APP端会返回图片的本地路径（H5端只能返回原路径）
				this.goodsImg = await this.getImageInfo(that.bgimg);
				this.ewmImg = await this.getImageInfo(that.qrcode);
				// this.canvasW = this.SystemInfo.windowWidth; // 画布宽度
				this.ratio = this.SystemInfo.windowWidth / 750;
				this.canvasW =750 * this.ratio;
				this.canvasH = 1624 * this.ratio;

				this.ewmW = 220 * this.ratio;
	
				
				console.log(this.canvasH, 'this.canvasH')
				// this.canvasH = this.goodsImg.height + this.ewmW + 200;  // 画布高度 = 主图高度+二维码高度 + 文字图片的间距（大概50）
			
				// 如果主图，二维码图片，设备信息都获取成功，开始绘制海报，这里需要用setTimeout延时绘制，否则可能会出现图片不显示。
				if (this.goodsImg.errMsg == 'getImageInfo:ok' && this.ewmImg.errMsg == 'getImageInfo:ok' && this
					.SystemInfo.errMsg == 'getSystemInfo:ok') {
					console.log('ok')
					uni.showToast({
						icon: 'loading',
						mask: true,
						duration: 10000,
						title: '海报绘制中',
					});
					setTimeout(() => {
						var ctx = uni.createCanvasContext('myCanvas', this);
						// 填充背景色，白色
						ctx.setFillStyle('#fff'); // 默认白色
						ctx.fillRect(0, 0, this.canvasW, this.canvasH) // fillRect(x,y,宽度，高度)
			
						// 绘制商品主图，二维码
						ctx.drawImage(this.goodsImg.path, 0, 0, this.canvasW, this
							.canvasH) // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)
							ctx.drawImage(this.ewmImg.path, (this.canvasW / 2 - this.ewmW / 2),this.canvasH - 85*this.ratio - this.ewmW,
								this.ewmW, this.ewmW) // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度,二维码的宽,高)
						
			
						// 3、绘制商品标题，多余文字自动换行
						ctx.setFontSize(16); // setFontSize() 设置字体字号
						ctx.setFillStyle('#333'); // setFillStyle() 设置字体颜色
						ctx.draw(false, (ret) => { // draw方法 把以上内容画到 canvas 中。
							console.log(ret)
							uni.showToast({
								icon: 'none',
								title: '生成成功！',
							});
							that.loading = false
							that.fina = true
							uni.canvasToTempFilePath({ // 保存canvas为图片
								canvasId: 'myCanvas',
								quality: 1,
								fileType: 'jpg',
								complete: function(res) {
									// 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
									console.log(res)
									that.canvasShow = false
									that.shareQrcodeUrl = res.tempFilePath
									that.$forceUpdate()
									setTimeout(function() {
										console.log(that.shareQrcodeUrl, that
											.canvasShow)
									}, 2000)
								},
							})
						});
					}, 1500)
				} else {
					console.log('err')
				}
			},
			// 获取设备信息
			getSystemInfo() {
				return new Promise((req, rej) => {
					uni.getSystemInfo({
						success: function(res) {
							req(res)
						}
					});
				})
			},
			// 获取图片信息
			getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: function(res) {
							req(res)
						},
					});
				})
			},
			//保存图片
			saveShareQrcode() {
				console.log(this.shareQrcodeUrl)
				uni.saveImageToPhotosAlbum({
					filePath: this.shareQrcodeUrl,
					success: (res) => {
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: "成功保存到相册",
						});
					},
					fail: (err) => {
						//重新提示用户打开保存图片的授权
						if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
							uni.showModal({
								title: '提示',
								content: '需要您授权保存相册',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success(settingdata) {
												if (settingdata.authSetting[
														'scope.writePhotosAlbum']) {
													uni.showModal({
														title: '提示',
														content: '获取权限成功,再次保存图片即可成功',
														showCancel: false,
													})
												} else {
													uni.showModal({
														title: '提示',
														content: '获取权限失败，无法保存到相册',
														showCancel: false
													})
												}
											}
										})
									}
								}
							})
						}
					},
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #a3a3a3;
		height: 100%;
	}

	.container {
		width: 100%;

		.posters-box {
			width: 100%;
			height: 1000rpx;
			margin-top: 40rpx;

			.slide-image {
				width: 100%;
				height: 100%;
				border-radius: 15rpx;
			}
		}

		.posters-box .slide-image.active {
			transform: none;
			transition: all 0.2s ease-in 0s;
		}

		.posters-box .slide-image.quiet {
			transform: scale(0.8333333);
			transition: all 0.2s ease-in 0s;
		}

		.keep {
			font-size: 30rpx;
			background: $base-color;
			color: #fff;
			width: 600rpx;
			height: 80rpx;
			border-radius: 50rpx;
			text-align: center;
			line-height: 80rpx;
			margin: 38rpx auto;
		}
	}

	.preserve {
		color: #fff;
		text-align: center;
		margin-top: 38rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.line {
			width: 100rpx;
			height: 1px;
			background-color: #fff;
		}

		.tip {
			margin: 0 20rpx;
			font-size: 28rpx;
		}
	}
	.hb {
		margin: auto;
	}
</style>