<template>
	<view class="container">
		<navBar title="二维码进入的页面" :back="true" color="white" background="green" />
		<button @click="getAccessToken">生成AccessToken</button>
		<button @click="getAccessToken">生成进入小程序的二维码</button>
		<button @click="createPoster">测试生成海报</button>

		<image @click="previewPic" :src="testUrl" mode=""></image>


		<u-popup :show="showPoster" mode="bottom" @close="showPoster = false">
			<!-- <view :style="{height: tobheight+'px'}"></view> -->
			<scroll-view scroll-y="true" :style="{maxHeight: posterheight +'px'}">

				<wike-painter :board="posterObj" @done="posterSuccess" ref="painter"></wike-painter>
				<view style="height: 78px;"></view>
				<view class="dygbhg">
					<view class="whole" @click="showPoster = false">取消</view>
					<view class="distinguish" @click="toSave">保存/分享</view>
				</view>
			</scroll-view>


		</u-popup>
	</view>
</template>

<script>
	import wikePainter from '@/components/wike-painter/wike-painter.vue'
	var util = require('@/utils/decodeQrQuery.js')
	import {
		getBase64Image
	} from '@/utils/streamDown.js'

	import uploadUrl from '@/common/config.js'
	export default {
		components: {
			wikePainter
		},
		data() {
			return {
				kcardCode: '',
				testUrl: '',
				info: {
					poster_bg_img_path: 'http://file.shopro.top/imgs/commission/commission_card_bg.png',
					poster_bg_width: '750',
					poster_bg_height: '1334',

					poster_qrcode_x: '514',
					poster_qrcode_y: '1174',

					poster_bg_img: "1671",
					poster_bg_img_path: "https://nywhcm.com/addons/wike_aging/public/static/storage/20230625/74f8be11f3f174e63576a777c71d644b.jpg",
					// poster_bg_img_path: "https://nywhcm.com/addons/wike_aging/public/static/storage/20230322/17859fbc20087bd430f224905f5d9370.jpg",

					poster_bg_img_filename: "分销海报.jpg",
					poster_qrcode_width: "135",
					poster_qrcode_width_path: "https://nywhcm.com/addons/wike_aging/public/static/storage/20230322/17859fbc20087bd430f224905f5d9370.jpg",
					poster_qrcode_width_filename: "tmp_c1537e2c3beb0a3d14f87a63da8b84cc548ea7871f918188.jpg",

				},

				qrcode: 'https://nywhcm.com/addons/wike_aging/public/h5/?uniacid=5059&spm=4825.1.0.1.1',
				// qrcode: 'https://nywhcm.com/addons/wike_aging/public/static/storage/20230322/17859fbc20087bd430f224905f5d9370.jpg',

				showPoster: false,
				posterObj: {},
				posterheight: 0
			}
		},
		onLoad(options) {

			const that = this;

			if (this.platform == 'wxMiniProgram') {
				var menumtop = uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight
				var paddingtop = uni.getSystemInfoSync().statusBarHeight + menumtop
				this.tobheight = (menumtop + paddingtop + uni.getMenuButtonBoundingClientRect().height)
			}
			this.posterheight = uni.$u.sys().windowHeight - this.tobheight

			console.log('二维码页面onLoad：', options);
			// 获取小程序启动时的参数
			let obj = wx.getLaunchOptionsSync();
			let query = null;

			if (options.scene || obj.query.scene) {
				// 这里是用开发者工具模拟的时候要先用 encodeURIComponent 编译，模拟真实传递参数的效果，项目发布审核的时候这句话要注释掉
				// query = options ? encodeURIComponent(options.scene) : encodeURIComponent(obj.query.scene);
				query = options ? decodeURIComponent(options.scene) : decodeURIComponent(obj.query.scene);
				// query =  decodeURIComponent(obj.query.scene);

				//解析参数
				let web_key = query.split("-")[0];
				let web_template = query.split("-")[1];
				let web_id = query.split("-")[2];
				console.log("第一个参数：", web_key);
				console.log("第二个参数：", web_template);
				console.log("第三个参数：", web_id);
			}

			// 'scene=asaa234354565-32323432kjkjkjkHHHHH-你好'

			// if (options.kcardCode) {
			// 	console.log('需要获取的二维码参数kcardCode：', options.kcardCode);
			// }

			// var that = this;
			// console.log("options携带参数：" + JSON.stringify(options))
			// //在此函数中获取扫描普通链接二维码参数
			// // 二维码链接内容会以参数q的形式带给页面，在onLoad事件中提取q参数并自行decodeURIComponent一次，即可获取原二维码的完整内容。
			// if (options.q !== undefined) {
			// 	let q = decodeURIComponent(options.q);

			// 	console.log("url=" + q)
			// 	console.log("kcardCode=" + util.getkcard(q, 'kcardCode'))
			// 	var kcardCode = util.getkcard(q, 'kcardCode');

			// 	console.log("解析获取到的kcardCode值：" + kcardCode);
			// 	that.kcardCode = kcardCode
			// } else {
			// 	console.log("未获取到扫码信息：" + kcardCode);

			// 	uni.showToast({
			// 		title: '错误：未获取到扫码信息!',
			// 		duration: 3000
			// 	})

			// 	return false
			// }
		},
		onShow() {


		},
		methods: {
			previewPic() {
				uni.previewImage({
					urls: [this.testUrl]
				})
			},
			getAccessToken() {
				let that = this
				let appId = 'wx98ab2939999e13de'
				let secret = '841f428c4d3e550e800d8ad0fd5e0354'
				wx.request({
					url: `https://api.weixin.qq.com/cgi-bin/token?appid=${appId}&secret=${secret}&grant_type=client_credential`,
					data: {},
					header: {
						'content-type': 'json'
					},
					success: function(res) {
						console.log(res);
						that.getUnlimitedQRCode(res.data.access_token)
					}
				})
			},
			// getWxQrCode(access_token) {
			getUnlimitedQRCode(access_token) {
				let that = this
				wx.request({
					url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}`,
					responseType: 'arraybuffer',
					data: JSON.stringify({
						scene: 'kcardCode=123456',
						// page: 'pages/index/index',
						// scene: 'a=1-b=2-c=李万涛',
						page: 'pages/index/index',
						check_path: false
					}),
					header: {
						'content-type': 'json',
					},
					method: 'POST',
					success: function(res) {
						// const imageArrayBuffer = res.data;
						// const base64Str = wx.arrayBufferToBase64(imageArrayBuffer);

						// let filePath = `${wx.env.USER_DATA_PATH}/temp${Date.now()}.jpg`
						// wx.getFileSystemManager().writeFile({
						// 	filePath,
						// 	data: base64Str,
						// 	encoding: 'base64',
						// 	success: function(res) {
						// 		that.testUrl = filePath
						// 		console.log('wx.getFileSystemManager()', res,
						// 			`${wx.env.USER_DATA_PATH}/temp.jpg`);
						// 		// wx.saveImageToPhotosAlbum({
						// 		// 	filePath: res.filePath,
						// 		// 	success: function() {
						// 		// 		console.log('保存成功');
						// 		// 	},
						// 		// 	fail: function(err) {
						// 		// 		console.log('保存失败', err);
						// 		// 	}
						// 		// });
						// 	},
						// 	fail: function(err) {
						// 		console.log('创建临时文件失败', err);
						// 	}
						// });
						// that.upImg(`${wx.env.USER_DATA_PATH}/temp.jpg`, 2)

						// return
						// console.log(res);
						const base64 = wx.arrayBufferToBase64(res.data);
						that.testUrl = 'data:image/jpeg;base64,' + base64;
						that.qrcode = 'data:image/jpeg;base64,' + base64
						// that.createPoster()
						// console.log('testUrl----base64', that.testUrl, base64, res.data);
					}
				})
			},
			genQr() {

			},

			upImg(file, type = 1) {
				// console.log('upImg的file', file)
				let _this = this
				uni.uploadFile({
					url: uploadUrl.baseUrl, // 上传的 URL 地址
					filePath: file, // 要上传的图片本地路径
					name: 'file', // 上传图片时使用的字段名
					header: { // 自定义请求头
						'Content-Type': 'multipart/form-data'
					},
					formData: {
						'fileType': 'images',
						'dirName': 'cert'
					},
					success: function(uploadRes) {
						let result = JSON.parse(uploadRes.data)
						// localStorage.set('imgUrl', result.data.fileUrl)
						if (result.code == 0) {
							if (type == 2) {
								_this.testUrl = result.data.url
							} else {
								_this.avatarUrl = result.data.url
							}
							// _this.user_img = result.data.url
							console.log('上传后的阿里云url地址', result.data.url)
						}
					},
					fail: function(err) {
						console.log('upload failed:', err)
					}
				})
			},




			// 测试生成海报
			async createPoster(e) {
				let that = this;
				let httpsurl = '';
				console.log('httpsurl----', httpsurl);
				uni.showLoading({
					title: '海报渲染中'
				});

				if (that.info.poster_bg_img_path.indexOf("https") < 0) {
					httpsurl = await that.getdownload(that.info.poster_bg_img_path.replace("http:", "https:"));
				} else {
					httpsurl = await that.getdownload(that.info.poster_bg_img_path);
				}
				if (httpsurl == 'fail') {
					uni.hideLoading();
					uni.showToast({
						title: '生成失败',
						icon: 'none'
					})
					return;
				}
				let proportionally = this.info.poster_bg_width / uni.$u.sys().windowWidth;
				(this.posterObj = {
					width: (this.info.poster_bg_width / proportionally) + 'px',
					height: (this.info.poster_bg_height / proportionally) + 'px',
					background: '#fff',
					borderRadius: '16rpx',

					views: [{
							src: httpsurl,
							type: "image",
							css: {
								width: (this.info.poster_bg_width / proportionally) + 'px',
								height: (this.info.poster_bg_height / proportionally) + 'px',
							}
						},
						{
							type: 'view',
							css: {
								left: (this.info.poster_qrcode_x / proportionally) + 'px',
								top: (this.info.poster_qrcode_y / proportionally) + 'px',
								position: 'fixed',

							},
							// #ifdef H5
							views: [{
								type: 'qrcode',
								text: this.qrcode,
								css: {
									width: (this.info.poster_qrcode_width / proportionally) + 'px',
									height: (this.info.poster_qrcode_width / proportionally) + 'px',
									background: '#fff'
								}
							}],
							// #endif
							// #ifdef MP-WEIXIN
							views: [{
								type: 'image',
								src: this.qrcode,
								css: {
									width: (this.info.poster_qrcode_width / proportionally) + 'px',
									height: (this.info.poster_qrcode_width / proportionally) + 'px',
									background: '#fff'
								}
							}],
							// #endif
						}
					]
					// #ifdef H5
					// #endif
					// #ifdef MP-WEIXIN
					// #endif
				}),
				(this.showPoster = true);
			},

			toSave() {
				uni.showLoading({
					title: '海报生成中'
				});
				this.$refs.painter.canvasToTempFilePathSync({
					// 在nvue里是jpeg
					fileType: 'jpg',
					quality: 1,
					success: res => {
						// #ifdef MP-WEIXIN
						wx.showShareImageMenu({
							path: res.tempFilePath
						})
						this.showPoster = false;
						uni.hideLoading();
						// #endif
						// #ifdef H5
						this.showPoster = false;
						uni.hideLoading();
						uni.showModal({
							confirmColor: '#26B3A0',
							confirmText: '查看图片',
							title: '提示',
							content: '查看图片后长按图片即可保存或分享',
							success(src) {
								if (src.confirm) {
									uni.previewImage({
										urls: [res.tempFilePath]
									});
								} else if (src.cancel) {
									this.showPoster = true;
								}
							}
						});
						// #endif
					}
				});
			},
			posterSuccess() {
				uni.hideLoading();
			},
			getdownload(e) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: e,
						method: 'GET',
						responseType: 'arraybuffer',
						success: ress => {
							let base64 = wx.arrayBufferToBase64(ress.data);
							base64 = 'data:image/jpeg;base64,' + base64
							resolve(base64);
						},
						fail: (e) => {
							resolve('fail');
						}
					})
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>