<!-- 分享图片弹框 -->
<template>
	<!-- 普通弹窗 -->
	<uni-popup ref="canvaspopup" >
		<view class="canvaspopup-content">
			<img :src="poster"  mode="widthFix" class="poster-img" :show-menu-by-longpress="true" alt="">
			<!-- <canvas type="2d" class="drawimg-canvas" id="drawimg" style="width:512px;height:600px;"></canvas> -->
			<canvas class="drawimg-canvas" id="drawimg" :style="{width:width+'px;',height: height+'px'}"></canvas>
			<view class="footer" @click="handleSaveImg">
				保存图片
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import { dateFormat } from '@/common/util.js'
	import { draw } from '@/api/draw.js'
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	var app = getApp();
	export default {
		props: {
			imgsrc: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				systemInfo: null,
				width: 0,
				height: 0,
				canvasAttrs: null,
				poster: '',
				qrcode: ''
			};
		},
		computed: {
			...mapState(['userId', 'settings', 'chatType'])
		},
		created() {
			console.log('app.globalData.systemInfo', app.globalData.systemInfo)
			this.systemInfo = app.globalData.systemInfo
			this.width = 280 * this.systemInfo.pixelRatio
			this.height = 360 * this.systemInfo.pixelRatio
		},
		mounted() {
			
		},
		methods: {
			dateFormat,
			getQrCodeImg() {
				const src = this.settings.qrcode
				const that = this
				let fileName = new Date().valueOf();
				wx.downloadFile({ //下载图片到本地
					url: src,
					filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.png',
					success(res) {
						console.log(res)
						if (res.statusCode === 200) {
							that.qrcode = res.filePath
							// that.$store.commit('setImageSrc', {name: `img_${that.message.id}`, src: img })
							// TODO draw image
							// that.startQueryElement()
							that.drawCanvas()
						}
					},
					fail() {
					}
				})
			},
			showPopup() {
				this.$refs.canvaspopup.open('center');
				this.startDownLoadImg()
			},
			// 先下载二维码
			startDownLoadImg() {
				this.getQrCodeImg()
			},
			startQueryElement() {
				// this.$nextTick(() => {
					var query = uni.createSelectorQuery().in(this);
					query.select('#drawimg').boundingClientRect().exec((res) => {
						// 返回值包括画布的实际宽高
						console.log(res)
						this.drawCanvas(res[0])
					})
				// })
			},
			drawCanvas() {
				const that = this
				// let ctx = wx.createCanvasContext('drawimg', this)
				const ratio = this.systemInfo.pixelRatio
				const query = uni.createSelectorQuery().in(this)
				query.select('#drawimg')
					.fields({ node: true, size: true })
					.exec(async (res) => {
						console.log(res)
						const canvas = res[0].node
						const ctx = canvas.getContext('2d')
						debugger
						// const dpr = wx.getSystemInfoSync().pixelRatio
						// canvas.width = res[0].width * dpr
						// canvas.height = res[0].height * dpr
						// ctx.scale(dpr, dpr)
						let canvasW = res[0].width // 画布的真实宽度
						let canvasH = res[0].height //画布的真实高度

						// 头像和二维码大小都需要在规定大小的基础上放大像素比的比例后面都会 *this.systemInfo.pixelRatio
						// let headerW = 48 * this.systemInfo.pixelRatio
						// let headerX = (canvasW - headerW) / 2
						// let headerY = 40 * this.systemInfo.pixelRatio
						// let qrcodeW = 73 * this.systemInfo.pixelRatio
						// let qrcodeX = 216 * this.systemInfo.pixelRatio
						// let qrcodeY = 400 * this.systemInfo.pixelRatio
						// 填充背景
						ctx.fillStyle = 'red'  
						ctx.fillRect(0, 0, canvasW, canvasH)
						ctx.save()
						// 画图
						
						const mainImg = canvas.createImage();
						mainImg.src = that.imgsrc;
						let mainImgPo = await new Promise((resolve, reject) => {
						  mainImg.onload = () => {
							resolve(mainImg)
						  }
						  mainImg.onerror = (e) => {
							reject(e)
						  }
						});
						let h = mainImgPo.height;
						let w = mainImgPo.width;
						
						console.log('：', h, w, canvasW , canvasW);
						ctx.drawImage(mainImgPo, 0, 0, w * ratio, h * ratio, 0, 0, canvasW , canvasW)
						ctx.save()
						 
						// 画二维码 
						// ctx.drawImage(that.qrcode, 20, canvasW + 20,  canvasW / 4, canvasW / 4)
						// ctx.save()
						
						//文案内容
						let txtLeftPos = 65;
						ctx.textBaseline = "bottom";
						ctx.textAlign = 'left';
						//用户昵称
						ctx.font = "14px bold"; //设置字体大小，默认10
						ctx.fillStyle = '#FFF'; //文字颜色：默认黑色
						ctx.fillText('yaoxin', 40, 20)//绘制文本
						
						// // ctx.draw()
						setTimeout(() => {
						//下面的13以及减26推测是因为在写样式的时候写了固定的zoom: 50%而没有用像素比缩放导致的黑边，所以在生成时进行了适当的缩小生成，这个大家可以自行尝试
						wx.canvasToTempFilePath({
							canvas: canvas ,
							x: 0,
							y: 0,
							width: that.widht,
							height: that.height,
							destWidth: that.width * ratio,
							destHeight: that.height * ratio,
							success: (res) => {
								console.log('canvasToTempFilePath', res);
								that.poster = res.tempFilePath
							}
						})
					}, 1000)

				})

			},
			handleSaveImg() {
				const that = this
				wx.saveImageToPhotosAlbum({
				  filePath: that.poster,
				  success: function (data) {
					wx.showToast({
					  title: '已保存到相册',
					  icon: 'success',
					  duration: 2000
					})
				  },
				  fail: function (err) {
					console.log(err)
				  },
				  complete(res) {
					console.log(res);
				  }
				})
			},
			async handleSaveImg2() {
				let self = this;
				const query = wx.createSelectorQuery();
				const canvasObj = await new Promise((resolve, reject) => {
				  query.select('#posterCanvas')
					.fields({ node: true, size: true })
					.exec(async (res) => {
					  resolve(res[0].node);
					})
				});
				console.log(canvasObj);
				wx.canvasToTempFilePath({
				  //fileType: 'jpg',
				  //canvasId: 'posterCanvas', //之前的写法
				  canvas: canvasObj, //现在的写法
				  success: (res) => {
					console.log(res);
					self.setData({ canClose: true });
					//保存图片
					wx.saveImageToPhotosAlbum({
					  filePath: res.tempFilePath,
					  success: function (data) {
						wx.showToast({
						  title: '已保存到相册',
						  icon: 'success',
						  duration: 2000
						})
					  },
					  fail: function (err) {
						console.log(err);
						if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
						  console.log("当初用户拒绝，再次发起授权")
						} 
					  },
					  complete(res) {
						wx.hideLoading();
						console.log(res);
					  }
					})
				  },
				  fail(res) {
					console.log(res);
				  }
				}, this)
			},
			getPhotosAuthorize: function () {
			    let self = this;
			    wx.getSetting({
			      success(res) {
			        console.log(res)
			        if (!res.authSetting['scope.writePhotosAlbum']) {
			          wx.authorize({
			            scope: 'scope.writePhotosAlbum',
			            success() {
			              console.log('授权成功')
			              self.saveImg();
			            },
			            //用户拒绝
			            fail() {
			              console.log("用户再次拒绝")
			            }
			          })
			        } else {
			          self.saveImg();
			        }
			      }
			    })
			  },
		}
	}
</script>

<style lang="less" scoped>

	.canvaspopup-content {
		height: 800rpx;
		width: 600rpx;
		padding: 20rpx 0rpx 130rpx;
		background-color: #33373f;
		box-sizing: border-box;
		
		.poster-img {
			width: 100%;
		}
		
		.drawimg-canvas {
			// background-color: #fafafa;
			// zoom: 50%; // 将画布缩小到50%（最好通过像素比进行缩小，像素比是2的话就是50%，如果不全是以像素比为标准，在生成图片的时候可能会出现四周黑边）
			position: absolute;
			left: -2000px; // 将画布隐藏在可视区域外
			// background: #206949;
			

		}
	}
	
</style>
