<template>
  <view class="printconfig">
		<view v-if="initPrint==false" class="initPrint">
			<view class="title">使用须知</view>
			<view class="tips">使用前先连接wifi打印机</view>
			<uni-easyinput class="input" confirm-type="done" v-model="printInfo.ip" placeholder="请输入打印机ip地址" @confirm="connectPrint"></uni-easyinput>
		</view>
		<view v-else class="printInfo">
			<view>当前连接打印机</view>
			<uni-easyinput disabled v-model="printInfo.ip" placeholder="请输入打印机ip地址"></uni-easyinput>
			<button @click="resetPrint">断开连接</button>
		</view>
  </view>
</template>

<script>
  export default {
    name: 'printConfig'
  }
</script>

<script setup>
import { onMounted, ref } from 'vue'

const plug= uni.requireNativePlugin('Html5app-Gprinter');
const initPrint = ref(false)
const printInfo = ref({
	ip:'',
	port:'9100'
})
onMounted(() => {

})

const emit = defineEmits(['emitClose'])

const connectPrint = ()=>{
	const ipReg = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
	if(ipReg.test(printInfo.value.ip)){
		if(RegExp.$1<256 && RegExp.$2<256 && RegExp.$3<256 && RegExp.$4<256){
			plug.connectIP({"ip":printInfo.value.ip,"port":printInfo.value.port},ret=>{
				console.log('connectPrint>>ret',ret)
				const res = JSON.parse(JSON.stringify(ret))
				console.log('connectPrint>>res',res.code)
				if(res.code==3){
					initPrint.value = true
					uni.setStorageSync('initPrint', true)
					// _this.tip=JSON.stringify(ret);
					// console.log(_this.tip);	
					// 关闭配置页操作
					emit('emitClose')
				} else{
					uni.$showMsg('打印机连接失败，请重试！', 500)
				}
				
			});
		} else{
			uni.$showMsg('ip地址有误，请重试！', 2000)
		}
	}
}

const resetPrint = ()=>{
	plug.disconnect({},ret=>{
		uni.$showMsg(ret.msg, 2000)
		initPrint.value = false
		// console.log(_this.tip);
	});
}


</script>

<style lang="scss">
  .printconfig{
		background-color: #fff;
		width: 500rpx;
		height: 300rpx;
		padding: 20rpx;
		.initPrint{
			.title{
				font-size: 20rpx;
			}
			.tips{
				font-size: 16rpx;
			}
			.input{
				width: 300rpx;
			}
		}
		
	}
</style>