<template>
	<view>
		<view class="poster" id="poster">
			<image class="poster-pic" :src="posterBg" mode="widthFix"></image>
			<view class="ddflex" style="padding: 22rpx 35rpx;position: relative;">
				<!-- 普通海报 -->
				<view class="flex" v-if="typeCode=='poster'">
					<view class="poster-title">
						{{userInfo.realName?userInfo.realName:(userInfo.nickName?userInfo.nickName:'')}} | 中国人寿股份湖南分公司
					</view>
					<view class="poster-note">长按小程序码了解更多</view>
				</view>
				<!-- 产品宣传 -->
				<view class="flex" v-if="typeCode=='poster_product'">
					<view class="poster-title">{{productTitle?productTitle:'请填写产品链接'}}</view>
					<view class="poster-note">长按二维码了解更多</view>
				</view>
				<!-- 长图海报 -->
				<view class="flex" v-if="typeCode=='poster_long'">
					<view class="poster-title">{{userInfo.realName?userInfo.realName:(userInfo.nickName?userInfo.nickName:'')}}{{userInfo.mobile?' | '+userInfo.mobile:''}}</view>
					<view class="poster-note">扫码即可咨询理赔事宜</view>
				</view>
				
				<image class="poster-code" :src="code?code:'../../static/images/lj_img.png'"></image>
				<view class="change-product ddflex" @click="jumpUrl('/library/productLink/productLink')"
					v-if="typeCode=='poster_product'">
					<image src="/static/images/edit1.png"></image>
					产品链接
				</view>
			</view>
		</view>

		<view style="position: absolute;left: 9999px;top: -9999px;">
			<uqrcode v-if="typeCode=='poster_product'&&productLink" ref="uqrcode" canvas-id="qrcode"
				:value="productLink" :options="{ margin: 10 }" @complete='creatCode'></uqrcode>
		</view>

		<view style="height: 150rpx;"></view>
		<view class="share-btn">
			<view class="btn" @click="generatePoster">立即分享</view>
		</view>



		<canvas v-if="showCanvas" class="canvas" :style="'width:'+cwidth+'px;height:'+cheight+'px;'" canvas-id="share"></canvas>
	</view>
</template>

<script>
	const app = getApp();
	const req = require("../../utils/request.js");
	import utils from '../../utils/util.js'

	export default {
		components: {},
		props: {},
		data() {
			return {
				productTitle: '',
				productLink: '',
				posterBg: '',

				id: null,
				typeCode: '',
				code: '',
				userInfo: '',
				
				imgUrl:'',

				cwidth: 670,
				cheight: 1200,
				showCanvas:true
			}
		},
		watch:{
			productLink:{
				handler(newV,oldV){
					if(this.typeCode=='poster_product'){
						if(newV!=oldV){
							uni.showLoading({
								title:'二维码生成中'
							})
						}
					}
				}
			}
		},
		onLoad(options) {
			this.id = options.id
			this.typeCode = options.code
			this.userInfo = req.getStorage('userInfo')
			this.getPosterDetail()
		},
		onShow() {

		},
		methods: {
			jumpUrl(url) {
				uni.navigateTo({
					url: url
				})
			},
			// 获取海报详情
			getPosterDetail() {
				req.getRequest('/api/material/library/detail', {
					id: this.id
				}, res => {
					this.posterDetail = res
					this.posterBg = this.posterDetail.pic
					if (this.typeCode == 'poster'||this.typeCode=='poster_long') {
						this.getCodeUrl()
					}
				})
			},
			// 获取小程序码
			getCodeUrl() {
				let that = this; //获取小程序码
				let userInfo = req.getStorage('userInfo')
				const params = {
					page: 'pages/index/index',
					params: userInfo.saleNo
				};
				return new Promise((resolve, reject) => {
					req.getRequest('/api/other/program/code', params, url => {
						this.code = url?url:'https://img.zhiqiyun.com/test/2023/08/28/170bb78d3cc86a35842e801aaeee991e.png'
						resolve();
					});
				});
			},
			creatCode() {
				this.$refs.uqrcode.toTempFilePath({
					success: res => {
						this.base64ToTempFilePath(res.tempFilePath.replace('data:image/png;base64,',''), (tempFilePath) => {
							this.code = tempFilePath
							uni.hideLoading()
						})
						// this.code = res.tempFilePath
					}
				});
			},
			// 将base64图片转换为临时地址
			base64ToTempFilePath(base64Data, success, fail) {
				const fs = uni.getFileSystemManager()
				const fileName = 'temp_image_' + Date.now() + '.png' // 自定义文件名，可根据需要修改
				const filePath = uni.env.USER_DATA_PATH + '/' + fileName
				const buffer = uni.base64ToArrayBuffer(base64Data)
				fs.writeFile({
					filePath,
					data: buffer,
					encoding: 'binary',
					success() {
						success && success(filePath)
					},
					fail() {
						fail && fail()
					}
				})
			},

			generatePoster() {
				let that = this;
				if(this.typeCode=='poster_product'){
					if(!this.productTitle||!this.productLink) return req.msg("请先添加产品链接")
				}
				uni.showLoading({
					title: '生成中…',
					mask: true
				});
				this.generate(imgUrl => {
					that.imgUrl = imgUrl;
					uni.hideLoading();
					this.saveImage()
				});
			},

			saveImage() {
				let that = this;
				utils.saveImage(this.imgUrl);
			},

			getImageInfo(url) {
				return new Promise((resolve, reject) => {
					if (!url) {
						resolve();
						return false;
					}
					uni.getImageInfo({
						src: url,
						success: resolve,
						fail: reject
					});
				});
			},

			generate(success) {
				let marginTop = 155;
				const avatarPromise = this.getImageInfo(this.posterBg); // 获取小程序码图
				let codePromise;
				if (!this.code) {
					return req.msg('二维码生成失败');
				} else {
					codePromise = this.getImageInfo(this.code);
				} //获取二维码

				let that = this;
				Promise.all([avatarPromise, codePromise]).then(([avatar, code]) => {
					if(avatar.width>670){
						this.cwidth = avatar.width
						this.cheight = avatar.height+180
					}else{
						let sc = avatar.width/avatar.height
						avatar.width = 670
						avatar.height = 670/sc
						this.cwidth = avatar.width
						this.cheight = avatar.height+180
					}
					this.showCanvas = false
					setTimeout(()=>{
						this.showCanvas = true
						const ctx = uni.createCanvasContext('share', this); // 绘制背景，填充满整个canvas画布
						
						let width = this.cwidth,
							height = this.cheight; //默认背景
						// ctx.setFillStyle('red');
						// ctx.fillRect(0, 0, width, height); // 画布背景
						
						// ctx.save();
						// ctx.beginPath();
						that.roundRect(ctx, 0, 0, width, height, 30);
						
						ctx.save();
						ctx.drawImage(avatar.path, 0, 0, width, avatar.height)
						
						
						// ctx.restore();
						let nickName = ''
						if(this.typeCode=='poster'){
							nickName = this.userInfo.realName?this.userInfo.realName:(this.userInfo.nickName?this.userInfo.nickName:'');
							nickName = nickName+' | 中国人寿股份湖南分公司'
						}else if(this.typeCode=='poster_product'){
							nickName = this.productTitle
						}else if(this.typeCode=='poster_long'){
							nickName = this.userInfo.realName?this.userInfo.realName:(this.userInfo.nickName?this.userInfo.nickName:'');
							nickName = nickName+(this.userInfo.mobile?' | '+this.userInfo.mobile:'')
						}
						
						ctx.fillStyle = '#333333';
						ctx.font = '400 28px PingFang SC';
						ctx.fillText(nickName, 35, avatar.height+80);
						
						let s = this.typeCode=="poster_product"?'长按二维码了解更多':'长按小程序码了解更多'
						ctx.fillStyle = '#999999';
						ctx.font = '26px PingFang SC';
						ctx.fillText(s, 35, avatar.height+130);
						
						ctx.drawImage(code.path, width-126-35, avatar.height+30, 126,
							126)
						
						ctx.draw(false, function() {
							uni.canvasToTempFilePath({
									canvasId: 'share',
									success: function(res) {
										success.call(this, res.tempFilePath);
									},
									fail: function(res) {
										// console.log(res);
									}
								},
								that
							);
						});
					},500)
				});
			},

			/**
			 *
			 * @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, c) {
				// 开始绘制
				ctx.beginPath(); // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
				// 这里是使用 fill 还是 stroke都可以，二选一即可

				ctx.setFillStyle(c ? c : 'white'); // 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();
			}
		},
		mounted() {},
	}
</script>
<style>
	@import "./posterService.css";
</style>