<template>
	<div class="tools_container g_pl_10 g_pr_10 g_pb_12 u-skeleton">
      <view class="g_h_10"></view>
		<div class="g_flex_row_start " style="column-gap: 6px">
			<div v-for="(item, index) in imgList" :key="index" class="g_flex_column_between flex_center g_radius_8 g_bg_f g_mb_6 " style="width: calc((100% - 12px) / 3); overflow: hidden">
				<div class="g_w_all u-skeleton-rect g_position_rela" style="overflow: hidden">
					<u-lazy-load :image="item.img" threshold="-100" @click="getPoster(item.img)" img-mode="widthFix" loadingImg="https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/dailibaoming/loading.gif"></u-lazy-load>
					<div @click="getPoster(item.img)" class="g_position_abso g_bg_f g_radius_3 g_flex_row_between flex_center" style="width: 94%; height: 15%; padding: 0 6px; transform: translateX(-50%); left: 50%; bottom: 3%; box-sizing: border-box">
						<div class="g_position_rela g_flex_row_start flex_center g_flex_1 g_h_all">
							<!-- <img style="width: 15%; height: 40%" :src="miniAppInfo.logo || 'https://matripe.oss-cn-beijing.aliyuncs.com/default.png'" alt="" /> -->
							<div class="g_ml_2 g_position_abso" style="left: 0%; transform-origin: left; transform: scale(0.4); width: calc(200%)">
								<div :style="{ fontSize: '12px' }">
									{{ miniAppInfo.fullName || miniAppInfo.agencyName }}
								</div>
								<div class="g_ell_1 g_w_all" :style="{ fontSize: '10px' }">
									{{ miniAppInfo.slogan }}
								</div>
							</div>
						</div>
						<img style="width: 20%; height: 64%" :src="miniAppInfo.qrCode" alt="" />
					</div>
				</div>
				<!-- <rh-button primaryColor='#6a81ff' btnText="生成海报" type="primary" size="mini" class="g_mb_12 g_mt_12 u-skeleton-rect" @clickBtn="getPoster(item)" /> -->
			</div>
		</div>
		<u-popup v-model="posterShow" mode="center" :closeable="true" uZindex="9999" width="90%" height="87%" border-radius="12" :mask-close-able="true" @close="currentImg = ''">
			<div v-if="currentImg" class="g_pt_36 g_pb_12 g_text_c g_position_abso" style="height: calc(100% - 56px); width: 100%; box-sizing: border-box; left: 0%; top: 0px; z-index: 999">
				<view class="fakerClose g_w_36 g_h_36" style="position: absolute; top: 0; right: 0; z-index: 999" @click="posterShow = false"></view>
				<image class="g_position_abso" style="height: 92%; left: 50%; top: 36px; transform: translateX(-50%)" :show-menu-by-longpress="true" :src="currentImg" mode="aspectFit" lazy-load binderror="" bindload=""> </image>
			</div>
			<div class="g_w_all g_flex_row_center g_pt_36 g_pb_12" style="height: calc(100% - 56px); box-sizing: border-box">
				<div v-if="fakeImg" class="g_h_all g_position_rela" style="width: 85%">
					<img :src="fakeImg" class="g_h_all g_w_all" alt="" />
					<div class="g_position_abso g_bg_f g_radius_6 g_flex_row_between flex_center" style="width: 94%; height: 16%; padding: 0 4%; transform: translateX(-50%); left: 50%; bottom: 3%; box-sizing: border-box">
						<div class="g_flex_row_start flex_center g_flex_1 g_h_all">
							<div class="g_ml_4 g_c_6">
								<div class="g_fw_600" :style="{ fontSize: '100%' }">
									{{ miniAppInfo.fullName || miniAppInfo.agencyName }}
								</div>
								<div :style="{ fontSize: '60%' }">
									{{ miniAppInfo.slogan || "为劳动者创造价值" }}
								</div>
							</div>
						</div>
						<img style="width: 22%; height: 60%" :src="miniAppInfo.qrCode" alt="" />
					</div>
				</div>
			</div>
			<div class="g_flex_row_center">
				<rh-button primaryColor='#6a81ff' :btnText="fakeImg ? '生成中...' : '保存图片'" :loading="fakeImg ? true : false" @clickBtn="saveImg" type="primary" size="160" class="" />
				<!-- <rh-button primaryColor='#6a81ff' btnText="分享图片" size="small" class="" /> -->
			</div>
		</u-popup>
		<canvas type="2d" style="position: absolute; left: -2000px; width: 425px; height: 350px; background: #fff" id="canvasId" ref="canvasId"></canvas>
	</div>
	<u-skeleton :loading="showPage" :animation="true" border-radius="12"></u-skeleton>
</template>

<script>
export default {
	name: "tools",
	data() {
		return {
			showPage: true,

			fakeImg: "", // 站位虚拟分享图

			imgList: [1,2,3,4,5,6,7,8,9,10,11,12],
			currentImg: "",
			posterShow: false,
			miniAppInfo: uni.getStorageSync("agencyInfo"),
			query: {
				page: 1,
				size: 50,
				list: [],
				isFinish: -1,
			},
		};
	},
	onLoad() {
		setTimeout(() => {
			this.showPage = false;
		}, 2000);
	},
	created() {
		// for (let i = 0; i < 12; i++) {
		// 	this.imgList[i] = `https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/dailibaoming/poster/a${i + 1}.png?chuo=` + new Date().getTime();
		// }
		// console.log(this.imgList);
		this.getPosterList();
		this.getUserQRCode();
	},
	props: {
		// firstLoad: {
		// 	type: Boolean,
		// 	default: false,
		// },
	},
	watch: {
		// firstLoad(val) {
		// 	console.log("firstLoad", val);
		// 	if (val) {
		// 		this.showPage = true;
		// 		setTimeout(() => {
		// 			this.showPage = false;
		// 		}, 2000);
		// 	}
		// },
	},
	methods: {
		getUserQRCode() {
			let that = this;
			if (uni.getStorageSync("user_qrcode")) {
				that.miniAppInfo.qrCode = uni.getStorageSync("user_qrcode");
			}
		},
		getPosterList() {
			let that = this;
			let params = {
				pageNum: that.query.page,
				pageSize: that.query.size,
				classify: 1, // 分享海报为1
			};
			that.G.Post(that.api.app_getPosterList, params, (res) => {
				console.log(res);
				that.imgList = res;
			});
		},
		getPoster(e) {
			const that = this;
			this.fakeImg = e;
			that.posterShow = true;
			try {
				// #ifdef  APP-PLUS
				that.getAppCanvas(e);
				// .then((res) => {});
				// #endif
				// #ifdef  MP-WEIXIN
				that.getWXCanvas(e).then((res) => {
					console.log("res", res);
					that.currentImg = res.tempFilePath;
					setTimeout(() => {
						this.fakeImg = "";
					}, 200);
					uni.hideLoading();
				});
				// #endif
			} catch (error) {
				uni.showToast({
					title: "生成失败，请重试",
					icon: "none",
				});
				uni.hideLoading();
				that.posterShow = false;
			}
		},
		// 微信端绘制
		getWXCanvas(sharelImg, type) {
			const that = this;
			return new Promise((resolve) => {
				var mycenter = 0; //文字左右居中显示
				var myheight = 0; //文字高度
				const query = uni.createSelectorQuery().in(this);
				query
					.select("#canvasId")
					.fields({
						node: true,
						size: true,
					})
					.exec((res) => {
						console.log("uni 获取节点信息：", res);
						// console.log("sharelImg", sharelImg);
						const canvas = res[0].node;
						const ctx = canvas.getContext("2d");
						new Promise(function (resolve) {
							// 绘制背景图片
							uni.getImageInfo({
								src: sharelImg, // 网络图片
								success(res) {
									console.log("res111", res);
									canvas.width = res.width;
									canvas.height = res.height;
									mycenter = canvas.width / 2;
									myheight = canvas.height;
									const img = canvas.createImage();
									img.src = res.path;
									console.log("img111", img);
									img.onload = (info) => {
										ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
										console.log("info111", info);
										resolve(true);
									};
								},
								fail(err) {},
							});
						}).then(() => {
							console.log("inthen");
							//使用：
							that
								.setShareJobImg(ctx, canvas, mycenter)
								.then(function (canvas1) {
									console.log("canvas1", canvas1);
									uni.canvasToTempFilePath({
										canvas: canvas1,
										success(res) {
											console.log("res222", res);
											resolve(res);
										},
										fail(res) {
											uni.hideLoading();
											uni.showToast({
												title: res.errMsg,
												icon: "error",
											});
										},
									});
								})
								.catch((err) => {
									console.log(err);
									uni.hideLoading();
									uni.showToast({
										title: "生成失败,请重试",
									});
								});
						});
					});
			});
		},
		// 设置分享布局
		setShareJobImg(ctx, canvas, mycenter, funObj) {
			let that = this;
			let labelLeft = 0;
			// ctx.arcTo()
			let baseTop, QRSize, baseLeft, titleFontSize, contentFontSize;
			baseTop = canvas.height - 412;
			// baseTop = 1470;
			QRSize = 144;
			baseLeft = 80;
			titleFontSize = 54;
			contentFontSize = 36;
			that.G.roundRect1(ctx, mycenter - (canvas.width - 60) / 2, baseTop, canvas.width - 60, 360, 48, "#fff");
			that.G.fillTextLineBreak(ctx, that.miniAppInfo.fullName || that.miniAppInfo.agencyName, baseLeft + 20, baseTop + 162, 300, 64, "#000", titleFontSize, "500"); // 代理名字
			let slogan = that.miniAppInfo.slogan || "为劳动者创造价值";
			// let slogan = '为劳动者创造价值'
			that.G.fillTextLineBreak(ctx, slogan, baseLeft + 20, baseTop + 168 + titleFontSize, 600, 48, "#666", contentFontSize, "500"); // slogan

			// miniAppInfo
			return new Promise((imgres) => {
				let p1 = new Promise((resolve) => {
					uni.getImageInfo({
						// src: "https://bocai-cms.oss-cn-beijing.aliyuncs.com/web-resource/dailibaoming/poster/renhaiQRCode.png",
						src: that.miniAppInfo.qrCode,
						success(res) {
							console.log("res333", res);
							const img = canvas.createImage();
							img.src = res.path;
							img.onload = () => {
								console.log("ctx", ctx);
								console.log("canvas", canvas);
								console.log("that.miniAppInfo.logo", that.miniAppInfo.logo);
								// that.G.roundRect1(ctx, mycenter - 580 / 2, baseTop + 740, 580, 580, 0, "#fff");
								that.G.roundRect(ctx, img, canvas.width - 320, baseTop + 60, 240, 240, 0);
								resolve();
							};
						},
						fail(err) {
							console.log(err);
						},
					});
				});
				let p2 = new Promise((resolve) => {
					uni.downloadFile({
						url: that.miniAppInfo.logo || "https://matripe.oss-cn-beijing.aliyuncs.com/default.png",
						success(res) {
							console.log(res);
							const img = canvas.createImage();
							img.src = res.tempFilePath;
							img.onload = () => {
								that.G.roundRect(ctx, img, 20, 20, 180, 180, 90);
								resolve();
							};
						},
						fail(err) {
							console.log(err);
							resolve();
						},
					});
				});
				Promise.all([p1, p2]).then(() => {
					// setTimeout(() => {
					imgres(canvas);
					// }, 300);
				});
			});
		},
		// App端绘制
		getAppCanvas(sharelImg, type) {
			let that = this,
				ctx = uni.createCanvasContext("text");
			console.log("this.miniAppInfo.qrCodethis.miniAppInfo.qrCodethis.miniAppInfo.qrCode", this.miniAppInfo.qrCode);
			new Promise(function (resolve) {
				// 绘制背景图片
				uni.downloadFile({
					url: sharelImg,
					success: function (bgRes) {
						uni.getImageInfo({
							src: bgRes.tempFilePath, // 网络图片
							success(res) {
								let mycenter = res.width;
								let _height = res.height;
								that.canvasWidth = res.width;
								that.canvasHeight = res.height;
								ctx.drawImage(bgRes.tempFilePath, 0, 0, mycenter, _height);
								console.log("bgResbgResbgResbgResbgRes", bgRes);

								// ctx.drawImage(bgRes.tempFilePath, 0, 0, mycenter, _height);
								uni.downloadFile({
									url: that.miniAppInfo.qrCode,
									success: function (QRres) {
										console.log("QRresQRresQRresQRresQRres", QRres);
										let baseTop, QRSize, baseLeft, titleFontSize, contentFontSize;
										baseTop = _height - 412;
										// baseTop = 1470;
										QRSize = 144;
										baseLeft = 80;
										titleFontSize = 54;
										contentFontSize = 36;
										that.G.roundRect1(ctx, 30, baseTop, mycenter - 60, 360, 48, "#fff");
										that.G.fillTextLineBreak(ctx, that.miniAppInfo.fullName || that.miniAppInfo.agencyName, baseLeft + 20, baseTop + 162, 300, 64, "#000", titleFontSize, "500"); // 代理名字
										let slogan = that.miniAppInfo.slogan || "为劳动者创造价值";
										// let slogan = '为劳动者创造价值'
										that.G.fillTextLineBreak(ctx, slogan, baseLeft + 20, baseTop + 168 + titleFontSize, 600, 48, "#666", contentFontSize, "500"); // slogan
										that.G.roundRect(ctx, QRres.tempFilePath, mycenter - 320, baseTop + 60, 240, 240, 0);
										ctx.restore();
										ctx.draw(false, () => {
											setTimeout(function () {
												that.endAppCanvas(ctx, mycenter, _height);
											}, 50);
										});
									},
								});
								// uni.downloadFile({
								// 	url: info.logo,
								// 	success: function (bgRes) {
								// 		that.G.roundRect(ctx, bgRes.tempFilePath, 915, 218, 272, 272, 136); // logo
								// 	},
								// });
							},
							fail(err) {},
						});
					},
				});
			}).then(() => {});
		},
		endAppCanvas(ctx, _width, _height) {
			let that = this;
			uni.canvasToTempFilePath({
				x: 0,
				y: 0,
				width: _width,
				height: _height,
				canvasId: "text",
				success: function (pathRres) {
					const savedFilePath = pathRres.tempFilePath; //相对路径
					const path = plus.io.convertLocalFileSystemURL(savedFilePath); //绝对路径
					console.log("path", path);
					that
						.getBase64FromFile(path)
						.then((res) => {
							console.log("resresres", res);
							that.currentImg = res;
							that.appfile = savedFilePath;
							setTimeout(() => {
								that.fakeImg = "";
							}, 200);
							uni.hideLoading();
						})
						.catch((err) => {
							console.log("err", err);
						});
					// const fileReader = new plus.io.FileReader();
					// fileReader.readAsDataURL(path);
					// fileReader.onloadend = (res) => {
					// 	console.log("resresresresres", res);
					// 	that.currentImg = path;
					// 	that.appfile = savedFilePath;
					// 	setTimeout(() => {
					// 		that.fakeImg = "";
					// 	}, 200);
					// 	uni.hideLoading();
					// };
				},
			});
		},
		getBase64FromFile(path) {
			return new Promise((resolve, reject) => {
				plus.io.resolveLocalFileSystemURL(
					path,
					(entry) => {
						console.log("entry", entry);
						entry.file((file) => {
							let reader = new plus.io.FileReader();
							reader.onloadend = function (e) {
								console.log("eeeeee", e);
								// 结果为 "data:image/png;base64,xxx..." 格式
								resolve(e.target.result);
							};
							reader.onerror = function (e) {
								reject("读取失败：" + e.message);
							};
							// 关键：使用 readAsDataURL 生成 Base64
							reader.readAsDataURL(file);
						}, reject);
					},
					reject
				);
			});
		},
		saveImg() {
			let that = this;
			console.log("saveImg");
			if (that.fakeImg) return false;
			uni.saveImageToPhotosAlbum({
				filePath: that.currentImg,
				success(res) {
					console.log(res);
					if (res.errMsg == "saveImageToPhotosAlbum:ok") {
						uni.showToast({
							title: "保存成功 ",
							icon: "none",
							duration: 1500,
						});
					}
				},
				fail(res) {
					console.log(res);
					uni.showToast({
						title: "图片保存失败",
						icon: "none",
						duration: 1500,
					});
				},
			});
		},
	},
};
</script>

<style>
.tools_container {
	min-height: 100vh;
	background-color: #ededed;
}
.list-image {
	background-size: cover;
	background-position: top center;
	background-repeat: no-repeat;
}
</style>
