<template>
	<view class="page1">
		<view class="type-popup" style="margin-bottom: 0;border-radius: 0;padding: 15rpx;">
			<view style="height: 80rpx;font-size: 36rpx;font-weight: bold;line-height: 80rpx;text-align: center;">
				<uni-easyinput v-model="printName" placeholder="请输入模板名称"></uni-easyinput>
			</view>
			<view  v-for="(item,index) in shippList" :key="index" style="display: flex;flex-direction: column;margin-top: 20rpx;background: #fff;border-radius: 10px;padding: 20rpx;">
				<view style='display: flex;'>
					<view style="color: #333;width: 40%;">
						<uni-easyinput trim='none' v-model="item.name" placeholder="请输入标签名称"></uni-easyinput>
					</view>
					<view style="height: 60rpx;width: 5%;text-align: center;line-height: 60rpx;">:</view>
					<view style="color: #333;width: 50%;margin: 0 auto 20rpx;">
						<uni-easyinput v-model="item.value" placeholder="请输入标签值"></uni-easyinput>
					</view>
					<view @tap="delItem(index)" style="width:12%;margin-left: 20rpx;margin-top: 10rpx;">
						<uni-icons color="red" type="minus" size="26"></uni-icons>
					</view>
				</view>
				<view style="display: flex;">
					<view @tap="addIcon(index,'left')" style="margin-top: 10rpx;width: 30%;height: 60rpx;line-height: 60rpx;background: #088FEB;text-align: center;color: #fff;border-radius: 5px;">
						左侧添加图标
					</view>
					<view @longpress="delIcon(index,index1,'left')" v-for="(item1,index1) in item.leftIcon" :key="index1">
						<img :src="item1" alt="" style="width: 60rpx;height: 60rpx;margin:10rpx 0 0 10rpx;"/>
					</view>
				</view>
				<view style="display: flex;">
					<view @tap="addIcon(index,'right')" style="margin-top: 10rpx;width: 30%;height: 60rpx;line-height: 60rpx;background: #088FEB;text-align: center;color: #fff;border-radius: 5px;">
						右侧添加图标
					</view>
					<view @longpress="delIcon(index,index1,'right')" v-for="(item1,index1) in item.rightIcon" :key="index1" style="">
						<img :src="item1" alt=""  style="width: 60rpx;height: 60rpx;margin:10rpx 0 0 10rpx;"/>
					</view>
				</view>
				<view style='display: flex;margin-top: 20rpx;'>
					<radio-group @change="discountChange(index,$event)" style="display: flex;width:41%;">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item1, index1) in items"
							:key="item1.value" style="margin-right:0">
							<view>
								<radio :value="item1.value" :checked="item.modelLeft == item1.value" />
							</view>
							<view style="width: 100rpx;">{{item1.name}}</view>
						</label>
					</radio-group>
					<radio-group @change="discountChange1(index,$event)" style="display: flex;">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item2, index2) in items2"
							:key="item2.value" style="margin-right:0">
							<view>
								<radio :value="item2.value" :checked="item.modelBlod == item2.value" />
							</view>
							<view style="width: 100rpx;">{{item2.name}}</view>
						</label>
					</radio-group>
				</view>
			</view>
			<view @tap="addShippList" style="text-align: right;height: 80rpx;line-height: 80rpx;padding-right: 20rpx;color: #088FEB;font-size: 30rpx;">新增一条</view>
			<uqrcode ref="uqrcode" canvas-id="qrcode"  hide="true" :value="QrUrl">
			</uqrcode>
			<view v-if="shopId == '1810179818189361152' || shopId == '1838094297858183168'" style="background: #fff;height: 100rpx;display: flex;line-height: 100rpx;">
				<input type="text" :value="QrList1.name" maxlength="50" @blur="addItemName" placeholder="输入名称"
					style="width: 30%;display: block;height: 100rpx;text-align: center;font-size: 32rpx;" />
				<input type="text" disabled @tap="scanCodeAdd" :value="QrList1.path" placeholder="点击扫描二维码"
					style="width: 58%;display: block;height: 80rpx;border: 1px solid #eee;padding-left: 20rpx;margin-top: 10rpx;" />
			</view> 
			<view style="display: flex;">
				<view style="width: 150rpx;height: 210rpx;margin: 20rpx;">
					<image :src="QrList1.imgUrl" style="width: 150rpx;height: 150rpx;background-size: 100%;"></image>
					<view v-if="QrList1.imgUrl != ''">{{QrList1.name}}</view>
				</view>
			</view> 
			<view style="width: 100%;height: 160rpx;line-height: 70rpx;text-align: center;border-radius: 0;color: #fff;">
				<view @tap="goAddClass" style="background: linear-gradient(90deg, #60F3FF, #088FEB);height: 70rpx;">确认</view>
				<view @tap="$refs.printPopup.open()" v-if="shopId == '1810179818189361152' || shopId == '1838094297858183168'" style="background: linear-gradient(90deg, #60F3FF, #088FEB);height: 70rpx;margin-top:20rpx;">
					打印
				</view>
			</view>
		</view>
		<!-- 洗涤图标展示框 -->
		<uni-popup ref="showIconPopup" background-color="#fff">
			<view class="popup-pay-content">
				<view class="popup-pay-title">
					<text>选择洗涤图标</text>
					<uni-icons @tap='$refs.showIconPopup.close()' type="closeempty" color='red' size="16"
						style="height:40rpx;line-height: 40rpx;position: absolute !important;bottom:0;right: 30rpx;"></uni-icons>
				</view>
				<view style="height:900rpx;overflow: scroll;">
					<view @tap="checkIcon(item)" v-for="(item,index) in iconList" :key="index" style="display: flex;flex-direction: column;text-align: center;width: 30%;float: left;margin-right: 3%;height: 180rpx;padding-top: 40rpx;">
						<img :src="item.value" alt="" style="width: 60rpx;height: 60rpx;background-size: 100%;margin-top: 20rpx;display: inline-block;margin: 0 auto;"/>
						<text>{{item.text}}</text>
					</view>
				</view>
			</view>
		</uni-popup>
		<!-- 打印数量输入框 -->
		<uni-popup ref="printPopup" background-color="#fff">
			<view class="popup-pay-content" style="width: 600rpx;height: 400rpx;">
				<view class="popup-pay-title">
					<text>请输入打印数量</text>
					<uni-icons @tap='$refs.showIconPopup.close()' type="closeempty" color='red' size="16"
						style="height:40rpx;line-height: 40rpx;position: absolute !important;bottom:0;right: 30rpx;"></uni-icons>
				</view>
				<view style="margin-top: 40rpx;">
					<uni-easyinput type="text" placeholder="请输入打印数量" v-model="number"></uni-easyinput>
					<view class="popup-pay-container">
						<kk-printer ref="kkprinter" :bufferData="bufferData" @onPrint="onPrint1" :printNum="printNum" :defaultText="'打印'"></kk-printer>
					</view>
				</view>
			</view>
		</uni-popup>
		<canvas canvas-id="qrcode1" style="width: 200px;height: 200px;top: -10000px;"></canvas>
	</view>
</template>

<script>
	import {
		washingInstructions,
		generateUUID
	} from '@/utils/global.js'
	import util from '@/components/kk-printer/utils/util.js';
	import * as blesdk from '@/components/kk-printer/utils/bluetoolth.js';
	import kkPrinter from '@/components/kk-printer/index.vue';
	import base from '@/utils/ossUploadFile/base64.js';
	export default {
		data() {
			return {
				QrUrl: '1212', //二维码临时存放
				QrList1: {
					name: '',
					path: '',
					imgUrl:''
				},
				number:'',
				shippList:[],
				bufferData: [],
				categoryId:'',
				printName:'',
				shopId:uni.getStorageSync('shopId'),
				shipId:'',
				discountCurrent:'left',
				items: [{
						value: 'left',
						name: '靠左'
					},
					{
						value: 'right',
						name: '居中'
					}
				],
				discountCurrent2:'blod',
				items2: [{
						value: 'blod',
						name: '加粗'
					},
					{
						value: 'notblod',
						name: '不加粗'
					}
				],
				iconList:[]
			}
		},
		components: {
			kkPrinter
		},
		onLoad(option) {
			this.iconList = washingInstructions()
			if(uni.getStorageSync('qrcode')){
				this.QrList1 = uni.getStorageSync('qrcode')
				uni.removeStorageSync('qrcode')
			}
			if(option){
				let item = JSON.parse(option.item)
				
				this.shipId = item.id
				this.printName = item.printName
				
				this.shippList = item.content
				
				for(let i=0;i<this.shippList.length;i++){
					if(this.shippList[i].leftIcon == undefined){
						this.shippList[i].leftIcon = []
					}
					if(this.shippList[i].rightIcon == undefined){
						this.shippList[i].rightIcon = []
					}
				}
				this.$forceUpdate()
			}
		},
		methods: {
			addItemName(e, index) {
				if(e.detail.value.length>6){
					uni.showToast({
						title: '最多输入6个字符',
						icon: 'none'
					})
					this.QrList1.name = ''
					return
				}
				this.QrList1.name = e.detail.value
			},
			scanCodeAdd(index) {
				let that = this;
				uni.scanCode({
					success: (res) => {
						if (res.result != '') {
							if(res.result.indexOf('u.wechat.com') == -1 && res.result.indexOf('qr.alipay.com') == -1 && res.result.indexOf('wxp://') == -1 && res.result.length > 80){
								let uid = uni.getStorageSync('shopId').substring('10','12') + generateUUID().substring('0','7');
								let urlMapping = []
								urlMapping.push({
									id:uid,
									longUrl:res.result
								})
								that.tui.request("/app/urlMapping/saveOrUpdateUrlMapping", "post",urlMapping, false, false).then((res) => {
									if (res.code == 200) {
										that.QrList1.path = that.tui.interfaceUrl() + '/app/urlMapping/redirect?id='+uid
									}
								})
							}else{
								that.QrList1.path = res.result
							}
							that.QrUrl = that.QrList1.path
							that.canUpdate = false
							that.$forceUpdate()
							setTimeout(res => {
								that.getQRCode(index)
							}, 1000)
							
						} else {
							uni.showToast({
								title: '扫描失败',
								icon: 'none'
							})
						}
					},
					fail: (res) => {
						uni.showToast({
							title: '扫描失败',
							icon: 'none'
						})
					}
				})
			},
			getQRCode(index) {
				let that = this
				setTimeout(res => {
					that.$refs.uqrcode.toTempFilePath({
						success: res => {
							let ctx = uni.createCanvasContext('qrcode1', that)
							ctx.setFillStyle('#fff');
							ctx.fillRect(0, 0, 200, 200);
							let promise = that.getTempFilePath(res.tempFilePath)
							promise.then((result) => {
							  ctx.drawImage(result, 8, 8, 184, 184);
							  ctx.draw(true);
							  setTimeout(ress => {
							  	uni.canvasToTempFilePath({
							  		x: 0,
							  		y: 0,
							  		width: 200, 
							  		height: 200,
							  		destWidth: 200,
							  		destHeight: 200,
							  		canvasId: 'qrcode1',
							  		success: (res3) => {
							  			uni.uploadFile({
							  				url: that.tui.interfaceUrl() + '/upload/file',
							  				filePath: res3.tempFilePath,
							  				name: 'file',
							  				header: {
							  					"content-type": "multipart/form-data",
							  					'accessToken': that.tui.getToken()
							  				},
							  				formData: {},
							  				success: (uploadFileRes) => {
							  					let path = JSON.parse(uploadFileRes.data)
							  					//后端返回的地址，存入图片地址
							  					that.QrList1.imgUrl = path.result
												that.canUpdate = true
							  					that.$forceUpdate()
							  				}
							  			});
							  		}
							  	});
							  }, 500)
							});
						}
					});
				}, 1000)
			},
			getTempFilePath(base64Data) {
				return new Promise((resolve, reject) => {
					const fs = uni.getFileSystemManager()
					base64Data = base64Data.split(',')[1]
					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:res => resolve(filePath),
						fail:err => reject(err)
					})
				});
			},
			delIcon(index,index1,type){
				var that = this;
				uni.showModal({
					title: "提示",
					content: "确定删除此图标吗？",
					success: function(res) {
						if (res.confirm) {
							if(type == 'left'){
								that.shippList[index].leftIcon.splice(index1, 1);
							}else{
								that.shippList[index].rightIcon.splice(index1, 1);
							}
						}
						that.$forceUpdate()
					}
				})
			},
			checkIcon(item){
				if(this.listType == 'left'){
					this.shippList[this.listIndex].leftIcon.push(item.value)
				}else{
					this.shippList[this.listIndex].rightIcon.push(item.value)
				}
				this.$forceUpdate()
				this.$refs.showIconPopup.close()
			},
			addIcon(index,type){
				this.listIndex = index;
				this.listType = type
				this.$refs.showIconPopup.open('bottom')
			},
			delItem(index) {
				let that = this;
				uni.showModal({
					title: "提示",
					content: "确定要删除吗？",
					success: function(res) {
						if (res.confirm) {
							that.shippList.splice(index, 1)
						}
					}
				})
			
			},
			discountChange1(index,e) {
				this.shippList[index].modelBlod = e.detail.value
			},
			discountChange(index,e) {
				this.shippList[index].modelLeft = e.detail.value
			},
			topAddShip(){
				this.printName = ''
				this.shipId = ''
				this.shippList = []
				this.addShippList()
				this.$refs.getaPopup.open()
			},
			addShippList(){
				let data = {
					name:'',
					value:'',
					modelLeft:'left',
					modelBlod:'blod',
					leftIcon:[],
					rightIcon:[]
				}
				this.shippList.push(data)
				this.$forceUpdate()
			},
			goAddClass(){
				for(let i = 0 ; i < this.shippList.length; i++){
					if(this.shippList[i].name == ''){
						this.tui.toast('请输入标签名称')
						return
					}
				}
				if(this.QrList1.path != ''){
					this.shippList.unshift(this.QrList1)
				}
				let data = JSON.stringify(this.shippList)
				if(this.shipId != ''){
					this.tui.request("/app/shopprint/update", "POST", {
						printName:this.printName,
						id:this.shipId,
						content:data
					}, false, false).then((res) => {
						if (res.code == 200) {
							this.tui.toast('修改成功')
							this.printName = ''
							this.shipId = ''
							this.$refs.getaPopup.close()
						} else {
							this.tui.toast(res.message)
						}
					}).catch((res) => {})
				}else{
					this.tui.request("/app/shopprint/add", "POST", {
						printName:this.printName,
						shopId:uni.getStorageSync('shopId'),
						content:data
					}, false, false).then((res) => {
						if (res.code == 200) {
							this.tui.toast('新增成功')
						} else {
							this.tui.toast(res.message)
						}
					}).catch((res) => {})
				}
				setTimeout(res=>{
					uni.navigateBack({
						delta: 1
					})
				},300)
			},
			onPrint1(){
				let that = this
				if(this.number == ''){
					this.tui.toast('请输入数量再打印')
					return
				}
				for(let i=0;i<this.number;i++){
					that.yNum = 20
					let bgineNum = 0
					for(let j=0;j<that.shippList.length;j++){
						if(that.shippList[j].name.length > 15){
							let num = Math.ceil(Number(that.shippList[j].name.length) / 15)
							bgineNum += num
						}else{
							bgineNum += 1
						}
					}
					let offHeigth = 0
					offHeigth = Math.ceil((440 - bgineNum * 24) / bgineNum)
					let strCmd = blesdk.CreatCPCLPage(640, 800, 1, 0);
					strCmd += blesdk.addCPCLSETBOLD('1');
					strCmd += blesdk.addCPCLSETMAG(2, 2)
					if(this.printName != ''){
						strCmd += blesdk.addCPCLLocation(2);
						strCmd += blesdk.addCPCLText('0', that.yNum, '24', '0', 0, this.printName)
					}
					strCmd += blesdk.addCPCLLocation(0);
					// strCmd += blesdk.addCPCLText('30', that.yNum += 30, '24', '0', 0, '')
					let codeWidth = 0
					strCmd += blesdk.addCPCLQRCode(420, 580,"M", '2', 4, that.QrList1.path) //二维码
					strCmd += blesdk.addCPCLSETMAG(1, 1)
					strCmd += blesdk.addCPCLText(420, 750, '24', '0', 0, that.QrList1.name)
					strCmd += blesdk.addCPCLSETMAG(2, 2)
					if(that.shippList.length > 0){
						for(let j=0;j<that.shippList.length;j++){
							let iconWidth = 0 
							if(that.shippList[j].modelLeft == 'right'){
								if(that.shippList[j].leftIcon.length >0 || that.shippList[j].rightIcon.length >0){
									strCmd += blesdk.addCPCLLocation(0);
									let allWidth = 370
									if((that.shippList[j].name + that.shippList[j].value).length > 0){
										allWidth -= 30
									}
									iconWidth = Math.floor((allWidth - ((that.shippList[j].leftIcon.length + that.shippList[j].rightIcon.length) * 32 + (that.shippList[j].name + that.shippList[j].value).length * 25)) / 2)
								}else{
									strCmd += blesdk.addCPCLLocation(2);
								}
							}else{
								strCmd += blesdk.addCPCLLocation(0);
							}
							if(that.shippList[j].modelBlod == 'notblod'){
								strCmd += blesdk.addCPCLSETBOLD('0');
							}else{
								strCmd += blesdk.addCPCLSETBOLD('1');
							}
							let beginNum = ((that.shippList[j].name.length - that.shippList[j].name.replace(/^\s+/, ' ').length) * 25 + 30)
							if(that.shippList[j].leftIcon.length >0 || that.shippList[j].rightIcon.length >0){
								 that.yNum += (32 + offHeigth)
							}else{
								 that.yNum += (25 + offHeigth)
							}
							
							if(that.shippList[j].leftIcon.length >0){
								iconWidth += 31
								for(let m=0;m<that.shippList[j].leftIcon.length;m++){
									strCmd += 'EG 4 32 ' + iconWidth +' '+ that.yNum +' '+ that.shippList[j].leftIcon[m] + ' '
									iconWidth += 40
								} 
							}
							that.shippList[j].name = that.shippList[j].name.replace(/^\s+/, ' ')
							if(that.shippList[j].value != ''){
								if(that.shippList[j].leftIcon.length >0 || that.shippList[j].rightIcon.length >0){
									strCmd += blesdk.addCPCLText((beginNum + iconWidth).toString(),  that.yNum + 4, '24', '0', 0, that.shippList[j].name+': '+that.shippList[j].value)
								}else{
									strCmd += blesdk.addCPCLText((beginNum + iconWidth).toString(),  that.yNum, '24', '0', 0, that.shippList[j].name+': '+that.shippList[j].value)
								}
							}else{
								if(that.shippList[j].name.length > 15){
									let num = Math.ceil(Number(that.shippList[j].name.length) / 15)
									for(let i = 0;i<num;i++){
										if(that.shippList[j].leftIcon.length >0 || that.shippList[j].rightIcon.length >0){
											strCmd += blesdk.addCPCLText((beginNum + iconWidth).toString(),  that.yNum + 4 , '24', '0', 0, that.shippList[j].name.substring(i*15,(i+1)*15))
										}else{
											strCmd += blesdk.addCPCLText((beginNum + iconWidth).toString(),  that.yNum , '24', '0', 0, that.shippList[j].name.substring(i*15,(i+1)*15))
										}
										if(that.shippList[j].leftIcon.length >0 || that.shippList[j].rightIcon.length >0){
											 that.yNum += (32 + offHeigth)
										}else{
											 that.yNum += (25 + offHeigth)
										}
									}
								}else{
									if(that.shippList[j].leftIcon.length >0 || that.shippList[j].rightIcon.length >0){
										strCmd += blesdk.addCPCLText((beginNum + iconWidth).toString(),  that.yNum + 4 , '24', '0', 0, that.shippList[j].name)
									}else{
										strCmd += blesdk.addCPCLText((beginNum + iconWidth).toString(),  that.yNum , '24', '0', 0, that.shippList[j].name)
									}
									
								}
							}
							if(that.shippList[j].rightIcon.length >0){
								let iconWidth1 = Number((that.shippList[j].name + that.shippList[j].value).length * 25 + 30) + iconWidth
								
								for(let m=0;m<that.shippList[j].rightIcon.length;m++){
									strCmd += 'EG 4 32 ' + iconWidth1 +' '+ that.yNum +' '+ that.shippList[j].rightIcon[m] + ' '
									iconWidth1 += 40
								}
							}
						}
						strCmd += blesdk.addCPCLLocation(1);
						codeWidth = 310
					}else{
						strCmd += blesdk.addCPCLLocation(2);
						codeWidth = that.yNum + 60
					}				
					strCmd += blesdk.addCPCLPrint();
					that.bufferData.push(strCmd);
				}
				
				that.$nextTick(()=>{
					uni.navigateBack({
						delta: 1
					})
				}) 
			}
		}
	}
</script>

<style>
	page,.page1{
		font-size: 28rpx;
	}
	.popup-pay-content {
		align-items: center;
		justify-content: center;
		padding: 30rpx;
		height: 1000rpx;
		background-color: #fff;
	}
	.popup-pay-title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		position: relative;
	}
	.popup-pay-container {
		margin-top: 40rpx;
		height: 100rpx;
		border-radius: 10px;
		background: #088FEB;
		line-height: 100rpx;
		text-align: center;
		border-bottom: 1px solid #eee;
		border-top: 1px solid #eee;
		color: #fff;
	}
</style>