<template>
  <el-container>
    <el-main>
      <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 :label="1">重打时提示，让我决定是否重打</el-radio>
              <div style="height: 8px"></div>
              <el-radio :label="2">重打时不提示，直接打印</el-radio>
              <div style="height: 8px"></div>
              <el-radio :label="3">重打时跳过，不打印</el-radio>
            </el-radio-group>
          </div>
          <div>号段范围：<el-input v-model="labelRange" style="width: 180px" readonly></el-input></div>
          <div>
            起始标签：
            <el-input v-model="startLabel" placeholder="请输入起始标签号" style="width: 180px" clearable></el-input>
          </div>
          <div>
            打印数量：
            <el-input-number v-model="printCount" :min="1" :max="100" type="number" placeholder="请输入打印数量" style="width: 180px" clearable></el-input-number>
          </div>
          <div>打印操作：<el-button type="primary" style="width: 180px" @click="begnPrint">开始打印</el-button></div>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

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

const windowSize = store.state.app.windowSize
const leftBoxStyle = {
  height: windowSize.h - 25 + 'px',
}

const labelRange = $ref(null)
const startLabel = $ref(null)
const printCount = $ref(1)
const excutable = $ref(false)
const reprintWarning = $ref(1)
const printedLabels = $ref([])
const begnPrint = async () => {
  if (!startLabel.startsWith('01180')) {
    ElMessageBox.alert('请输入正确的起始标签！', '提示', {
      type: 'error',
      confirmButtonText: '确定',
    }).then(() => {})
    return
  }
  excutable = true
  for (let i = 0; i < printCount; i++) {
    if (excutable) {
      const labelIndex = Number(startLabel.substring(5, startLabel.length)) + i
      if (labelIndex > 76000) {
        ElMessage({
          message: '打印完成。',
          type: 'success',
          duration: 2500,
          showClose: true,
        })
        return
      }
      const label = '01180' + labelIndex
      await executePrint(label)
        .then((res) => {
          console.log('printed:', res.label)
        })
        .catch((e) => {
          console.log('canceled: ' + e)
        })
    }
  }
}

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

const executeReprint = (origin, resolve) => {
  reprintLabel(origin).then((reprint) => {
    let found = false
    printedLabels.forEach((ele) => {
      if (ele.label === origin.label) {
        ele.reprint = 1
        found = true
        return
      }
    })
    if (!found) {
      printedLabels.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.ADD_PRINT_TEXT('10mm', '4mm', '30mm', '5mm', '泰和医院20人混采')
  LODOP.ADD_PRINT_TEXT('15mm', '4mm', '30mm', '5mm', label)
  LODOP.ADD_PRINT_BARCODE('9mm', '32mm', '17mm', '17mm', 'QRCode', label)
  //   LODOP.SET_PRINT_STYLE('FontSize', 18)
  //   LODOP.ADD_PRINT_TEXT('11mm', '6mm', '50mm', '5mm', '信息科-杜虎')
  LODOP.PRINT()
  //   LODOP.PREVIEW()
}

const endPrint = () => {
  excutable = false
}

onMounted(() => {
  initLodop()
  selectMaxLabelRange().then((origin) => {
    labelRange = origin.range
    startLabel = origin.advise
  })
})
</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;
      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>
