<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="onPrinterChange"
						class="height-100">
						<view class="uni-input">{{printerList[printerIndex]}}</view>
					</picker>
				</view>
			</view>
		</view>
    <view class="flex align-center">
    	<button type="primary" class="mx-auto my-1 span-10" @tap="onGet" v-if='showConnectBtn'>连接打印机</button>
    	<button type="primary" :disabled="disabledPrint" class="mx-auto my-1 span-10" @tap="onPrint" v-if='showPrintBtn'>打印</button>
      <view class="text-center">
        <view class="d-inline-block p-1 ml-sm" @tap="onTogglePrintBtn(false)" v-if="showPrintBtn">隐藏打印按钮</view>
      </view>
    </view>
		<view type="primary" :prop="renderObj" :change:prop="canvas.create" id="canvas"></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: [], // 接口请求的物品信息
				loadedList:[], // 已经加载的图片
				picdataArr: [], // 存储base64 图片数据
				// 打印及页面的数据
				printerList: [],
				printerIndex: 0,
				connectPrinter:false, // 是否连接打印机
				disabledPrint:true,  // 禁止点击打印
				renderObj:{
					type:"",
					list:[],
				},
        showPrintBtn:false,  //显示打印按钮
        showConnectBtn:false, // 显示连接按钮
			}
		},
    computed:{
      printerName () {
        return 	this.printerList.length>0 ? this.printerList[this.printerIndex] : null
      }
    },
		watch:{
		},
		onLoad(e) {
      console.log("onLoad")
			this.type = e.type
			this.infoList=e.list ? JSON.parse(e.list) :[]
			this.renderObj.type=this.type
		},
    onShow () {
      console.log("onShow")
      this.initPage()
    },
		onUnload() {
			this.closePrinter()
		},
		onHide () {
		},
		methods: {
			// ceshi
			demo () {
				for (let i = 0; i < 1; 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.renderObj.type=this.type
			},
			// 初始化页面，超过30秒自动关闭loading层
			async initPage() {
				const list = await this.onGet(); // 获取打印机
				if (list.length===0) {
					this.showConnectBtn=true
					uni.showToast({
					  title:"未检测到打印机",
					  icon:"none"
					})
					return false
				}
				// 自动连接打印机
        const res=await this.openPrinter()
        return res
			},
      // 获取打印机
      async onGet(){
        this.printerList.splice(0);
        uni.showLoading({
          title:"正在搜索打印机..."
        })
        const list = await api.getPrinters(); // 获取打印机
        uni.hideLoading()
        if (list.length===0) {
          uni.showToast({
            title:"未检测到打印机",
            icon:"none"
          })
        }else{
          this.showConnectBtn=false
          for (let item of list) {
          	this.printerList.push(item.name);
          }
        }
        return this.printerList
      },
			// 连接打印机
			async openPrinter() {
        uni.showLoading({
          title:"正在连接打印机..."
        })
        const res=await api.openPrinter(this.printerName, (value) => {
          uni.hideLoading()
        	if (value) {
        		this.connectPrinter=true
            uni.showToast({
            	title: '打印机连接成功'
            });
        	}else{
            uni.showToast({
            	title: '打印机连接失败,请检测打印机是否打开',
              icon:"none"
            });
        		this.connectPrinter=false
        	}
          Promise.resolve(res)
        });
        return res
			},
			// 隐藏打印按钮
      onTogglePrintBtn(visible){
        this.showPrintBtn=visible
      },
      // 选择打印机
			onPrinterChange(e) {
				this.printerIndex =e.target.value
			  // 切换打印机后，再连接打印机
			  this.openPrinter()
			  this.onTogglePrintBtn(true)
			},
      // 断开打印机连接
			closePrinter() {
				api.closePrinter();
			},
			// 结束打印任务
			async endJob() {
				const res = await api.endJob()
			},
			//打印图片,自动打印和for循环不一样
			async printImage(data,isawait=false) {
        const width = 70;
        const height = 60;
        const isPrinterOpened=await api.isPrinterOpened();
        console.log("isPrinterOpened",isPrinterOpened)
        const printFn=async ()=>{
          uni.showLoading({
            title:"正在打印标签"
          })
          await api.startJob({
          	width,
          	height
          });
          await api.drawImage({
          	image: data,
          	width: width,
          	height: height,
          });
          await api.commitJob();
          uni.hideLoading()
        }
        // 打印机已经打开
				if (isPrinterOpened) {
          // const res=await this.initPage();
          // console.log("打印机已打开",res)
          if (isawait) {
            await printFn()
          }else{
            printFn()
          }
				}else{
          const res=await this.initPage();
          console.log("打印机未打开",res)
          if (res) {
            if (isawait) {
              await printFn()
            }else{
              printFn()
            }
          }else{
            unis.showToast({
              title:"出现未知错误，请重新连接打印机",
              icon:"none"
            })
          }
        }
				return true
			},
			// 监听图片已经加载，加载完毕，关闭loading层
			onPicload({index}) {
				const item = this.infoList[index]
				this.loadedList.push(item)
				if (this.loadedList.length===this.infoList.length) {
					this.renderObj.list=this.infoList
				}
			},
			/*获取renderjs 传递过来的img数据（格式是base64）
			  如果获取到的数据长度===我们请求的数据长度，则关闭loading层
			*/
			async getRenderPicdata(e) {
				const data = e.data
				const index = e.index
        await this.printImage(data)
        this.picdataArr.push(data)
        console.log("getRenderPicdata",this.picdataArr.length)
				if (this.picdataArr.length===this.infoList.length) {
					this.disabledPrint=false
				}else{
					this.disabledPrint=true
				}
			},
			async onPrint () {
				const arr=this.picdataArr
				for (let i=0;i<arr.length;i++) {
					await this.printImage(arr[i],true)
				}
			},
		}
	}
</script>

<script module="canvas" lang="renderjs">
	
	export default {
		data() {
			return {
        type:""
      }
		},
		mounted() {
      console.log("html2canvas:mounted")
			const script = document.createElement('script')
			script.src = 'static/html2canvas.min.js'
			script.onload = this.initCanvas.bind(this)
			document.head.appendChild(script)
		},
		methods: {
			async initCanvas() {
			}, // 将普通script 的数据传递到renderjs里面
			async create(newVal,oldVal,ownerInstance,instance) {
				const type=newVal.type
				const list=newVal.list
				const idname=type==="产成品" ? 'finishLabel' : 'buyLabel'
				// 采购件
				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")
						//将数据传递给普通script
						ownerInstance.callMethod("getRenderPicdata", {
							data: data,
							index:i,
						})
					}else{
            uni.shoToast({
              title:`html2canvas_err:转换图片失败`
            })
					}
				}
			},
			// 点击打印按钮，将表格转成图片，且发送给普通script
			// async onPrintrender(event, ownerInstance) {
   //        console.log("onPrint",this.loadedList)
			// 		const len=this.loadedList.length
   //        const idname=this.type==="产成品" ? 'finishLabel' : 'buyLabel'
			// 		for (let i=0;i<len;i++) {
			// 			const dom = document.getElementById(idname + i)
			// 			html2canvas(dom, {
			// 					useCORS: true,
			// 					allowTaint: false
			// 				})
			// 				.then(canvas => {
			// 					const data = canvas.toDataURL("image/png")
			// 					//将数据传递给普通script
			// 					ownerInstance.callMethod("getRenderPicdata", {
			// 						data: data
			// 					})
			// 				})
			// 				.catch(err => {
			// 					uni.shoToast({
			// 					  title:`html2canvas_err:转换图片失败:${err}`
			// 					})
			// 				})
			// 		}
			// },
		}
	}
</script>




<style>
</style>
