<template>
  <div class="main-wrapper">
    <div class="left" :style="leftBoxStyle">
      <div v-for="itm in printedLabels" :key="itm.label" style="margin: 0 8px 8px 0">
        <div class="label-box">
          <div class="label-text">
            <div>泰和医院20人混采</div>
            <div>
              {{ itm.label }}
              <el-tag v-if="itm.reprint === 1" type="warning">重打</el-tag>
            </div>
          </div>
          <div :id="itm.label + 'qrcode'"></div>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="reprint-box">
        <el-radio-group v-model="reprintWarning">
          <el-radio :value="1">重打时提示，让我决定是否重打</el-radio>
          <div style="height: 8px"></div>
          <el-radio :value="2">重打时不提示，直接打印</el-radio>
          <div style="height: 8px"></div>
          <el-radio :value="3">重打时跳过，不打印</el-radio>
        </el-radio-group>
      </div>
      <div>
        <span :style="{ color: textColor }">号段范围：</span>
        <el-select v-model="labelTableName" style="width: 200px" @change="handleLabelRangeChange">
          <el-option v-for="item in labelRanges" :key="item.tableName" :label="item.labelRange"
                     :value="item.tableName">
            <span v-html="analyzeFinishStatus(item.finishFlag)"></span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.labelRange }}</span>
          </el-option>
        </el-select>
      </div>
      <div>
        起始标签：
        <el-input v-model="startLabel" placeholder="请输入起始标签号" style="width: 200px" clearable></el-input>
      </div>
      <div>
        打印数量：
        <el-input-number v-model="printCount" :min="1" :max="100" type="number" placeholder="请输入打印数量"
                         style="width: 200px" clearable></el-input-number>
      </div>
      <div>打印操作：
        <el-button type="primary" style="width: 200px" @click="begnPrint">开始打印</el-button>
      </div>
    </div>
  </div>
</template>

<script setup name="MixLabelPrinter">
import {
  selectLabelRanges,
  selectBeginLabel,
  selectLabelPrinter,
  printLabel,
  reprintLabel,
  allPrinted
} from '@/api/mix-label-printer'
import {ElMessage, ElMessageBox} from 'element-plus'
import {qrcanvas} from 'qrcanvas'
import {initLodop, getLodop} from '@/utils/c-lodop'

const leftBoxStyle = {
  height: window.innerHeight - 25 + 'px',
}

const labelRanges = ref([])
const labelTableName = ref(null)
const currentLabelRange = ref({})
const startLabel = ref(null)
const printCount = ref(1)
const reprintWarning = ref(1)
const printedLabels = ref([])
const textColor = computed(() => {
  return currentLabelRange.value.finishFlag === 0 ? 'green' : 'red'
})

const analyzeFinishStatus = (val) => {
  return val === 0 ? '<span style="font-size:12px;color:green">未打完</span>' : '<span style="font-size:12px;color:red">已打完</span>'
}

const handleLabelRangeChange = (val) => {
  selectBeginLabel(val).then((begin) => {
    startLabel.value = begin
  })
  labelRanges.value.forEach((item) => {
    if (item.tableName === labelTableName.value) {
      currentLabelRange.value = item
      return
    }
  })
}

const begnPrint = async () => {
  if (!startLabel.value || startLabel.value.length < currentLabelRange.value.sliceIndex) {
    ElMessage({
      message: '请输入正确的起始标签！',
      type: 'error',
      duration: 2500,
      showClose: true,
    })
    return
  }
  printedLabels.value = []
  for (let i = 0; i < printCount.value; i++) {
    const labelIndex = Number(startLabel.value.substring(currentLabelRange.value.sliceIndex, startLabel.value.length)) + i
    if (labelIndex > currentLabelRange.value.endNumber) {
      ElMessage({
        message: '打印完成',
        type: 'success',
        duration: 2500,
        showClose: true,
      })
      return
    }
    const label = currentLabelRange.value.prefix + labelIndex
    await executePrint(label).then((res) => {}).catch((e) => {})
  }

  selectBeginLabel(labelTableName.value).then((begin) => {
    if (begin) {
      startLabel.value = begin
    }
  })
}
const executePrint = (label) => {
  return new Promise((resolve, reject) => {
    selectLabelPrinter(labelTableName.value, label).then((origin) => {
      if (origin.status === 0) {
        printLabel(labelTableName.value, label).then((firstPrint) => {
          printedLabels.value.push(firstPrint)
          setTimeout(() => {
            drawQrcoce(firstPrint.label)
            lodopPrint(firstPrint.label)
            if (label === currentLabelRange.value.maxLabel) {
              allPrinted(labelTableName.value).then((msg) => {
                resolve(firstPrint)
              })
            } else {
              resolve(firstPrint)
            }
          }, 100)
        })
      } else {
        if (reprintWarning.value === 3) {
          reject(label)
        } else if (reprintWarning.value === 2) {
          executeReprint(origin, resolve)
        } else if (reprintWarning.value === 1) {
          ElMessageBox.confirm(`标签【${label}】已打印过，确定要重新打印吗？`, '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(() => {
            executeReprint(origin, resolve)
          }).catch(() => {
            reject(label)
          })
        }
      }
    })
  })
}

const executeReprint = (origin, resolve) => {
  origin.tableName = labelTableName.value
  reprintLabel(origin).then((reprint) => {
    let found = false
    printedLabels.value.forEach((ele) => {
      if (ele.label === origin.label) {
        ele.reprint = 1
        found = true
        return
      }
    })
    if (!found) {
      printedLabels.value.push(reprint)
    }
    setTimeout(() => {
      document.getElementById(origin.label + 'qrcode').innerHTML = ''
      drawQrcoce(reprint.label)
      lodopPrint(reprint.label)
      resolve(reprint)
    }, 100)
  })
}

const drawQrcoce = (label) => {
  const labelCanvas = qrcanvas({
    data: label,
    size: 50,
  })
  document.getElementById(label + 'qrcode').appendChild(labelCanvas)
}

const lodopPrint = (label) => {
  const LODOP = getLodop()
  LODOP.PRINT_INIT('labels')
  LODOP.SET_PRINT_PAGESIZE(1, '50mm', '30mm', 'CreateCustomPage')
  LODOP.SET_PRINT_STYLE('Bold', 1)
  LODOP.ADD_PRINT_TEXT('8mm', '3mm', '32mm', '5mm', '泰和医院20人混采')
  LODOP.ADD_PRINT_BARCODE('14mm', '3mm', '32mm', '10mm', '128Auto', label)
  LODOP.ADD_PRINT_BARCODE('10mm', '35mm', '17mm', '17mm', 'QRCode', label)
  LODOP.PRINT()
}

onMounted(() => {
  initLodop()
  selectLabelRanges().then((ranges) => {
    labelRanges.value = ranges
    if (ranges && ranges.length > 0) {
      for (let index = 0; index < ranges.length; index++) {
        const item = ranges[index]
        if (item.finishFlag === 0) {
          currentLabelRange.value = item
          labelTableName.value = item.tableName
          selectBeginLabel(item.tableName).then((begin) => {
            startLabel.value = begin
          })
          return
        }
      }
    }
  })
})
</script>

<style lang="scss" scoped>
.main-wrapper {
  display: flex;
  padding: 12px;

  .left {
    width: 70%;
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;

    .label-box {
      width: 50mm;
      height: 30mm;
      background: white;
      display: flex;
      align-items: center;
      justify-content: center;

      .label-text {
        margin-right: 2mm;
        font-size: 12px;
        font-weight: bold;

        > div {
          padding: 1mm 0 1mm 0;
        }
      }
    }
  }

  .right {
    padding: 8px 0 0 30px;
    width: 30%;

    > div {
      margin-bottom: 8px;
    }

    .reprint-box {
      margin-bottom: 12px;
      background: white;
      width: 220px;
      padding: 12px;
      border-radius: 4px;
    }
  }
}
</style>
