<template>
	<view class="content">
		<view class="bg" >
			<image  :src="cardInfo.avatar" mode="aspectFit"></images>
		</view>
		<view>
			<view class="info">
				<!-- <view class="logo"><image :src="cardInfo.avatar ? cardInfo.avatar : '../../static/images/qy_logo.jpg'" mode="aspectFit"></image></view> -->
				<view class="brief" v-if="cardInfo.msg">
					<image src="../static/images/yin_l.png" class="yin-l"></image>
					{{ cardInfo.msg }}
					<image src="../static/images/yin_r.png" class="yin-r"></image>
				</view>
				<!-- codUrl -->
				<view class="code"><image :src="codUrl"></image></view>
				<view class="infos">
					<view class="name">{{ cardInfo.realName }}</view>
					<view class="company">{{ cardInfo.companyName }}</view>
					<view class="industry">{{ cardInfo.job }}</view>
				</view>
				<!-- <view class="qy-logo ddflex"><image src="../../static/images/logo.png"></image></view> -->
			</view>
			<view class="opt dflex">
				<!-- @click="downloadImg(codUrl)" -->
				<!-- <button class="li" hover-class="none" open-type="share">
					<image src="../static/images/hb_ico1.png"></image>
					<view>分享到微信</view>
				</button> -->
				<view class="li" @click="downloadImg(codUrl)">
					<image src="../static/images/hb_ico1.png"></image>
					<view>下载名片码</view>
				</view>
				
				<view class="li" @click="generatePoster()">
					<image src="../static/images/hb_ico2.png"></image>
					<view>保存图片</view>
				</view>
			</view>
			<canvas class="canvas" style="width:590px;height:736px;" canvas-id="share"></canvas>
		</view>
	</view>
</template>

<script>
const app = getApp();
const req = require('../../utils/request.js');
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
export default {
	data() {
		return {
			id: '',
			cardInfo: '',
			codUrl: 'https://img.zhiqiyun.com/zqy3t9kp2zc5i/2023/03/20/be0cfb643cd38b97d5a7b14eecaaa8a1.png',
			isShowLoading: false
		};
	},

	onLoad(opt) {
		this.id = opt.id;
		this.getCardInfo();
	},
	onShareAppMessage(res) {
		if (res.from == 'button') {
			let userInfo = req.getStorage('userInfo');
			this.userBehavior(6)
			return {
				title: this.cardInfo.realName,
				path: '/card/index/index?cardId=' + this.cardInfo.id + '&userId=' + userInfo.id+ '&appId=' + req.getStorage('appId'),
				imageUrl: this.cardInfo.avatar + '?x-oss-process=style/w375', // 分享图
			};
		}
	},
	
	
	
	methods: {
		removeHtml(content){
			return util.removeHtml(content);
		},
		
		appToShare() {
			let userInfo = req.getStorage('userInfo');
			uni.share({
				provider: 'weixin',
				scene: 'WXSceneSession',
				type: 5,
				imageUrl: this.cardInfo.avatar + '?x-oss-process=style/w375',
				title: this.cardInfo.realName,
				summary: this.cardInfo.realName,
				miniProgram: {
					id: req.public.miniProgramGh_id,
					path: '/card/index/index?cardId=' + this.cardInfo.id + '&userId=' + userInfo.id,
					type: req.env[req.env.NODE_ENV].typeMiniProgram,
					webUrl: req.public.homeWebUrl
				},
				success: ret => {
					this.userBehavior(6)
				}
			});
		},
		getCardInfo() {
			let dataP = {}
			let url = ''
			if (this.id) {
				url = api.card_info;
				dataP.id = this.id;
			} else {
				url = api.card_userInfo;
				dataP = {};
			}
			req.getRequest(url, dataP, data => {
				this.cardInfo = data;
				this.getCodeUrl()
			});
		},
		
		// 用户行为
		userBehavior(type){
			var dataP = {};
			dataP.type = 23 //、产品 2、活动 3、未知 4、内容 5、课程 6、老师 7、素材 8、题目 9、资料领取 10、招聘职位 12、用户须知 13、素材 15、医院科室 16、海报 20、医生 21 新闻 23名片
			dataP.behavior = type; //1、关注 2、收藏 3、点赞 4、浏览 5、确认 6、分享
			dataP.bindId = this.cardInfo.id;
			req.postRequestLoding('/api/v3/behavior/save', dataP, data => {
			});
		},
		
		getCodeUrl() {
			let that = this; //获取小程序码
			const params = {
				page: 'card/index/index',
				scene: this.cardInfo.id
			};
			return new Promise((resolve, reject) => {
				req.getRequest('/api/program/codev', params, url => {
					// console.log(url);
					this.codUrl = url
					resolve();
				});
			});
		},

		generatePoster() {
			let that = this;
			if (!that.isShowLoading) {
				uni.showLoading({
					title: '生成中',
					mask: true
				});
				that.isShowLoading = true;
			}
			this.generate(imgUrl => {
				console.log(imgUrl)
				if (that.isShowLoading) {
					uni.hideLoading();
					that.isShowLoading = false;
					that.saveImage(imgUrl);
				}
			});
		},

		generate(success) {
			let that = this;
			let logoPromise = this.getImageInfo(this.cardInfo.imageMap?this.cardInfo.imageMap:this.cardInfo.avatar);
			let codePromise = this.getImageInfo(this.codUrl);
			Promise.all([logoPromise, codePromise]).then(([logo, code]) => {
				const ctx = uni.createCanvasContext('share', this); // 绘制背景，填充满整个canvas画布
				let width = 590;
				let height = 736;
				// ctx.setFillStyle('#fff');
				ctx.fillRect(0, 0, width, height);
				ctx.drawImage('../static/images/poster_bg.png',0, 0, width, height);
				
				
				// 简介
				ctx.fillStyle = '#fff';
				ctx.font = '30px PingFang SC';
				// let text = '“'+that.removeHtml(that.cardInfo.brief)+'”';
				let text = '“'+that.cardInfo.msg+'”';
				var textWidth = ctx.measureText(text).width;
				var xPosition = width / 2 - textWidth / 2;
				ctx.fillText(text,xPosition,70);
				ctx.save();

				// 姓名
				ctx.fillStyle = '#fff';
				ctx.font = '32px PingFang SC';
				ctx.fillText(that.cardInfo.realName, (width - 324) / 2 , 490);
				ctx.save();

				ctx.fillStyle = '#fff';
				ctx.font = '20px PingFang SC';
				ctx.fillText(that.cardInfo.companyName, (width - 324) / 2, 530);
				ctx.save();
				
				ctx.fillStyle = '#fff';
				ctx.font = '20px PingFang SC';
				ctx.fillText(that.cardInfo.job, (width - 324) / 2, 570);
				ctx.save();
				
				this.roundRect(ctx,(width - 324) / 2, 100,324, 324,16)
				
				// 小程序码
				ctx.drawImage(code.path, (width - 304) / 2, 110, 304, 304);
				ctx.save();
				

				// 完成作画
				ctx.draw(false, function() {
					uni.canvasToTempFilePath(
						{
							canvasId: 'share',
							success: function(res) {
								success.call(this, res.tempFilePath);
							},
							fail: function(res) {}
						},
						that
					);
				});
			});
		},

		getImageInfo(url) {
			if (url) {
				return new Promise((resolve, reject) => {
					if (!url) {
						resolve();
						return '';
					}
					uni.getImageInfo({
						src: url,
						success: resolve,
						fail: reject
					});
				});
			} else {
				return '';
			}
		},
		/**
		 *
		 * @param {CanvasContext} ctx canvas上下文
		 * @param {number} x 圆角矩形选区的左上角 x坐标
		 * @param {number} y 圆角矩形选区的左上角 y坐标
		 * @param {number} w 圆角矩形选区的宽度
		 * @param {number} h 圆角矩形选区的高度
		 * @param {number} r 圆角的半径
		 */
		roundRect: function(ctx, x, y, w, h, r) {
			// 开始绘制
			ctx.beginPath(); // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
			// 这里是使用 fill 还是 stroke都可以，二选一即可
			ctx.setFillStyle('#fff'); // ctx.setStrokeStyle('transparent')
			// 左上角
			ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); // border-top
			ctx.moveTo(x + r, y);
			ctx.lineTo(x + w - r, y);
			ctx.lineTo(x + w, y + r); // 右上角
			ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2); // border-right
			ctx.lineTo(x + w, y + h - r);
			ctx.lineTo(x + w - r, y + h); // 右下角
			ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5); // border-bottom
			ctx.lineTo(x + r, y + h);
			ctx.lineTo(x, y + h - r); // 左下角
			ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI); // border-left
			ctx.lineTo(x, y + r);
			ctx.lineTo(x + r, y); // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
			ctx.fill(); // ctx.stroke()
			ctx.closePath(); // 剪切
			ctx.clip();
		},
		
		borderRect(ctx, x, y, w, h, r, fillColor, strokeColor) {
		    // 画圆角 ctx、x起点、y起点、w宽度、y高度、r圆角半径、fillColor填充颜色、strokeColor边框颜色
		    // 开始绘制
		    ctx.beginPath()
		 
		    // 绘制左上角圆弧 Math.PI = 180度
		    // 圆心x起点、圆心y起点、半径、以3点钟方向顺时针旋转后确认的起始弧度、以3点钟方向顺时针旋转后确认的终止弧度
		    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
		 
		    // 绘制border-top
		    // 移动起点位置 x终点、y终点
		    ctx.moveTo(x + r, y)
		    // 画一条线 x终点、y终点
		    ctx.lineTo(x + w - r, y)
		    // ctx.lineTo(x + w, y + r)
		 
		    // 绘制右上角圆弧
		    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
		 
		    // 绘制border-right
		    ctx.lineTo(x + w, y + h - r)
		    // ctx.lineTo(x + w - r, y + h)
		 
		    // 绘制右下角圆弧
		    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
		 
		    // 绘制border-bottom
		    ctx.lineTo(x + r, y + h)
		    // ctx.lineTo(x, y + h - r)
		 
		    // 绘制左下角圆弧
		    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
		 
		    // 绘制border-left
		    ctx.lineTo(x, y + r)
		    // ctx.lineTo(x + r, y)
		 
		    if (fillColor) {
		      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
		      ctx.setFillStyle(fillColor)
		      // 对绘画区域填充
		      ctx.fill()
		    }
		 
		    if (strokeColor) {
		      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
		      ctx.setStrokeStyle(strokeColor)
		      // 画出当前路径的边框
		      ctx.stroke()
		    }
		    // 关闭一个路径
		    // ctx.closePath()
		 
		    // 剪切，剪切之后的绘画绘制剪切区域内进行，需要save与restore
		    ctx.clip()
		  },

		/**
		 * 下载图片
		 * @param {Object} url
		 */
		downloadImg(url) {
			let that = this;
			uni.getImageInfo({
				src: url,
				success(res) {
					console.log('res==',res)
					that.saveImage(res.path);
				}
			})
			// that.saveImage(url);
		},
		isAuth(fun) {
			if (!uni.saveImageToPhotosAlbum) {
				uni.showModal({
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
				});
				return;
			}
		
			; //可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope  
			// #ifndef H5
			uni.getSetting({
				success(res) {
					// console.log(res);
		
					if (!res.authSetting['scope.writePhotosAlbum']) {
						// 接口调用询问  
						uni.authorize({
							scope: 'scope.writePhotosAlbum',
		
							success() {
								// console.log("2-授权《保存图片》权限成功");
								fun(true);
							},
		
							fail() {
								fun(false);
							}
		
						});
					} else {
						// 拒绝授权
						fun(true);
					}
				},
		
				fail(res) {
					fun(false);
				}
		
			});
			// #endif
		},
		/**
		 * 保存图片
		 * @param {Object} tempFilePath
		 */
		saveImage(tempFilePath) {
			let that = this;
			that.isAuth(success => {
				if (success) {
					uni.saveImageToPhotosAlbum({
						filePath: tempFilePath,
		
						success(res) {
							that.saveShareBehavior();
							uni.showToast({
								title: '图片保存成功',
								icon: 'none',
		
								success() { // that.generate(imgUrl => {
									//   that.setData({
									//     imgUrl: imgUrl
									//   })
									// })
								},
		
								fail() {
									uni.showToast({
										title: '图片保存失败'
									});
								}
		
							});
						}
		
					});
				}
			});
		},
		saveShareBehavior(){
			let params = {
				behavior: 6,
				type: 23,
				bindId: this.cardInfo.id
			}
			req.saveBehavior(params,res=>{})
		},
		// saveImage(tempFilePath) {
		// 	util.saveImage(tempFilePath);
		// }
	}
};
</script>

<style>
@import './poster.css';
</style>
