<template>
	<view>
		<view class="p-2 mb-1 bg-white border">
			<view v-if="printerList.length===1">(当前只有一个打印机)</view>
			<view class="flex align-center form-item-input">
				<view class="flex-shrink">选择打印机：</view>
				<view class="flex-1">
					<picker mode="selector" :value="printerIndex" :range="printerList" @change="onPrinterChanged"
						class="height-100">
						<view class="uni-input">{{printerList[printerIndex]}}</view>
					</picker>
				</view>
			</view>
		</view>
		<view type="primary" :prop="renderObj" :change:prop="canvas.create" id="canvas"></view>
		<view class="mt-4">
			<button type="primary" class="mx-auto my-1 span-10" :disabled="disabledPrint && !connectPrinter"
				@tap="onPrint">打印</button>
		</view>
<!-- 
		<view class="border-red bg-primary p-3">
			<view v-for="(item,index) in picdataArr">
				image-{{index}}:
				<img :src="item" alt=""/>
			</view>
		</view> -->
		<template v-if="type==='产成品'">
			<view v-for="(item,index) in infoList" :id="'finishLabel'+index">
				<finish-good :item="item" :index="index" @picLoad="onPicload"></finish-good>
			</view>
		</template>
		<template v-else-if="type==='采购件'">
			<view v-for="(item,index) in infoList" :id="'buyLabel'+index">
				<buy-good :item="item" :index="index" @picLoad="onPicload"></buy-good>
			</view>
		</template>
	</view>
</template>

<script>
	import finishGood from "@/components/label-print/finish-good.vue"
	import buyGood from "@/components/label-print/buy-good.vue"

	import {
		LABEL_WIDTH,
		LABEL_HEIGHT
	} from "@/common/utils/tipMessage.js"
	
	import api from '@/common/utils/lpapi-uniplugin.js';
	const modal = uni.requireNativePlugin('modal');


	export default {
		components: {
			finishGood,
			buyGood
		},
		data() {
			return {
				type: "", // 物品类型
				infoList: [], // 接口请求的物品信息
				picdataArr: [], // 存储base64 图片数据
				// 打印及页面的数据
				printerList: [],
				printerIndex: 0,
				printerName: '',
				connectPrinter:false, // 是否连接打印机
				disabledPrint:true,  // 禁止点击打印
				renderObj:{
					type:"",
					list:[],
				},
				isprint:false, // 正在打印
			}
		},
		onLoad(e) {
			this.type = e.type
			this.infoList=e.list ? JSON.parse(e.list) :[],
			this.renderObj.type=this.type
			
			// for (let i = 0; i < 2; i++) {
			// 	this.infoList.push({
			// 		"GG": "0.8*6.2*17*9.5",
			// 		"SWRQ": null,
			// 		"QTY": i,
			// 		"WPMC": "测试一"+i,
			// 		"GYLCKH": null,
			// 		"WPTM": "http://192.168.0.188:8180/samex/rest/webclientrest/queryBarCode?picname=2101000130001750.0",
			// 		"WPH": "101000130"
			// 	})
			// }
			// this.type="产成品"
			this.initPage()
		},
		onUnload() {
			console.log('onUnload')
			this.closePrinter()
		},
		methods: {
			// 初始化页面，超过30秒自动关闭loading层
			async initPage() {
				this.printerList.splice(0);
				const list = await api.getPrinters();
				if (list.length > 0) {
					for (let item of list) {
						console.log("打印机名字", item);
						this.printerList.push(item.name);
					}
				} else {
					this.printerList.push('未检测到打印机');
				}
				// 自动连接打印机
				this.onPrinterChanged();
				this.openPrinter()
			},
			// 选择打印机
			onPrinterChanged(e) {
				this.printerIndex = e ? e.target.value : 0;
				this.printerName = this.printerList[this.printerIndex];
			},
			// 连接打印机
			async openPrinter() {
				if (this.printerName) {
					// 连接新的打印机
					api.openPrinter(this.printerName, (value) => {
						if (value) {
							this.connectPrinter=true
							modal.toast({
								message: '打印机连接成功',
								duration: 1.5,
							});
						}else{
							this.connectPrinter=false
						}
					});
				}
			},
			// 断开打印机连接
			closePrinter() {
				api.closePrinter();
			},
			// 结束打印任务
			async endJob() {
				const res = await api.endJob()
			},
			//打印图片
			async printImage(data) {
				const width = 70;
				const height = 60;
				if (await api.isPrinterOpened()) {
					if (this.isprint) return
					await api.startJob({
						width,
						height
					});
					this.isprint=true
					await api.drawImage({
						image: data,
						width: width,
						height: height,
					});
					await api.commitJob();
					this.isprint=false
					console.log('打印2',this.isprint)
				}
				return true
			},
			// 监听图片已经加载，加载完毕，关闭loading层
			onPicload({index}) {
				const item = this.infoList[index]
				this.renderObj.list.push(item)
			  console.log("onPicload",index)
			},
			/*获取renderjs 传递过来的img数据（格式是base64）
			  如果获取到的数据长度===我们请求的数据长度，则关闭loading层
			*/
			async getRenderPicdata(e) {
				console.log("index"+e.index)
				uni.showLoading({
					title:"正在生成标签图片"
				})
				const data = e.data
				this.picdataArr.push(e.data)
				if (this.picdataArr.length===this.infoList.length) {
					this.disabledPrint=false
					console.log("getRenderPicdata:获取到全部数据")
					uni.hideLoading()
				}else{
					this.disabledPrint=true
				}
			},
			onPrint () {
				uni.showModal({
					title:"确定打印吗?",
					success:async res=>{
						if (res.confirm) {
							const arr=this.picdataArr
							for (let i=0;i<arr.length;i++) {
								await this.printImage(arr[i])
							}
						}
					}
				})
			},
		}
	}
</script>

<script module="canvas" lang="renderjs">
	
	export default {
		data() {
			return {}
		},
		mounted() {
			const script = document.createElement('script')
			script.src = 'static/html2canvas.min.js'
			script.onload = this.initCanvas.bind(this)
			document.head.appendChild(script)
		},
		methods: {
			initCanvas() {
			}, // 将普通script 的数据传递到renderjs里面
			async create(newVal,oldVal,ownerInstance,instance) {
				const type=newVal.type
				const list=newVal.list
				const idname=type==="产成品" ? 'finishLabel' : 'buyLabel'
				// 采购件
				console.log("create")
				for (let i=0;i<list.length;i++) {
					const dom = document.getElementById(idname+i)
					const res=await html2canvas(dom, {useCORS: true,allowTaint: false})
					if (res.nodeName.toLowerCase() === 'canvas') {
						const data = res.toDataURL("image/png")
						// const url=window.URL.createObjectURL(data);
						//将数据传递给普通script
						ownerInstance.callMethod("getRenderPicdata", {
							data: data,
							index:i
						})
					}else{
						console.log("html2canvas-err:", err)
					}
				}
			},
			// 点击打印按钮，将表格转成图片，且发送给普通script
			// async onPrint1(event, ownerInstance) {
			// 	const ok = window.confirm("确定打印标签吗?")
			// 	if (ok) {
			// 		ownerInstance.callMethod("startPrint")
			// 		const len=this.loadedList.length
			// 		for (let i=0;i<len;i++) {
			// 			const dom = document.getElementById("finishLabel" + i)
			// 			html2canvas(dom, {
			// 					useCORS: true,
			// 					allowTaint: false
			// 				})
			// 				.then(canvas => {
			// 					const data = canvas.toDataURL("image/png")
			// 					//将数据传递给普通script
			// 					ownerInstance.callMethod("getRenderPicdata", {
			// 						data: data
			// 					})
			// 				})
			// 				.catch(err => {
			// 					console.log("html2canvas-err:", err)
			// 				})
			// 		}
			// 	}
			// },

		}
	}
</script>




<style>
</style>
