<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="card-list-flexbox">
          <text class="card-list-title" :style="[isPad?'font-size: 18px':'font-size: 14px']">批次内容</text>
          <view class="card-list-item">
            <text>料号</text>
            <text>{{ paramsDetail.erpMaterialNo }}</text>
          </view>
          <view class="card-list-item">
            <text>批号</text>
            <text>{{ paramsDetail.batchNumber }}</text>
          </view>
          <view class="card-list-item">
            <text>件数</text>
            <text>{{ paramsDetail.qty }}</text>
          </view>
        </view>
        <view class="table-title">
          <view><text style="font-size: 16px;">拆分列表</text></view>
          <view class="">
            <text class="c-button" @click="handleAddPackage">新增项</text>
          </view>
        </view>
        <view class="split-list">
          <!-- eslint-disable-next-line vue/valid-v-for -->
          <view v-for="(item, key) in packageList" v-key="key">
            <uni-swipe-action>
              <!-- 基础用法 -->
              <uni-swipe-action-item :right-options="options" @click="handleRemoveDetail(key)">
                <template #left>
                  <view />
                </template>
                <div class="split-list-item">
                  <text>第{{ key + 1 }}条</text>
                  <input v-model="item.num" type="digit">
                  <text>PCS</text>
                </div>
              </uni-swipe-action-item>
            </uni-swipe-action>
          </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="paramsDetail.qty <= 0? 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 paramsDetail = ref({
      batchNumber: '-',
      erpMaterialNo: '-',
      qty: 0
    })
    const packageList = ref([{
      index: 1,
      num: ''
    }])
    const blueConfig = ref({
      loopBuffer: 0,
      currentTime: 1,
      lastData: 0,
      onBufferSize: 20,
      printerNum: 1,
      currentPrint: 1,
      isLabelSend: false
    })

    const countRemainder = function() {
      let remainder = 0
      for (let i = 0; i < packageList.value.length; i++) {
        remainder = add(packageList.value[i].num, remainder)
      }
      return remainder
    }

    const computedRemainder = computed(() => {
      const remainder = countRemainder()
      return paramsDetail.value.qty - remainder
    })

    const computedReadonlyText = computed(() => {
      const remainder = countRemainder()
      return paramsDetail.value.qty - remainder < 0 ? '余数不正确' : ''
    })

    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 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) {
                Object.assign(paramsDetail.value, 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) {
            Object.assign(paramsDetail.value, data)
            setInputFocus()
          } 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() {
      let list = []
      const subBatchVOList = []
      packageList.value.forEach(ret => {
        if (ret.num) {
          subBatchVOList.push({
            qty: ret.num
          })
        }
      })
      uni.$reqPost('batchQrCodeSplit', {
        batchNumber: paramsDetail.value.batchNumber,
        subBatchVOList
      })
        .then(async({
          code,
          data,
          msg
        }) => {
          if (code === 0) {
            list = data
            if (list.length > 0) {
              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)
            }
            paramsDetail.value = {
              batchNumber: '-',
              erpMaterialNo: '-',
              qty: 0
            }
            packageList.value = [{
              index: 1,
              num: ''
            }]
            setInputFocus()
          } else {
            // #ifdef APP-PLUS
            plus.device.beep(2)
            // #endif
            errorTipMessage.value = msg
            errorTip.value.open()
            errorState.value = 0
          }
        })
    }

    const handleAddPackage = function() {
      packageList.value.push({
        index: packageList.value.length,
        num: ''
      })
    }

    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) {
      if (packageList.value.length === 1) {
        // #ifdef APP-PLUS
        plus.device.beep(2)
        // #endif
        errorTipMessage.value = '最少保留一条'
        errorTip.value.open()
        errorState.value = -1
      }
      if (packageList.value.length > 1) {
        packageList.value.splice(key, 1)
      }
    }
	
	// 禁用软键盘
	const handleInputFocus = function() {
		setTimeout(() => {
			uni.hideKeyboard()
		}, 100)
	}

    return {
      options: [{
        text: '删除',
        style: {
          backgroundColor: '#dd524d'
        }
      }],
      goHome,
      paramsDetail,
      easyinput,
      errorTip,
      errorTipMessage,
      modalForm,
      packageList,
      scanNumber,
      handleMapass,
      handleKeydown,
	  handleInputFocus,
      computedRemainder,
      computedReadonlyText,
      handleAddPackage,
      handleRemoveDetail,
      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);
		min-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%;
			min-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;

			& text:nth-of-type(1) {
				min-width: 40px;
			}

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

		}

	}

	.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;
		}

		& view:nth-of-type(2) {
			justify-content: end;
			align-items: center;
		}
	}

	.c-button {
		display: flex;
		width: 60px;
		height: 30px;
		border: 1px solid #55aaff;
		border-radius: 4px;
		box-shadow: 2px 2px 2px 1px #dddddd;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		color: white;
		background-color: rgb(0, 160, 233);
	}

	.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;
		}
	}

	.split-list {
		min-height: 460px;
		padding: 0 14px;
		margin-bottom: 96px;
		background-color: white;

		.split-list-item {
			height: 60px;
			line-height: 60px;
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;

			text:nth-of-type(1) {
				font-size: 14px;
				text-align: left;
			}

			input:nth-of-type(1) {
				width: 70% !important;
				height: 40px;
				border-bottom: 1px dotted gray;
			}

			text:nth-of-type(2) {
				font-size: 14px;
				text-align: right;
				margin-right: 4px;
			}
		}

	}
</style>
