<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="goHome"
        >&#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="scan">
          <view class="scan-card">
            <uni-easyinput
              ref="easyinput"
              v-model="scanNumber"
              :input-border="false"
              :clearable="false"
              type="text"
              focus
			  @focus="handleInputFocus"
              placeholder="扫描内部标签"
              @confirm="handleKeydown"
            />
            <text class="font-icons" @click="handleMapass">&#xe6b7;</text>
          </view>
        </view>
        <view class="table-title">
          <view><text style="font-size: 16px;">合并列表</text></view>
        </view>
        <view v-if="packageList?.length > 0" class="list-panel">
          <!-- eslint-disable-next-line vue/valid-v-for -->
          <view v-for="(item, key) in packageList" v-key="key" class="panel">
            <uni-swipe-action>
              <!-- 基础用法 -->
              <uni-swipe-action-item :right-options="options" @click="handleRemoveDetail(key)">
                <template #left>
                  <view />
                </template>
                <view class="panel-row">
                  <text>批次</text>
                  <text>{{ item.batchNumber }}</text>
                </view>
                <view class="panel-row">
                  <text>数量</text>
                  <text>{{ item.qty }} PCS</text>
                </view>
                <view class="panel-row">
                  <text>产品编码</text>
                  <text>{{ item.materialNo }}</text>
                </view>
              </uni-swipe-action-item>
            </uni-swipe-action>
          </view>
        </view>
        <view v-else>
          <view class="bg-image" style="height: 70vh !important;">
            <image src="@/static/empty.png" mode="heightFix" />
            <text>这里什么都没有...</text>
          </view>
        </view>
        <view class="operation-panel">
          <view class="operation-title">合并数量:
            <text style="font-size: 16px;font-weight: bold;">{{ computedRemainder }}</text>
            <text
              style="color: #f85661;font-size: 16px;font-weight: bold;"
            >&nbsp;&nbsp;{{ computedReadonlyText }}</text>
          </view>
          <button
            type="primary"
            :disabled="packageList?.length < 2? true: false"
            style="width: calc(100% - 8px);margin: 0 4px;"
            @click="hanleSplitLabelCode"
          >合并</button>
        </view>
      </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 {
  add
} from '@/unit/Math.js'
import tsc from '@/unit/CHITEN_SDK_APP/tsc.js'
export default defineComponent({
  setup() {
    const bluetooth = ref()
    const modalForm = ref('')
    const errorState = ref(0)
    const easyinput = ref()
    const errorTip = ref('')
    const errorTipMessage = ref('')
    const scanNumber = ref('')
    const packageList = ref([])
    const blueConfig = ref({
      loopBuffer: 0,
      currentTime: 1,
      lastData: 0,
      onBufferSize: 20,
      printerNum: 1,
      currentPrint: 1,
      isLabelSend: false
    })

    const computedRemainder = computed(() => {
      let remainder = 0
      for (let i = 0; i < packageList.value.length; i++) {
        remainder = add(packageList.value[i].qty, remainder)
      }
      return remainder
    })

    const computedReadonlyText = computed(() => {
      const materialNo = packageList.value[0]?.materialNo
      const isTrue = packageList.value.every(item => item.materialNo === materialNo)
      return !isTrue ? '列表产品编码不一致' : ''
    })

    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
    })

    const validataPackageRepeat = function(objectData) {
      const batchNumbers = []
      batchNumbers.push(objectData.batchNumber)
      packageList.value.forEach(ret => {
        batchNumbers.push(ret.batchNumber)
      })
      uni.$reqPost('blendingCheck', {
        batchNumbers
      })
        .then(({
          code,
          data,
          msg
        }) => {
          if (code === 0 && data) {
            packageList.value.push(objectData)
            setInputFocus()
          } else {
            // #ifdef APP-PLUS
            plus.device.beep(2)
            // #endif
            errorTipMessage.value = msg
            errorTip.value.open()
            errorState.value = 0
          }
        })
    }

    const handleMapass = function() {
      // #ifdef APP-PLUS
      const mpaasScanModule = uni.requireNativePlugin('Mpaas-Scan-Module')
      mpaasScanModule.mpaasScan({
        // 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
        'scanType': ['qrCode', 'barCode'],
        // 是否隐藏相册，默认false不隐藏
        'hideAlbum': false
      },
      (ret) => {
        if (ret.resp_code === 1000) {
          uni.$reqGet('getQrCodeInfo', {
            qrCode: ret.resp_result
          })
            .then(({
              code,
              data,
              msg
            }) => {
              if (code === 0) {
                validataPackageRepeat(data)
              } else {
                // #ifdef APP-PLUS
                plus.device.beep(2)
                // #endif
                errorTipMessage.value = msg
                errorTip.value.open()
                errorState.value = 0
              }
            })
        }
      })
      // #endif
    }

    // 扫描完成品标签输入框回车事件
    const handleKeydown = function(e) {
      uni.$reqGet('getQrCodeInfo', {
        qrCode: e
      })
        .then(({
          code,
          data,
          msg
        }) => {
          if (code === 0) {
            validataPackageRepeat(data)
          } else {
            // #ifdef APP-PLUS
            plus.device.beep(2)
            // #endif
            errorTipMessage.value = msg
            errorTip.value.open()
            errorState.value = 0
          }
        })
    }

    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 labelTest = function(ret) {
      var command = tsc.dlabelPrinter.createNew()
      command.setBackFeed(6)
      // (480 * 200)dots
      command.setSize(60, 25)
      command.setCls()
      command.setGap(6)
      command.setBox(0, 0, 475, 200, 1)
      // 1
      command.setBar(108, 0, 2, 40)
      command.setBar(108, 40, 2, 40)
      command.setBar(108, 80, 2, 40)
      command.setBar(108, 120, 2, 40)
      command.setBar(108, 160, 2, 40)
      command.setBar(108, 200, 2, 40)
      // 竖
      command.setBar(210, 80, 2, 40)
      command.setBar(210, 120, 2, 40)
      command.setBar(210, 160, 2, 40)
      command.setBar(210, 200, 2, 40)
      // 横
      command.setBar(0, 40, 480, 2)
      command.setBar(0, 80, 320, 2)
      command.setBar(0, 120, 210, 2)
      command.setBar(0, 160, 210, 2)
      // 横
      command.setBar(320, 80, 480, 2)
      command.setBar(320, 120, 480, 2)
      command.setBar(320, 160, 480, 2)
      // 竖
      command.setBar(322, 40, 2, 40)
      command.setBar(322, 80, 2, 40)
      command.setBar(322, 120, 2, 40)
      command.setBar(322, 160, 2, 40)
      // 竖
      command.setBar(378, 40, 2, 40)
      command.setBar(378, 80, 2, 40)
      command.setBar(378, 120, 2, 40)
      command.setBar(378, 160, 2, 40)

      // row1
      command.setText(4, 8, 'TSS24.BF2', 0, 1, 1, '料号')
      command.setText(112, 10, '2', 0, 1, 1, ret.pn)
      // row2
      command.setText(4, 48, 'TSS24.BF2', 0, 1, 1, '工令单')
      command.setText(112, 50, '2', 0, 1, 1, ret.wordOrderNo)
      command.setText(328, 48, 'TSS24.BF2', 0, 1, 1, '数量')
      command.setText(384, 50, '2', 0, 1, 1, ret.qty)
      // row3
      command.setText(4, 88, 'TSS24.BF2', 0, 1, 1, '生产日期')
      command.setText(110, 90, '1', 0, 1, 1, ret.dateOfManufacture)
      command.setText(328, 88, 'TSS24.BF2', 0, 1, 1, '库位')
      command.setText(384, 90, '1', 0, 1, 1, ret.storageLocation)
      // row4
      command.setText(4, 128, 'TSS24.BF2', 0, 1, 1, '供应商')
      command.setText(112, 130, '3', 0, 1, 1, ret.vendor)
      command.setText(328, 128, 'TSS24.BF2', 0, 1, 1, '后制')
      command.setText(384, 130, '1', 0, 1, 1, ret.postProduction)
      // row5
      command.setText(4, 168, 'TSS24.BF2', 0, 1, 1, '包装')
      command.setText(112, 170, '1', 0, 1, 1, ret.packaging)
      command.setText(328, 168, 'TSS24.BF2', 0, 1, 1, 'QC')
      command.setText(384, 170, '1', 0, 1, 1, ret.qc)

      command.setQrcode(214, 88, 'L', 5, 'A', ret.qrCode)
      command.setPagePrint()
      prepareSend(command.getData())
    }

    const hanleSplitLabelCode = function() {
      const list = []
      const batchNumbers = []
      packageList.value.forEach(ret => {
        batchNumbers.push(ret.batchNumber)
      })
      uni.$reqPost('blending', {
        batchNumbers
      })
        .then(({
          code,
          data,
          msg
        }) => {
          if (code === 0) {
            list.push(data)
            blueConfig.value.currentPrint = 1
            blueConfig.value.printNum = list.length

            const timer = setInterval(async() => {
              const currentPrint = blueConfig.value.currentPrint - 1
              if (blueConfig.value.isLabelSend === false &&
									currentPrint <
									blueConfig.value.printNum) {
                const paramsObj = {
                  pn: list[currentPrint]
                    .pn ?? '',
                  wordOrderNo: list[currentPrint]
                    .wordOrderNo ??
											'',
                  qty: list[currentPrint]
                    .qty ??
											'',
                  dateOfManufacture: list[currentPrint]
                    .dateOfManufacture ??
											'',
                  storageLocation: list[currentPrint]
                    .storageLocation ??
											'',
                  postProduction: list[currentPrint]
                    .postProduction ??
											'',
                  vendor: list[currentPrint]
                    .vendor ??
											'',
                  packaging: list[currentPrint]
                    .packaging ??
											'',
                  qc: list[currentPrint]
                    .qc ??
											'',
                  qrCode: list[currentPrint]
                    .qrCode ??
											''
                }
                await labelTest(paramsObj)
              }
              if (currentPrint === blueConfig.value.printNum) {
                await clearInterval(timer)
              }
            }, 3000)
            packageList.value.length = 0
            setInputFocus()
          } else {
            // #ifdef APP-PLUS
            plus.device.beep(2)
            // #endif
            errorTipMessage.value = msg
            errorTip.value.open()
            errorState.value = 0
          }
        })
    }

    const goHome = function() {
      uni.$goHome()
    }

    const setInputFocus = function() {
      scanNumber.value = ''
      easyinput.value.onBlur()
      easyinput.value.onFocus()
    }

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

    const handleRemoveDetail = function(key) {
      packageList.value.splice(key, 1)
    }
	
	// 禁用软键盘
	const handleInputFocus = function() {
		setTimeout(() => {
			uni.hideKeyboard()
		}, 100)
	}

    return {
      options: [{
        text: '删除',
        style: {
          backgroundColor: '#dd524d'
        }
      }],
      goHome,
      computedReadonlyText,
      easyinput,
      errorTip,
      errorTipMessage,
      modalForm,
      packageList,
	  handleInputFocus,
      scanNumber,
      handleMapass,
      handleKeydown,
      handleRemoveDetail,
      computedRemainder,
      handleCloseErrorTipsModal,
      hanleSplitLabelCode
    }
  }
})
</script>

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

	.list-content {
		margin-top: 80px;
		background-color: #edeeee;
	}

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

	.font-icons {
		width: 40px;
		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;
			}
		}
	}

	.card-list-flexbox {
		width: calc(100vw - 24px);
		height: 150px;
		margin: 0 12px;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		overflow-y: scroll;

		.card-list-title {
			width: 100%;
			height: 35px;
			line-height: 35px;
			margin: 0 4px 0 4px;
			border-radius: 4px 4px 0 0;
			text-align: center;
			color: white;
			background-color: rgba(0, 160, 233, 1.0);
		}

		.card-list-item,
		.card-list-item-operation {
			width: 100%;
			height: 35px;
			margin: 0 4px 3rpx 4px;
			border-radius: 4px;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			background-color: #fff;

			uni-text {
				font-size: 14px;
				height: 50rpx;
				text-align: left;
				padding: 0 8px;
				display: flex;
				flex-direction: row;
				align-items: center;
			}

			.text-1 {
				flex: 1;
				height: 35px;
				justify-content: flex-start;
			}

			.text-2 {
				flex: 3;
				height: 35px;
				justify-content: flex-end;
				margin-right: 4px;
				padding: 2px 6px;
			}

		}

	}

	.table-title {
		height: 40px;
		line-height: 40px;
		margin: 4px 0 0px 0;
		padding: 4px 12px;
		font-size: 16px;
		font-weight: bold;
		display: flex;
		border-bottom: 1px solid #dddddd;
		background-color: white;

		& view {
			flex: 1;
			display: flex;
		}
	}

	.c-button {
		display: flex;
		width: 40px;
		height: 30px;
		margin: 0 6px;
		border: 1px solid #c3c3c3;
		border-radius: 4px;
		justify-content: center;
		align-items: center;
		cursor: pointer;
	}

	.custom-table {
		height: calc(100vh - 265px);
		min-height: 230px;
		margin: 5px 0;
		overflow-y: scroll;
	}

	.operation-panel {
		padding: 0 0 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;
		}
	}

	.list-panel {
		margin-top: 6px;
		margin-bottom: 96px;
		padding: 5px 8px;
		overflow-y: scroll;
	}
</style>
