<template>
  <page-layer>
    <template #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>
            <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>
  </page-layer>
</template>

<script setup name="MixLabelPrinter">
import { selectLabelRanges, selectBeginLabel, selectLabelPrinter, printLabel, reprintLabel, allPrinted } 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'
import PageLayer from "@/layout/PageLayer";

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

let labelRanges = $ref([])
let labelTableName = $ref(null)
let currentLabelRange = $ref({})
let startLabel = $ref(null)
let printCount = $ref(1)
let reprintWarning = $ref(1)
let printedLabels = $ref([])
const textColor = computed(() => {
  return currentLabelRange.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 = begin
  })
  labelRanges.forEach((item) => {
    if (item.tableName === labelTableName) {
      currentLabelRange = item
      return
    }
  })
}

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

  selectBeginLabel(labelTableName).then((begin) => {
    if (begin) {
      startLabel = begin
    }
  })
}
const executePrint = (label) => {
  return new Promise((resolve, reject) => {
    selectLabelPrinter(labelTableName, label).then((origin) => {
      if (origin.status === 0) {
        printLabel(labelTableName, label).then((firstPrint) => {
          printedLabels.push(firstPrint)
          setTimeout(() => {
            drawQrcoce(firstPrint.label)
            lodopPrint(firstPrint.label)
            if (label === currentLabelRange.maxLabel) {
              allPrinted(labelTableName).then((msg) => {
                console.log(msg)
                resolve(firstPrint)
              })
            } else {
              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) => {
  origin.tableName = labelTableName
  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.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 = ranges
    if (ranges && ranges.length > 0) {
      for (let index = 0; index < ranges.length; index++) {
        const item = ranges[index]
        if (item.finishFlag === 0) {
          currentLabelRange = item
          labelTableName = item.tableName
          selectBeginLabel(item.tableName).then((begin) => {
            startLabel = 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>
