<template>
	<view class="content">
		<view class="bg" >
			<image  :src="cardInfo.avatar" mode="aspectFit"></images>
		</view>
		<view>
			<view class="info">
				<image style="position: absolute;top: 0;right: 0;left: 0;bottom: 0;width: 100%;height: 100%;" src="../static/images/posterBg.png"></image>
				<view class="logo"><image :src="about.CONFIG_PROJECT_LOGO ? about.CONFIG_PROJECT_LOGO : '../../static/images/qy_logo.jpg'" mode="aspectFill"></image></view>
				<!-- <view class="brief" v-if="cardInfo.message">
					<image src="../static/images/yin_l.png" class="yin-l"></image>
					{{ cardInfo.message }}
					<image src="../static/images/yin_r.png" class="yin-r"></image>
				</view> -->
				<view class="info-title">专业顾问为您提供服务</view>
				<!-- codUrl -->
				<view class="code"><image :src="codUrl"></image></view>
				<view class="infos">
					<view class="name">{{ cardInfo.realName }}<text style="font-size: 24rpx;margin-left: 10rpx;font-weight: 400;">{{ cardInfo.jobName }}</text></view>
					<view class="company">{{ cardInfo.companyName }}</view>
					<view class="industry">入司{{ cardInfo.inDate?monthDayDiff(cardInfo.inDate):'1年'}}</view>
				</view>
			</view>
			<view class="opt dflex">
				<!-- @click="downloadImg(codUrl)" -->
				<!-- #ifdef MP-WEIXIN -->
				<button class="li" hover-class="none" open-type="share">
					<image src="../static/images/hb_ico1.png"></image>
					<view>分享到微信</view>
				</button>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<view class="li" @click="appToShare" >
					<image src="../static/images/hb_ico1.png"></image>
					<view>分享到微信</view>
				</view>
				<!-- #endif -->
				
				<view class="li" @click="generatePoster()">
					<image src="../static/images/hb_ico2.png"></image>
					<view>保存图片</view>
				</view>
			</view>
			<canvas class="canvas" style="width:590px;height:920px;" 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: '',
			isShowLoading: false,
			about:{}
		};
	},

	onLoad(opt) {
		this.id = opt.id;
		this.getCardInfo();
		this.getConfig()
	},
	onShareAppMessage(res) {
		if (res.from == 'button') {
			let userInfo = req.getStorage('userInfo');
			this.userBehavior(6)
			req.saveBehaviorNew(this.cardInfo.id,1,6)
			return {
				title: this.cardInfo.realName,
				path: '/card/index/index?cardId=' + this.cardInfo.id + '&userId=' + userInfo.id + (this.cardInfo.jobNumber?('&shareId=' + this.cardInfo.jobNumber):''),
				imageUrl: this.cardInfo.avatar, // 分享图
			};
		}else{
			let userInfo = req.getStorage('userInfo');
			this.userBehavior(6)
			req.saveBehaviorNew(this.cardInfo.id,1,6)
			return {
				title: this.cardInfo.realName,
				path: '/card/index/index?cardId=' + this.cardInfo.id + '&userId=' + userInfo.id + (this.cardInfo.jobNumber?('&shareId=' + this.cardInfo.jobNumber):''),
				imageUrl: this.cardInfo.avatar, // 分享图
			};
		}
	},
	onShareTimeline(res) {
		if (res.from == 'button') {
			let userInfo = req.getStorage('userInfo');
			this.userBehavior(6)
			req.saveBehaviorNew(this.cardInfo.id,1,6)
			return {
				title: this.cardInfo.realName,
				path: '/card/index/index?cardId=' + this.cardInfo.id + '&userId=' + userInfo.id + (this.cardInfo.jobNumber?('&shareId=' + this.cardInfo.jobNumber):''),
				imageUrl: this.cardInfo.avatar, // 分享图
			};
		}else{
			let userInfo = req.getStorage('userInfo');
			this.userBehavior(6)
			req.saveBehaviorNew(this.cardInfo.id,1,6)
			return {
				title: this.cardInfo.realName,
				path: '/card/index/index?cardId=' + this.cardInfo.id + '&userId=' + userInfo.id + (this.cardInfo.jobNumber?('&shareId=' + this.cardInfo.jobNumber):''),
				imageUrl: this.cardInfo.avatar, // 分享图
			};
		}
	},
	methods: {
		getConfig() {
			var _this = this;
			return new Promise((res, rej) => {
				req.g(
					'/api/other/config',
					data => {
						req.setStorage('configRes', JSON.stringify(data));
						this.about = data;
						res(data);
					},
					true
				);
			});
		},
		appToShare() {
			let userInfo = req.getStorage('userInfo');
			uni.share({
				provider: 'weixin',
				scene: 'WXSceneSession',
				type: 5,
				imageUrl: this.cardInfo.avatar,
				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/visiting/card/info';
				dataP.id = this.id;
			} else {
				url = '/api/visiting/card/userInfo';
				dataP = {};
			}
			req.getRequest(url, dataP, data => {
				this.cardInfo = data;
				this.getCodeUrl()
				// this.generatePoster()
			});
		},
		
		// 用户行为
		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',
					params: this.cardInfo.id+'_'+this.cardInfo.jobNumber
				};
				return new Promise((resolve, reject) => {
					req.getRequest('/api/other/program/code', 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 projectPromise = this.getImageInfo(this.about.CONFIG_PROJECT_LOGO);
			let logoPromise = this.getImageInfo(this.cardInfo.avatar);
			let codePromise = this.getImageInfo(this.codUrl);
			Promise.all([projectPromise, logoPromise, codePromise]).then(([project,logo, code]) => {
				const ctx = uni.createCanvasContext('share', this); // 绘制背景，填充满整个canvas画布
				let width = 590;
				let height = 920;
				ctx.setFillStyle('#FFF');
				ctx.fillRect(0, 0, width, height);
				this.roundRect(ctx,0,0,width, height,16)
				ctx.drawImage('../static/images/posterBg.png', 0, 0, width, height);
				ctx.save();
				
				// ctx.fillRect(0, 0, 130, 130);
				this.roundRect(ctx,(width - 130) / 2, 60,130, 130,65)
				ctx.drawImage(project.path, (width - 130) / 2, 60, 130, 130);
				ctx.restore()
				ctx.save();
				

				let text = '专业顾问为您提供服务'
				ctx.fillStyle = '#fff';
				ctx.font = '38px PingFang SC';
				ctx.fillText(text, width/2-ctx.measureText(text).width/2 , 285);
				ctx.save();
					
				// 小程序码
				this.roundRect(ctx,(width - 340) / 2, 340,340, 340,16)
				ctx.drawImage(code.path, (width - 340) / 2+30, 340+30, 290, 290);
				ctx.restore()
				ctx.save();
				
				// 姓名
				ctx.fillStyle = '#fff';
				ctx.font = '38px PingFang SC';
				let rnl = ctx.measureText(that.cardInfo.realName).width
				ctx.fillText(that.cardInfo.realName, 120 , 745);
				ctx.save();
				
				ctx.fillStyle = '#fff';
				ctx.font = '24px PingFang SC';
				ctx.fillText(that.cardInfo.jobName, 120+rnl+10 , 745);
				ctx.save();

				ctx.fillStyle = '#fff';
				ctx.font = '28px PingFang SC';
				ctx.fillText(that.cardInfo.companyName, 120, 790);
				ctx.save();
				
				// 边框文本
				ctx.setFontSize(20);
				ctx.setFillStyle('#ffffff');
				ctx.setTextAlign('left');
				var discountText = '入司'+(that.cardInfo.inDate?that.monthDayDiff(that.cardInfo.inDate):'1年')
				var bdColor = '#fff';
				var bdBackground = 'transparent';
				var bdRadius = 5;
				var textPadding = 12;
				var boxHeight = 38;
				var boxWidth = ctx.measureText(discountText).width + textPadding * 2;
				ctx.fillText(discountText, 120+textPadding, 835);
				that.borderRect(ctx, 120,835-26, boxWidth, boxHeight, bdRadius, bdBackground, bdColor)

				// 完成作画
				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 '';
			}
		},
		monthDayDiff(date){
			return util.monthDayDiff(date)
		},
		/**
		 *
		 * @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;
			console.log('下载图片>>>>>>',url);
			uni.downloadFile({
				url: url, //仅为示例，并非真实的资源
				success: res => {
					that.saveImage(res.tempFilePath);
				}
			});
		},
		/**
		 * 保存图片
		 * @param {Object} tempFilePath
		 */
		saveImage(tempFilePath) {
			util.saveImage(tempFilePath);
			req.saveBehaviorNew(this.cardInfo.id,1,6)
		}
	}
};
</script>

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