<template>
	<gui-page :custom-header="true" :header-class="['gui-theme-background-color']">
		<template #gHeader>
			<view style="height:44px;" class="gui-flex gui-nowrap gui-rows gui-align-items-center">
				<!-- 使用组件实现返回按钮及返回首页按钮 -->
				<text style="font-size:44rpx;" class="gui-header-leader-btns gui-color-white font-icons"
					@tap="goBack">&#xe6c5;</text>
				<!-- 导航文本此处也可以是其他自定义内容 -->
				<text
					class="gui-h4 gui-blod gui-flex1 gui-text-center gui-ellipsis gui-color-white gui-primary-text">装箱明细</text>
				<!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
				<!-- 实际宽度请根据自己情况设置 -->
				<view style="width:40px;" />
				<!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
			</view>
		</template>
		<template #gBody>
			<view class="list-content">
				<view class="collapsed-panel" v-if="cardList.length > 0">
					<div class="content" v-for="item in cardList" :key="item.id" @click="handleHighLightRow(item)">
						<div :class="['panel-row', highLightField?.id === item.id?'printer':'']">
							<span>内盘标批号</span>
							<span>{{ item.workpieceTrayLabel }}</span>
						</div>
						<div :class="['panel-row', highLightField?.id === item.id?'printer':'']">
							<span>数量</span>
							<span>{{ ~~item.qty }}</span>
						</div>
					</div>
				</view>
				<view v-else>
					<view class="bg-image">
						<image src="@/static/empty.png" mode="heightFix" />
						<text>这里什么都没有...</text>
					</view>
				</view>
			</view>
			<view class="operation-panel">
				<button type="primary" :disabled="!highLightField" style="width: calc(100% - 8px);margin: 0 4px;"
					@click="handleShipmentBoxPrinter">内盘/袋标签补打</button>
			</view>
			<uni-popup ref="errorTip" type="dialog">
				<uni-popup-dialog type="error" cancel-text="关闭" confirm-text="确认" title="提示" :content="errorTipMessage"
					@confirm="handleCloseErrorTipsModal" @close="handleCloseErrorTipsModal" />
			</uni-popup>
		</template>
	</gui-page>
</template>

<script>
	import {
		computed,
		defineComponent,
		onBeforeMount,
		ref
	} from 'vue'
	import tsc from '@/unit/CHITEN_SDK_APP/tsc.js'
	export default defineComponent({
		setup(options) {
			const easyinput = ref()
			const errorTip = ref('')
			const errorTipMessage = ref('')
			const cardList = ref([])
			const formData = ref()
			const parseData = JSON.parse(options?.params) ?? {}
			const highLightField = ref()
			const bluetooth = ref()
			const blueConfig = ref({
				loopBuffer: 0,
				currentTime: 1,
				lastData: 0,
				onBufferSize: 20,
				printerNum: 1,
				currentPrint: 1,
				isLabelSend: false
			})

			onBeforeMount(() => {
				// #ifdef APP-PLUS
				const bluetoothConfig = uni.getStorageSync('bluetoothConfig')
				if ([null, '', undefined].includes(bluetoothConfig)) {
					bluetooth.value = {
						'isOpenBle': false,
						'deviceId': '',
						'serviceId': '',
						'writeId': '',
						'notifyId': ''
					}
					setTimeout(() => {
						// #ifdef APP-PLUS
						plus.device.beep(2)
						// #endif
						errorTipMessage.value = '蓝牙打印机未连接'
						errorState.value = -1
						errorTip.value.open()
					}, 800)
				} else {
					bluetooth.value = JSON.parse(bluetoothConfig)
				}
				// #endif


				formData.value = parseData
				cardList.value = parseData?.insideRespVOList ?? [];
			})

			const handleShipmentBoxPrinter = function() {
				// const filterBoxId = cardList.value?.filter(ret => ret.labelContent === highLightField
				// 	.value)[0]?.id
				// 打印内部标签
				uni.$reqGet("getShippingLabelPrintData", {
						id: highLightField.value.id
					})
					.then(async ({
						code,
						data,
						msg
					}) => {
						if (code === 0) {
							// 打印
							await labelInnerTest(data)
							blueConfig.value.currentPrint = 1
							blueConfig.value.printNum = 2
							const timer = setInterval(() => {
								if (blueConfig.value.isLabelSend === false &&
									blueConfig.value.currentPrint === 2) {
									blueConfig.value.currentPrint += 1
									labelExternalTest(data)
								}
								if (blueConfig.value.currentPrint === blueConfig
									.value.printNum) {
									clearInterval(timer);
								}
							}, 2000)
						} else {
							// #ifdef APP-PLUS
							plus.device.beep(2)
							// #endif
							errorTipMessage.value = msg
							errorTip.value.open()
						}
					})
			}

			const Send = function(buff) {
				var currentTime = blueConfig.value.currentTime
				var loopBuffer = blueConfig.value.loopBuffer
				var lastData = blueConfig.value.lastData
				var onBufferSize = blueConfig.value.onBufferSize
				var printNum = blueConfig.value.printerNum
				var currentPrint = blueConfig.value.currentPrint
				var buf
				var dataView
				if (currentTime < loopBuffer) {
					buf = new ArrayBuffer(onBufferSize)
					dataView = new DataView(buf)
					for (let i = 0; i < onBufferSize; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onBufferSize + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (let i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onBufferSize + i])
					}
				}
				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: bluetooth.value.deviceId,
					serviceId: bluetooth.value.serviceId,
					characteristicId: bluetooth.value.writeId,
					value: buf,
					success: function(res) {
						if (currentPrint <= printNum) {
							wx.showToast({
								title: '数据打印中',
								icon: 'loading'
							})
						}
						// 将complete中处理数据的代码挪过来，增加30ms延迟, 解决蓝牙打印数据传输10007问题
						setTimeout(() => {
							currentTime += 1
							if (currentTime <= loopBuffer) {
								blueConfig.value.isLabelSend = true
								blueConfig.value.currentTime = currentTime
								Send(buff)
							}
							// end
							if (currentTime === loopBuffer) {
								blueConfig.value.currentPrint += 1
								blueConfig.value.isLabelSend = false
							}
						}, 10)
					},
					fail: function(e) {
						wx.showToast({
							title: '打印第' + currentPrint + '张失败' + 'error: code ' + e
								?.code + ', message ' + e?.message,
							icon: 'none',
							duration: 4000
						})
					},
					complete: function() {}
				})
			}

			const prepareSend = function(buff) {
				var time = blueConfig.value.onBufferSize
				var loopBuffer = parseInt(buff.length / time)
				var lastData = parseInt(buff.length % time)
				blueConfig.value.loopBuffer = loopBuffer + 1
				blueConfig.value.lastData = lastData
				blueConfig.value.currentTime = 1
				Send(buff)
			}

			const labelInnerTest = function(ret) {
				var command = tsc.dlabelPrinter.createNew()
				command.setBackFeed(4)
				command.setOffset(-2)
				// (480 * 200)dots
				command.setSize(60, 25)
				command.setCls()
				command.setGap(6, 2)
				command.setSpeed(1.5)

				// row1
				command.setText(4, 0, '1', 0, 1, 1, '(C)Customer P/N:')
				command.setText(172, 0, '1', 0, 1, 1, ret.c)
				command.setText(278, 0, '1', 0, 1, 1, '(D)QTY(EA):')
				command.setText(378, 0, '1', 0, 1, 1, ret.qty)
				// row2
				command.setText(4, 20, '1', 0, 1, 1, '(G)LOT NO:')
				const strList = ret.lotNo?.split('');
				let lotNo = ''
				let lotNo2 = ''
				if (strList.length > 16) {
					lotNo = ret.lotNo?.substring(0, 16)
					lotNo2 = ret.lotNo?.substring(16)
					command.setText(102, 20, '1', 0, 1, 1, lotNo)
					command.setText(102, 40, '1', 0, 1, 1, lotNo2)
				} else {
					command.setText(102, 20, '1', 0, 1, 1, ret.lotNo)
				}
				command.setText(270, 20, '1', 0, 1, 1, '(J)ExpDate:')
				const timeList = ret.expDate?.split('');
				let timeText = ''
				let timeText2 = ''
				if (timeList.length > 9) {
					timeText = ret.expDate?.substring(0, 9)
					timeText2 = ret.expDate?.substring(9)
					command.setText(380, 20, '1', 0, 1, 1, timeText)
					command.setText(380, 40, '1', 0, 1, 1, timeText2)
				} else {
					command.setText(380, 20, '1', 0, 1, 1, ret.expDate)
				}
				// row3
				command.setText(128, 60, '1', 0, 1, 1, '(E)Manuf:')
				command.setText(218, 60, '1', 0, 1, 1, ret.manuf)
				command.setText(128, 78, 'TSS24.BF2', 0, 1, 1, '存储条件:')
				// let strList2 = []
				// let strText = ''
				// if (ret.storageEnvironmentName) {
				// 	strList2 = ret.storageEnvironmentName?.split(' ')
				// 	strText = strList2[0] + ' ' + strList2[1]
				// } else {
				// 	strText = '';
				// }
				command.setText(208, 94, 'TSS24.BF2', 0, 1, 1, '温度 ' + ret.temperature)
				command.setText(208, 112, 'TSS24.BF2', 0, 1, 1, '湿度 ' + ret.humidity)
				// command.setText(208, 94, 'TSS24.BF2', 0, 1, 1, strText)
				
				// row4
				command.setQrcode(4, 64, 'H', 4, 'A', ret.lotNo2)
				command.setQrcode(318, 54, 'M', 3, 'A', ret.qrCode1)
				command.setText(128, 160, '1', 0, 1, 1, 'C.O.O.CN')
				command.setText(128, 178, '2', 0, 1, 1, 'ROHS 2.0 HF')

				command.setPagePrint()
				blueConfig.value.isLabelSend = true
				prepareSend(command.getData())
			}

			const labelExternalTest = function(ret) {
				var command = tsc.dlabelPrinter.createNew()
				command.setBackFeed(6)
				// (640 * 320)dots
				command.setSize(80, 40)
				command.setCls()
				command.setGap(6)
				command.setSpeed(1.5)

				// row1
				command.setText(4, 0, '1', 0, 1, 1, '(A)Cust PO:')
				command.setText(120, 0, '1', 0, 1, 1, ret.a)
				// row2
				command.setText(4, 15, '1', 0, 1, 1, '(C)Customer P/N:')
				command.setText(165, 15, '1', 0, 1, 1, ret.c)
				command.setText(280, 12, '1', 0, 1, 1, 'C.O.O.CN')
				// row3
				command.setText(4, 30, '1', 0, 1, 1, '(E)Manuf:')
				command.setText(100, 30, '1', 0, 1, 1, ret.manuf)
				// command.setText(300, 45, 'TSS24.BF2', 0, 1, 1, '量产模具生产')
				// row4
				command.setText(4, 45, '1', 0, 1, 1, '(H)Date Code:')
				command.setText(140, 45, '1', 0, 1, 1, ret.h)
				command.setText(280, 30, '2', 0, 1, 1, 'ROHS 2.0 HF')
				// row5
				command.setText(4, 60, '1', 0, 1, 1, '(J)ExpDate:')
				command.setText(120, 60, '1', 0, 1, 1, ret.expDate)
				command.setText(270, 60, '1', 0, 1, 1, '(B)Line NO:')
				command.setText(385, 60, '1', 0, 1, 1, ret.b)
				// row6
				command.setText(4, 75, '1', 0, 1, 1, '(G)LOT NO:')
				const strList = ret.lotNo?.split('');
				let lotNo = ''
				let lotNo2 = ''
				if (strList.length > 16) {
					lotNo = ret.lotNo?.substring(0, 16)
					lotNo2 = ret.lotNo?.substring(16)
					command.setText(102, 75, '1', 0, 1, 1, lotNo)
					command.setText(102, 90, '1', 0, 1, 1, lotNo2)
				} else {
					command.setText(102, 75, '1', 0, 1, 1, ret.lotNo)
				}
				command.setText(270, 75, '1', 0, 1, 1, '(D)QTY(EA):')
				command.setText(385, 75, '1', 0, 1, 1, ret.qty)
				// row3
				command.setText(90, 110, 'TSS24.BF2', 0, 1, 1, '存储条件:')
				// let strList2 = []
				// let strText = ''
				// if (ret.storageEnvironmentName) {
				// 	strList2 = ret.storageEnvironmentName?.split(' ')
				// 	strText = strList2[0] + ' ' + strList2[1]
				// } else {
				// 	strText = '';
				// }
				command.setText(90, 135, 'TSS24.BF2', 0, 1, 1, '温度 ' + ret.temperature)
				command.setText(90, 150, 'TSS24.BF2', 0, 1, 1, '湿度 ' + ret.humidity)
				// command.setText(90, 135, 'TSS24.BF2', 0, 1, 1, strText)
				
				command.setText(230, 110, '1', 0, 1, 1, '(F)MPN:')
				command.setText(315, 110, '1', 0, 1, 1, ret.f)
				command.setText(4, 195, '1', 0, 1, 1, '(K)ERP LOT:')
				// QR
				command.setQrcode(4, 100, 'Q', 3, 'A', ret.lotNo2)
				command.setQrcode(470, 0, 'Q', 3, 'A', ret.qrCode1)
				command.setBarCode(4, 210, '39', 50, 1, 0, 1, 2, ret.k)
				// row5
				command.setText(230, 125, '1', 0, 1, 1, '(I)ManufID:')
				command.setText(340, 125, '1', 0, 1, 1, ret.i)
				command.setText(230, 140, '1', 0, 1, 1, '(L)ADH:')
				command.setText(315, 140, '1', 0, 1, 1, ret.l)
				// row5
				command.setText(275, 190, 'TSS24.BF2', 0, 1, 1, '原胶LOT NO:')
				command.setText(410, 195, '2', 0, 1, 1, ret.rawIncomingReceiptMaterialLots)
				// row6
				command.setText(275, 230, '1', 0, 1, 1, 'ADHManufDate:')
				command.setText(410, 230, '1', 0, 1, 1, ret.rawProduceDate)
				command.setText(275, 250, '1', 0, 1, 1, 'ADHExpDate:')
				command.setText(400, 250, '1', 0, 1, 1, ret.rawExpirationDate)

				command.setPagePrint()
				blueConfig.value.isLabelSend = true
				prepareSend(command.getData())
			}

			// 高亮行点击事件
			const handleHighLightRow = function(ret) {
				highLightField.value = ret;
			}

			const goBack = function() {
				uni.$goBack(
					`/pages/workbranch/production/shipment/shipmentOrderInfoDetails?params=${JSON.stringify(parseData)}`
				)
			}

			// 关闭错误信息弹窗
			const handleCloseErrorTipsModal = async function() {
				errorTip.value.close()
			}

			return {
				formData,
				highLightField,
				goBack,
				easyinput,
				errorTip,
				errorTipMessage,
				cardList,
				handleHighLightRow,
				handleShipmentBoxPrinter,
				handleCloseErrorTipsModal
			}
		}
	})
</script>

<style lang="scss" scoped>
	.gui-header-leader-btns {
		color: black;
		margin-left: 24rpx;
		font-size: 24px !important;
	}

	.list-content {
		margin-top: 80px;
		min-height: calc(100vh - 80px);
		background-color: #edeeee;
	}

	.input-200 {
		width: 200px;
		padding-left: 10px;
	}

	.icon-scan {
		font-size: 20px;
		text-align: right;
	}

	.scan {
		height: 45px;
		width: calc(100% - 48px);
		margin: 12px;
		padding: 0 12px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-radius: 6px;
		background-color: white;

		.scan-card {
			width: 100%;
			display: grid;
			grid-template-rows: 1fr;
			grid-template-columns: 7fr 2fr;
			align-items: center;

			input {
				height: 35px;
				line-height: 35px;
			}

			text {
				width: 100%;
				text-align: right;
			}
		}
	}

	span,
	text {
		font-size: 12px;
	}

	.collapsed-panel {
		// height: calc(100vh - 190px);
		// min-height: 230px;
		margin: 5px 0;
		padding: 0 8px;
		overflow-y: scroll;

		.content {
			position: relative;
			overflow-y: scroll;
			border-top: 2px dashed rgba(237, 238, 238, 1);

			.panel-row {
				// height: 32px;
				line-height: 32px;
				padding: 0 12px;
				display: flex;
				justify-content: space-between;
				background-color: #fbfbfb;

				span:nth-of-type(1) {
					min-width: 30%;
				}

				span:nth-of-type(2) {
					min-width: 30%;
					padding-right: 8px;
					text-align: right;
					word-wrap: break-word;
					overflow-y: scroll;
				}
			}

			.font-icons {
				position: absolute;
				right: 2px;
				top: 50%;
				transform: translate(0, -50%);
				z-index: 1;
			}
		}
	}

	.printer {
		color: white;
		background-color: #00a0e9 !important;
	}

	.operation-panel {
		padding: 12px 0;
		position: fixed;
		bottom: 0;
		width: 100%;
		display: grid;
		grid-template-columns: 1fr;
		grid-template-rows: 1fr;
		background-color: white;

		.operation-title {
			height: 40px;
			line-height: 40px;
			padding: 0 14px;
			font-size: 16px;
			font-weight: bold;
		}
	}
</style>