<template>
	<view>
		<view class="wanl-poster" @tap="close" :style="{paddingTop: topNum + 'px'}">
			<canvas v-if="!tempFilePath" :canvas-id="canvasID" class="wanl-poster__canvas"
				:style="{ width: canvasW + 'px', height: canvasH + 'px'}" />
			<view v-else class="wanl-poster__main">
				<view @tap.stop="">
					<image lazy-load class="image" :src="tempFilePath" mode="widthFix" @longpress="toSave(tempFilePath)"/>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var that;
	import {mapState} from 'vuex';
	export default {
		name: 'wanl-poster',
		props: {
			canvasID: {
				Type: String,
				default: 'PosterCanvas'
			},
			img: {
				Type: String,
				default: ''
			},
			price: {
				Type: String,
				default: ''
			},
			marketPrice: {
				Type: String,
				default: ''
			},
			title: {
				Type: String,
				default: '勉学优品'
			},
			page: {
				Type: String,
				default: ''
			},
			scene: {
				type: Object,
				default () {
					return {}
				}
			}
		},
		data() {
			return {
				config: {},
				loading: false,
				lineType: true,
				mpQrcodeUrl: '',
				tempFilePath: '',
				canvasW: 0,
				canvasH: 0,
				ctx: null,
				topNum: 0
			};
		},
		computed: {
			...mapState(['user', 'common'])
		},
		created() {
			uni.showLoading({
				title: '海报生成中...'
			});
			that = this;
			that.OnCanvas();
		},
		methods: {
			async OnCanvas() {
				that.loading = true;
				that.ctx = uni.createCanvasContext(that.canvasID, this);
				let imgurl = 'https://admin.dbcdq.cn/assets/img/icon/bg3.png'
				// let imgurl = 'https://admin.dbcdq.cn/assets/img/icon/bg2.png'
				//网络主图
				let _imgInfo = await that.getImageInfo({
					img: imgurl
				});
				that.canvasW = (uni.getSystemInfoSync().windowWidth/750)*520
				that.canvasH = (uni.getSystemInfoSync().windowWidth/750)*764
				that.topNum = 40
				//canvas背景颜色
				that.ctx.setFillStyle('#fff');
				//canvas画布大小
				that.ctx.fillRect(0, 0, that.canvasW, that.canvasH);
				//添加图片展示
				that.ctx.drawImage(_imgInfo.path, 0, 0, that.canvasW, that.canvasH);

				let _qrcodeImg = await that.getImageInfo({img: 'https://admin.dbcdq.cn/assets/img/icon/qrcodebg.png'});

				this.$api.qrcode({},res=>{
					if(res.code == '1'){
						
					}
				})
				that.ctx.drawImage(_imgInfo.path, that.canvasW - 80, that.canvasH - 80, 50,50);
				//延迟后渲染至canvas上
				setTimeout(function() {
					console.log('14')
					that.ctx.draw(true, ret => {
						uni.hideLoading();
						console.log('16')
						that.getNewImage();
						console.log('17')
					});
					console.log('15')
				}, 500);
			},
			async OnCanvas2() {
				console.log('1',uni.getSystemInfoSync().windowHeight)
				// that.common.appConfig.poster_env = 'develop'	//设置成跳转开发版小程序
				that.loading = true;
				that.ctx = uni.createCanvasContext(that.canvasID, this);
				console.log('2--',that.common,that.common.appConfig.poster_width)
				that.common.appConfig.poster_width = (uni.getSystemInfoSync().windowWidth/750)*520//500
				const canvasWidth = uni.upx2px(that.common.appConfig.poster_width - 0),	//设置海报宽度
					//canvas Paddng 间距
					margin = uni.upx2px(0),
					//二维码或太阳码宽高
					qrcodeWidth = uni.upx2px(150);
					console.log('2',that.common.appConfig.poster_width)
				//文本宽度
				let _strlineW = 0;
				console.log('3')
				let imgurl = 'https://admin.dbcdq.cn/assets/img/icon/bg3.png'
				// let imgurl = 'https://admin.dbcdq.cn/assets/img/icon/bg2.png'
				//网络主图
				let _imgInfo = await that.getImageInfo({
					// img: that.img ? that.$wanlshop.oss(that.img, 400, 0) : that.$wanlshop.oss(that.common.appConfig.poster_image, 400, 0)
					img: imgurl//that.img ? that.common.uploaddata.cdnurl+that.img : that.common.uploaddata.cdnurl+that.common.appConfig.poster_image
				});
				console.log('4')
				let r = [_imgInfo.width, _imgInfo.height];
				let imgW = canvasWidth - margin * 2;
				if (r[0] != imgW) {
					r[1] = Math.floor((imgW / r[0]) * r[1]);
					r[0] = imgW;
				}
				that.canvasW = (uni.getSystemInfoSync().windowWidth/750)*520//canvasWidth;
				console.log('2')
				// 是否存在价格行
				// #ifdef MP
				if (that.price != '') {
					that.canvasH = r[1] + qrcodeWidth + 120;
				} else {
					that.canvasH = r[1] + qrcodeWidth + 85;
				}
				// #endif
				// #ifndef MP
				if (that.price != '') {
					that.canvasH = r[1] + qrcodeWidth + 114;
				} else {
					that.canvasH = r[1] + qrcodeWidth + 80;
				}
				that.canvasH = (uni.getSystemInfoSync().windowWidth/750)*764
				let h = (uni.getSystemInfoSync().windowWidth/750)*764
				let w = (uni.getSystemInfoSync().windowWidth/750)*520
				// #endif
				console.log('5',(uni.getSystemInfoSync().windowHeight/750)*764)
				that.topNum = 40//uni.getSystemInfoSync().windowHeight/2 - that.canvasH/2
				//canvas背景颜色
				// that.ctx.setFillStyle(that.common.appConfig.poster_background);
				that.ctx.setFillStyle('#fff');
				//canvas画布大小
				that.ctx.fillRect(0, 0, that.canvasW, that.canvasH);

					
				//添加图片展示
				that.ctx.drawImage(_imgInfo.path, margin, margin, that.canvasW, that.canvasH);
				//添加图片展示 end
console.log('6',margin,r,canvasWidth)

				//设置文本
				that.ctx.setFontSize(uni.upx2px(32)); //设置标题字体大小
				that.ctx.setFillStyle(that.common.appConfig.poster_title_color); //设置标题文本颜色
				let _strLastIndex = 0; //每次开始截取的字符串的索引
				let _strHeight = r[1] + margin * 2 + 15; //绘制字体距离canvas顶部的初始高度
				let _num = 1;
				console.log('7')
				let title = ['ddd','fff']//that.title ? that.title : that.common.appConfig.poster_title;
				// for (let i = 0; i < title.length-1; i++) {console.log('2')
				// 	_strlineW += that.ctx.measureText(title[i]).width;
				// 	if (_strlineW > r[0]) {
				// 		if (_num == 2 && that.lineType) {
				// 			//文字换行数量大于二进行省略号处理
				// 			that.ctx.fillText(title.substring(_strLastIndex, i - 2) + '...', margin, _strHeight);
				// 			_strlineW = 0;
				// 			_strLastIndex = i;
				// 			_num++;
				// 			break;
				// 		} else {
				// 			that.ctx.fillText(title.substring(_strLastIndex, i), margin, _strHeight);
				// 			_strlineW = 0;
				// 			_strHeight += 20;
				// 			_strLastIndex = i;
				// 			_num++;
				// 		}
				// 	} else if (i == title.length - 1) {
				// 		that.ctx.fillText(title.substring(_strLastIndex, i + 1), margin, _strHeight);
				// 		_strlineW = 0;
				// 	}
				// }
				//设置文本 end
console.log('7')

				//设置价格
				if (that.price != '') {
					_strlineW = margin;

					_strHeight += uni.upx2px(60);

					if (_num == 1) {
						_strHeight += 20; //单行标题时占位符
					}
					if (that.price != '') {
						//判断是否有销售价格
						that.ctx.setFillStyle(that.common.appConfig.poster_price_color);
						that.ctx.setFontSize(uni.upx2px(38));
						that.ctx.fillText('￥' + that.price, _strlineW, _strHeight); //商品价格
						_strlineW += that.ctx.measureText('￥' + that.price).width + uni.upx2px(10);
					}
					//商品原价
					that.ctx.setFillStyle(that.common.appConfig.poster_original_color);
					that.ctx.setFontSize(uni.upx2px(24));
					that.ctx.fillText(that.marketPrice, _strlineW, _strHeight); 
					// 删除线
					that.ctx.strokeStyle = that.common.appConfig.poster_original_color;
					that.ctx.moveTo(_strlineW, _strHeight - uni.upx2px(10)); //起点
					that.ctx.lineTo(_strlineW + that.ctx.measureText(that.marketPrice).width, _strHeight - uni.upx2px(10)); //终点
					that.ctx.stroke();
				}
				//设置价格 end
				
				
				console.log('1')
				let _qrcodeImg = await that.getImageInfo({img: 'https://admin.dbcdq.cn/assets/img/icon/qrcodebg.png'});
				//添加二维码 drawImage(图片, 左边距, 上边距, 宽度, 高度);
				// let _qrcodeImg = await that.getImageInfo({img: `${that.$wanlshop.config('appurl')}/wanlshop/common/qrcode?width=${qrcodeWidth}&page=${encodeURIComponent(that.page + '?' + that.$wanlshop.parseParams(JSON.parse(JSON.stringify(that.scene).replace('"i"','"id"'))))}`});
				_strHeight += uni.upx2px(20);
				// #ifdef APP || H5 || MP-WEIXIN
				// 微信二维码
				// 展示全部二维码
				console.log('1')
				// if (that.common.appConfig.poster_qrcode == '0') {
				// 	that.ctx.drawImage(_qrcodeImg.path, r[0] - qrcodeWidth + margin, _strHeight, qrcodeWidth,qrcodeWidth);
				// 	let _mpQrcodeImg = await that.getImageInfo({img: `${that.$wanlshop.config('appurl')}/wanlshop/common/mpQrcode?data=${encodeURIComponent(JSON.stringify({
				// 		page:that.page,
				// 		scene: that.scene,
				// 		width: qrcodeWidth,
				// 		env: that.common.appConfig.poster_env
				// 	}))}`});
				// 	that.ctx.drawImage(_mpQrcodeImg.path, r[0] - qrcodeWidth - qrcodeWidth, _strHeight, qrcodeWidth,qrcodeWidth);
				// 	// 展示小程序码
				// } else if (that.common.appConfig.poster_qrcode == '1') {
				// 	let _mpQrcodeImg = await that.getImageInfo({img: `${that.$wanlshop.config('appurl')}/wanlshop/common/mpQrcode?data=${encodeURIComponent(JSON.stringify({
				// 		page:that.page,
				// 		scene: that.scene,
				// 		width: qrcodeWidth,
				// 		env: that.common.appConfig.poster_env
				// 	}))}`});
				// 	that.ctx.drawImage(_mpQrcodeImg.path, r[0] - qrcodeWidth + margin, _strHeight, qrcodeWidth,qrcodeWidth);
				// 	// 展示普通二维码
				// } else if (that.common.appConfig.poster_qrcode == '2') {
				// 	// 生成二维码
				// 	that.ctx.drawImage(_qrcodeImg.path, r[0] - qrcodeWidth + margin, _strHeight, qrcodeWidth,qrcodeWidth);
				// }else{
				// 	let _mpQrcodeImg = await that.getImageInfo({img: `${that.$wanlshop.config('appurl')}/wanlshop/common/mpQrcode?data=${encodeURIComponent(JSON.stringify({
				// 		page:that.page,
				// 		scene: that.scene,
				// 		width: qrcodeWidth,
				// 		env: that.common.appConfig.poster_env
				// 	}))}`});
				// 	that.ctx.drawImage(_mpQrcodeImg.path, r[0] - qrcodeWidth + margin, _strHeight, qrcodeWidth,qrcodeWidth);
				// }
				
				this.$api.qrcode({},res=>{
					if(res.code == '1'){
						
					}else{
						uni.showToast({ title: res.msg , icon: 'none' })
					}
				})
				// #endif
				console.log('12',_qrcodeImg.path)
				that.ctx.drawImage(_imgInfo.path, w - 80, h - 80, 50,50);
				// #ifndef APP || H5 || MP-WEIXIN
				// that.ctx.drawImage(_imgInfo.path, 0, 0, 50,50);
				// 生成二维码
				// that.ctx.drawImage(_qrcodeImg.path, r[0] - qrcodeWidth + margin, _strHeight, qrcodeWidth,qrcodeWidth);
				// #endif
				//添加二维码 end
console.log('12')


				//添加推荐人与描述
				let username = that.user.isLogin ? '@' + that.user.nickname : that.common.appConfig.poster_user;
				// that.ctx.setFillStyle(that.common.appConfig.poster_title_color);
				that.ctx.setFontSize(uni.upx2px(30));
				console.log('13')
				// that.ctx.fillText(username, margin, _strHeight + qrcodeWidth / 2);
				// that.ctx.setFillStyle(that.common.appConfig.poster_original_color);
				console.log('12')
				that.ctx.setFontSize(uni.upx2px(24));
				// that.ctx.fillText(that.common.appConfig.poster_viewDetails, margin, _strHeight + qrcodeWidth / 2 + 20);
				//添加推荐人与描述 end
console.log('13')

				//延迟后渲染至canvas上
				setTimeout(function() {
					console.log('14')
					that.ctx.draw(true, ret => {
						uni.hideLoading();
						console.log('16')
						that.getNewImage();
						console.log('17')
					});
					console.log('15')
				}, 500);
			},
			async getImageInfo({
				img
			}) {
				console.log(img,'----------')
				return new Promise((resolve, errs) => {
					uni.getImageInfo({
						src: img,
						success: function(image) {
							resolve(image);
						},
						fail(err) {
							errs(err);
							uni.showToast({
								title: '海报生成失败',
								mask: false,
								duration: 2000,
								icon: "none"
							});
							uni.hideLoading()
						}
					});
				});
			},
			getNewImage() {
				console.log(that.canvasID,'----------+++')
				uni.canvasToTempFilePath({
						canvasId: that.canvasID,
						quality: 1,
						complete: res => {
							console.log(that.canvasID,res,'ffffff')
							that.tempFilePath = res.tempFilePath;
							that.loading = false;
							that.$emit('success', res);
							uni.hideLoading();
						}
					},
					this
				);
			},
			close() {
				this.$emit('close');
			},
			// 手动保存
			toSave(url) {
				//#ifndef H5
				uni.getImageInfo({
					src: url,
					success: function(image) {
						uni.saveImageToPhotosAlbum({
							filePath: image.path,
							success: function() {
								uni.showToast({
									title: '海报已保存相册',
									icon: 'success',
									duration: 2000
								});
							}
						});
					}
				});
				//#endif
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wanl-poster {
		&__canvas {
			margin: 0 auto;
		}

		&__main {
			position: relative;
			margin: 0 auto;
			width: 75%;
			padding-bottom: 60rpx;

			.image {
				width: 100%;
				border-radius: 20rpx;
				overflow: hidden;
				will-change: transform;
			}

			.close {
				position: absolute;
				top: 6rpx;
				right: 4rpx;

				.wlIcon {
					font-size: 46rpx;
					color: rgba(0, 0, 0, 0.5);
				}
			}
		}

	}
</style>