<!-- 
电子证书
http://localhost:5173/card/#/pages/achievement/ecert/ecert
https://oss-mbh5.colormaprun.com/card/#/pages/achievement/ecert/ecert
 -->
<template>
	<view class="main">
		<my-topbar :mcName="ecertConfig.title" class="mytopbar" :showRule="false" @btnBackClick="btnBack"></my-topbar>
		<!-- <text class="title" v-html="ecertConfig.title"></text> -->
		<image v-if="canvasReady" ref="ecertImg" class="ecertImg" :style="getEcertImageStyle()" mode="aspectFit" :src="ecertUrl" @click="previewCert"></image>
		<div v-else class="loading-animation"></div>
		<view class="btnlist uni-row uni-jcse">
			<text v-if="isCertCreate == 0" class="btnlist-item" @click="modify">修改姓名</text>
			<text class="btnlist-item" @click="previewCert">预览证书</text>
			<text class="btnlist-item" @click="downloadCert">下载证书</text>
			<!-- <text class="btnlist-item" @click="shareWx">打开微信</text> -->
		</view>
		
		<!-- <br>
		<a :href="'action://down_file?filename='+encodeURIComponent('图片下载_xfl.png')+'&url='+encodeURIComponent('https://oss-mbh5.colormaprun.com/card/static/logo/xfl.png')">下载图片</a>
		&nbsp;
		<a :href="'action://down_file?filename='+encodeURIComponent('文件下载_index.html')+'&url='+encodeURIComponent('https://oss-mbh5.colormaprun.com/card/index.html')">下载文件</a>
		&nbsp;
		<a :href="'action://down_file?filename='+encodeURIComponent('音频下载_1.mp3')+'&url='+encodeURIComponent('https://oss-mbh5.colormaprun.com/card/static/audio/1.mp3')">下载音频</a>
		&nbsp;
		<br>
		<a :href="'action://down_file?filename='+encodeURIComponent('小视频下载_Walk_to_image_room.mp4')+'&url='+encodeURIComponent('https://oss-mbh5.colormaprun.com/card/Walk_to_image_room.mp4')">下载小视频</a>
		&nbsp;
		<a :href="'action://down_file?filename='+encodeURIComponent('大视频下载_wifidigger.mp4')+'&url='+encodeURIComponent('https://oss-mbh5.colormaprun.com/card/wifidigger.mp4')">下载大视频</a>
		&nbsp; -->
		<!-- <a href="tel:13335119550">拨打电话</a> &nbsp; -->

		<canvas v-if="canvasReady" canvas-id="ecert" id="ecert" class="ecert" :style="getEcertCanvasStyle()"></canvas>
		
		<uni-popup ref="modifyDialog" type="dialog">
			<uni-popup-dialog type="warn" mode="base" title="修改姓名" @confirm="modifyDialogConfirm">
				<view class="dialogView uni-column uni-jcse">
					<input class="uni-input" maxlength="12" placeholder="请输入姓名" placeholder-style="font-size: 14px;" v-model="newName" />
					<view class="dialogView-memo">（ 注：姓名<span style="color: red;">只能修改一次</span> ）</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="confirmDialog" type="dialog">
			<uni-popup-dialog type="warn" cancelText="取消" confirmText="确定" title="提示" :content="confirmContent"
				@confirm="confirmDialogConfirm"></uni-popup-dialog>
		</uni-popup>
		
		<!-- <movable-area :scale-area="true" class="movable-area">
			<movable-view class="movable-view" direction="all" :inertia="true" :scale-min="0.5" :scale-max="10" :scale="true" :out-of-bounds="true">
				<canvas canvas-id="ecert" id="ecert" class="ecert" :style="getEcertStyle()"></canvas>
			</movable-view>
		</movable-area> -->
	</view>
</template>

<script>
	import tools from '/common/tools';
	import {
		token,
		apiCertStyleQuery,
		apiUserBaseQueryInCertificate,
		apiCertificateCreateByUserAi,
		checkResCode
	} from '/common/api';

	export default {
		data() {
			return {
				pageName: "ecert",
				queryObj: {},
				queryString: "",
				token: "",
				certStyleType: "", // 证书样式类型 比如 "shanda1"
				oarId: 0, // 成就记录id

				dpr: 1, // 设备像素比
				windowWidth: uni.getSystemInfoSync().windowWidth, // 可视区域宽度
				// windowHeight: uni.getSystemInfoSync().windowHeight, // 可视区域高度
				ecertWidth: 0,
				ecertHeight: 0,
				ecertUrl: "",
				btnCertText: "确认生成证书",

				nickName: '',				
				coiId: 0, // 报名单位id
				coiName: "", // 报名单位名称
				teamNum: 0, // 队伍
				compName: "", // 赛事名称
				certificateName: "", // 奖项名称
				compBt: 0, // 赛事开始时间戳
				compEt: 0, // 赛事结束时间戳
				totalSysPoint: 0, // 个人总积分
				totalDistance: 0, // 个人总里程，单位米
				isCertCreate: 0, // 是否已经生成证书(生成后不能修改昵称) 0 未生成 1 已生成

				ecertConfig: {},
				canvasReady: false,
				newName: "",
				confirmContent: ""
			}
		},
		onLoad(query) {
			// console.log(query);
			this.queryObj = query;
			this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
			this.token = query["token"] ?? token;
			this.certStyleType = query["certStyleType"] ?? "";
			this.oarId = query["oarId"] ?? 0;

			this.init();
		},
		onReady() {
			// this.test();
		},
		methods: {
			init() {
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						that.dpr = res.pixelRatio;
						// console.log('设备像素比：', that.dpr);
						that.userBaseQueryInCertificate();
					}
				});
			},
			// 格式化 距离
			fmtDistanct(val) {
				return Math.round(val * 100 / 1000) / 100;
			},
			// 格式化 赛事日期
			fmtMcTime(timestamp1, timestamp2) {
				return tools.fmtMcTime3(timestamp1, timestamp2);
			},
			getEcertImageStyle() {
				if (this.ecertWidth == 0) {
					return "";
				}
				
				const ratio = 0.9;
				const width = this.windowWidth * ratio;
				const height = Math.round(this.windowWidth / this.ecertWidth * this.ecertHeight) * ratio;
				let style = "";
				style += "width: " + width + "px;";
				style += "height: " + height + "px;";
				// console.log("[getEcertImageStyle]", style);
				return style;
			},
			getEcertCanvasStyle() {
				let style = "";
				style += "width: " + this.ecertWidth + "px;";
				style += "height: " + this.ecertHeight + "px;";
				// console.log("[getEcertCanvasStyle]", style);
				return style;
			},
			getParamValue(paramName) {
				let value = null;
				if (paramName == "coiName") {
					value = "（" + this.coiName + "）";
				} else if (paramName == "totalDistance") {
					value = this.fmtDistanct(this.totalDistance);
				} else if (paramName == "compTime") {
					value = this.fmtMcTime(this.compBt, this.compEt);
				} else {
					return this[paramName];
				}
				return value;
			},
			drawText(param, text, context) {
				if (param.font != undefined) {
					const font = param.font;
					if (font.align != undefined && font.align.length > 0) {
						context.setTextAlign(font.align);
					}
					if (font.size != undefined && font.size > 0) {
						const font_family = (font.family != undefined && font.family.length > 0) ? font.family : "Arial";
						const font_size = Math.round(font.size / this.dpr);
						let style = `${font_size}px ${font_family}`;
						if (font.preStyle != undefined && font.preStyle.length > 0) {
							style = `${font.preStyle} ${style}`;
						}
						// console.log(style);
						context.font = style;
					}
					// if (font.size != undefined && font.size > 0) {
					// 	context.setFontSize(font.size / this.dpr);
					// }
					if (font.color != undefined && font.color.length > 0) {
						context.fillStyle = font.color;
					}

				}

				context.fillText(text, param.position.x / this.dpr, param.position.y / this.dpr);
			},
			makeCert() {
				let that = this;
				// console.log("[makeCert]", that.ecertConfig.tplUrl);
				
				const ctx = uni.createCanvasContext('ecert');
				ctx.drawImage(that.ecertConfig.tplUrl, 0, 0, that.ecertWidth, that.ecertHeight);
				
				for (var i = 0; i < that.ecertConfig.paramList.length; i++) {
					const param = that.ecertConfig.paramList[i];
					const text = that.getParamValue(param.paramName);
					that.drawText(param, text, ctx);
				}
				
				ctx.draw(true, () => {
					// 在这里调用uni.canvasToTempFilePath，确保绘制完成
					uni.canvasToTempFilePath({
						canvasId: 'ecert',
						success: function(res) {
							// 在H5平台下，tempFilePath 为 base64
							// console.log(res.tempFilePath);
							let imageData = res.tempFilePath;
							that.ecertUrl = imageData;
						}
					});
				});
			},
			// 查询电子证书样式
			certStyleQuery() {
				uni.request({
					url: apiCertStyleQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						"certStyleType": this.certStyleType
					},
					success: (res) => {
						// console.log("certStyleQuery", res);
						if (res.data.code == 0) {
							const data = res.data.data;
							const ecertConfig = data.configJson != "" ? JSON.parse(data.configJson) : "";
							this.ecertConfig = ecertConfig;

							/* this.ecertConfig = {
								"title": "完赛证书",
								"tplUrl": "/static/ecert/ecert_tpl.jpg",
								"width": 2000,
								"height": 2828,
								"paramList": [
									{
										"paramName": "compName",
										"font": {
											"preStyle": "bold",
											"size": 86,
											"family": "",
											"color": "#000000",
											"align": "center"
										},
										"position": {
											"x": 1000,
											"y": 1550
										}
									},
									{
										"paramName": "compTime",
										"font": {
											"preStyle": "",
											"size": 44,
											"family": "",
											"color": "#000000",
											"align": "center"
										},
										"position": {
											"x": 1100,
											"y": 1643
										}
									},
									{
										"paramName": "certificateName",
										"font": {
											"preStyle": "bold",
											"size": 116,
											"family": "",
											"color": "#fe0000",
											"align": "center"
										},
										"position": {
											"x": 1000,
											"y": 1900
										}
									},
									{
										"paramName": "nickName",
										"font": {
											"preStyle": "bold",
											"size": 56,
											"family": "",
											"color": "#000000",
											"align": "center"
										},
										"position": {
											"x": 1000,
											"y": 2120
										}
									},
									{
										"paramName": "coiName",
										"font": {
											"preStyle": "",
											"size": 46,
											"family": "",
											"color": "#646363",
											"align": "center"
										},
										"position": {
											"x": 1000,
											"y": 2200
										}
									},
									{
										"paramName": "totalDistance",
										"font": {
											"preStyle": "",
											"size": 40,
											"family": "",
											"color": "#fe0000",
											"align": "center"
										},
										"position": {
											"x": 910,
											"y": 1704
										}
									},
									{
										"paramName": "totalSysPoint",
										"font": {
											"preStyle": "",
											"size": 40,
											"family": "",
											"color": "#fe0000",
											"align": "left"
										},
										"position": {
											"x": 1320,
											"y": 1704
										}
									}
								]
							}; */

							// console.log("ecertConfig:", this.ecertConfig);

							this.ecertWidth = Math.round(this.ecertConfig.width / this.dpr);
							this.ecertHeight = Math.round(this.ecertConfig.height / this.dpr);
							// console.log("[certStyleQuery] ecertWidth ecertHeight:", this.ecertWidth, this.ecertHeight);
							this.canvasReady = true;
							
							this.$nextTick(() => {
								this.makeCert();
							});
						}
					},
					fail: (err) => {
						console.log("certStyleQuery err", err);
					},
				});
			},
			// 查询电子证书成就对应用户基本信息
			userBaseQueryInCertificate() {
				uni.request({
					url: apiUserBaseQueryInCertificate,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						"oarId": this.oarId
					},
					success: (res) => {
						// console.log("userBaseQueryInCertificate", res);
						if (res.data.code == 0) {
							const data = res.data.data;
							this.nickName = data.nickName;
							this.coiId = data.coiId;
							this.coiName = data.coiName;
							this.teamNum = data.teamNum;
							this.compName = data.compName;
							this.certificateName = data.certificateName;
							this.compBt = data.compBt;
							this.compEt = data.compEt;
							this.totalSysPoint = data.totalSysPoint;
							this.totalDistance = data.totalDistance;
							this.isCertCreate = data.isCertCreate;
						
							this.certStyleQuery();
						}
					},
					fail: (err) => {
						console.log("userBaseQueryInCertificate err", err);
					},
				});
			},
			// 根据成就信息确认生成电子证书
			certificateCreateByUserAi() {
				uni.request({
					url: apiCertificateCreateByUserAi,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						"oarId": this.oarId,
						"coiName": this.coiName,
						"coiId": this.coiId,
						"teamNum": this.teamNum,
						"nickName": this.nickName,
					},
					success: (res) => {
						// console.log("certificateCreateByUserAi", res);
						if (checkResCode(res)) {
							uni.showToast({
								icon: "none",
								title: "姓名修改成功",
								duration: 3000
							});
						}
						this.userBaseQueryInCertificate();
					},
					fail: (err) => {
						console.log("certificateCreateByUserAi err", err);
						uni.showToast({
							icon: "none",
							title: "姓名修改失败：" + err.message
						});
						this.userBaseQueryInCertificate();
					},
				});
			},
			modify() {
				if (this.isCertCreate) {
					uni.showToast({
						icon: "none",
						title: "不能再次修改姓名"
					});
					return;
				}
				this.newName = this.nickName;
				this.$refs.modifyDialog.open();			
			},
			modifyDialogConfirm() {
				this.newName = this.newName.trim();
				if (this.newName.length == 0) {
					uni.showToast({
						icon: "none",
						title: "请输入姓名"
					});
					return;
				}
				if (this.newName != this.nickName) {
					this.confirmContent = `姓名：${this.newName}\r\n\r\n只能修改一次，确定要修改吗？`;
					this.$refs.confirmDialog.open();
				} else {
					uni.showToast({
						icon: "none",
						title: "姓名未修改，操作取消"
					});
					return;
				}
			},
			confirmDialogConfirm() {
				this.nickName = this.newName.trim();
				this.certificateCreateByUserAi();
			},
			previewCert() {
				uni.previewImage({
					showmenu: true,
					urls: [this.ecertUrl] // 需要预览的图片 HTTP 链接列表
				});
			},
			downloadCert() {
				let data = {
					name: `${this.compName}_${this.certificateName}_ecert.png`,
					content: this.ecertUrl,
					type: "image"
				};
				data = JSON.stringify(data);
				// console.log(data);
				save_base64.postMessage(data);
				
				/* let filename = `${this.compName}_${this.certificateName}_ecert`;
				// console.log("filename:", filename);
				filename = encodeURIComponent(filename);
				
				let fileurl = this.ecertUrl;
				// console.log("fileurl:", fileurl);
				fileurl = encodeURIComponent(fileurl);
				
				const url = `action://down_pic_base64?filename=${filename}&url=${fileurl}`;
				tools.appAction(url); */
				
				/* uni.downloadFile({
					// url: this.ecertConfig.tplUrl,
					// url: this.$refs.ecertImg.src,
					url: this.ecertUrl,
					success: function(downloadResult) {
						if (downloadResult.statusCode === 200) {
							// 下载成功后，尝试保存图片到本地相册
							uni.saveImageToPhotosAlbum({
								filePath: downloadResult.tempFilePath,
								success: function() {
									console.log('图片保存成功');
									uni.showToast({
										icon: "none",
										title: "图片保存成功",
										duration: 2000
									});
								},
								fail: function(err) {
									console.log('保存图片失败', err);
									uni.showToast({
										icon: "none",
										title: "保存图片失败：" + err.errMsg,
										duration: 5000
									});
								}
							});
						}
					},
					fail: function(err) {
						console.log('下载图片失败', err);
						uni.showToast({
							icon: "none",
							title: "下载图片失败：" + err.errMsg,
							duration: 5000
						});
					}
				}); */
			},
			shareWx() {
				let data = {
					title: "彩图奔跑商家版",
					url: "https://oss-mbh5.colormaprun.com/shop/",
					image: "https://oss-mbh5.colormaprun.com/shop/static/logo.png",
					scene: "session" // session:分享到对话  timeline:分享到朋友圈  favorite:分享到收藏
				};
				data = JSON.stringify(data);
				// console.log(data);
				share_wx.postMessage(data);
			},
			btnCert() {
				this.makeCert();
			},
			btnBack() {
				window.history.back();
				/* const url = `action://to_home/`;
				tools.appAction(url); */
			},
			test() {
				// var ctx = uni.createCanvasContext('firstCanvas')
				var ctx = uni.createCanvasContext('ecert')
				// ctx.scale(this.dpr, this.dpr);
				ctx.setStrokeStyle("#00ff00")
				ctx.setLineWidth(5)
				ctx.rect(0, 0, 200, 200)
				ctx.stroke()

				ctx.setStrokeStyle("red");
				// ctx.setLineWidth(5);
				ctx.moveTo(150, 20);
				ctx.lineTo(150, 170);
				ctx.stroke();

				ctx.setFontSize(15);
				ctx.setTextAlign('left');
				ctx.fillText('textAlign=left', 150, 60);

				ctx.setTextAlign('center');
				ctx.fillText('textAlign=center', 150, 80);

				ctx.setTextAlign('right');
				ctx.fillText('textAlign=right', 150, 100);

				ctx.draw()
			},
		}
	}
</script>

<style scoped>
	.main {
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		text-align: center;
	}

	.mytopbar {
		padding-top: 40px;
		padding-bottom: 20px;
		margin-left: auto;
		margin-right: auto;
	}

	/* .title {
		display: block;
		margin-top: 35px;
		margin-bottom: 15px;
		font-size: 22px;
		font-weight: 550;
		color: #333333;
	} */

	.loading-animation {
		margin: 200px auto;
		border: 6px solid #f3f3f3;
		border-top: 6px solid #3498db;
		border-radius: 50%;
		width: 50px;
		height: 50px;
		animation: spin 1s linear infinite;
	}
	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}
	
	.ecertImg {
		margin-top: 6px;
		margin-bottom: 20px;
		border: #bfbfbf solid 1px;
		box-shadow: 3px 3px 8px #b9b9b9;
		/* -webkit-touch-callout: default; */
	}
	
	.btnlist {
		width: 80%;
		/* height: 30px; */
		margin: 0px auto;
		/* background-color: #3498db; */
	}
	
	.btnlist-item {
		font-size: 14px;
		font-weight: 500;
		color: #383838;
		text-decoration: underline;
	}

	.ecert {
		visibility: hidden;
		/* width: 100vw;
		height: 100vh; */
		/* transform: scale(0.5); */
	}
	
	.dialogView {
		width: 90%;
	}
	
	.dialogView-memo {
		font-size: 12px;
		font-weight: 400;
		color: #808080;
	}
	
	.uni-input {
		width: 100%;
		height: 34px;
		margin-bottom: 10px;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		font-size: 14px;
	}
	
	::v-deep #u-a-p > div {
		top: 30px !important;
	}

	/* .info {
		max-width: fit-content;
		margin-left: auto;
		margin-right: auto;
		margin-top: 30px;
	}

	.info-text {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
		line-height: 30px;
	}

	.info-memo {
		font-size: 12px;
		font-weight: 400;
		color: #808080;
		line-height: 25px;
	}

	.btnCert {
		width: 289px;
		height: 53px;
		margin-top: 30px;
		margin-bottom: 20px;
		border-radius: 27px;
		background: #a43a07;
		color: #ffffff;
		line-height: 53px;
	} */

	/* .movable-area {
		width: 100vw;
		height: 80vh;
		background-color: #ddd;
		overflow: hidden;
		align-items: center;
	}

	.movable-view {
		width: 100%;
		height: 50%;
		transform: scale(0.1) !important;
	} */
</style>