<template>
  <Dialog
    title="打印预览"
    v-model="dialogVisible"
    width="1000"
    top="0%"
    :before-close="(doClose) => beforeDialogClose(doClose)"
  >
    <el-button @click="outopen" style="float: right;margin-right: 0.5%;">取消</el-button>
    <el-button @click="onPrint" type="primary" style="float: right;margin-right: 1%;">打印</el-button>

    <!-- 打印预览 -->
    <div class="print-wrap page" ref="print">
      <div id="qrCodeContainer"></div>
    </div>
    <template #footer>
      <el-button @click="onPrint" type="primary">打印</el-button>
      <el-button @click="outopen">取消</el-button>
    </template>
  </Dialog>
        <printFinalDialog ref="printref" :minAmount="minAmount" :formData="formData" />
</template>

<script setup lang="ts">
import QRCode from 'qrcode'
import printFinalDialog from './printFinalDialog.vue';
const dialogVisible = ref(false)
let clauseId = null;
const startPageNum = ref(0);
const endPageNum = ref(0);
const printref = ref()
const onPrint = () => {
    printref.value.open(bomCodes.value,cnenList.value)
 
}
 
function beforeDialogClose(doClose: (shouldClose: boolean) => void): void {
  outopen()
}

const outopen = () => {
  dialogVisible.value = false
}

const printCodeName = ref([])
const datavals = ref([])
const specarr = ref([])
const cnenList = ref([])
const bomCodes = ref('')



const open = async (bomCode, vals) => {
 const sortedVals = [...vals].sort((a, b) => {
    const aParts = a.blueprintNo.split('-').map(part => parseInt(part) || part);
    const bParts = b.blueprintNo.split('-').map(part => parseInt(part) || part);

    // 逐段比较
    for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
      const aPart = aParts[i] || 0; // 如果某段不存在，视为 0
      const bPart = bParts[i] || 0;

      // 如果当前段是数字，按数字比较
      if (typeof aPart === 'number' && typeof bPart === 'number') {
        if (aPart !== bPart) return aPart - bPart;
      } 
      // 如果当前段是字符串，按字典序比较
      else {
        if (aPart !== bPart) return String(aPart).localeCompare(String(bPart));
      }
    }

    // 如果所有段都相同，按原始字符串比较
    return a.blueprintNo.localeCompare(b.blueprintNo);
  })

  cnenList.value = sortedVals;
  bomCodes.value = bomCode;
  specarr.value = []
  datavals.value = []
  printCodeName.value = []
  
  sortedVals.forEach((item) => {
    const row = {
      blueprintNo: item.blueprintNo,
    }
    const newName = `${bomCode}-${item.blueprintNo}`
    const row1 = {
      code: newName,
      name: item.materialName == null ? '' : item.materialName,
      amount: item.amount == null ? '' : item.amount
    }
    printCodeName.value.push(row1)
    datavals.value.push(row)
  })

  dialogVisible.value = true
  const currentDate = new Date()
  const formattedDate = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')} ${String(currentDate.getHours()).padStart(2, '0')}:${String(currentDate.getMinutes()).padStart(2, '0')}:${String(currentDate.getSeconds()).padStart(2, '0')}`
  var i = 0;
  await Promise.all(
    printCodeName.value.map(async (item) => {
      const qrCodeData = await QRCode.toDataURL(item.name,{
  errorCorrectionLevel: 'H' 
})
      const qrCodeElement = document.getElementById('qrCodeContainer')
      if (qrCodeElement) {
        (qrCodeElement.innerHTML +=
          `<div style="width: 90mm; height: 60mm; padding: 2mm; box-sizing: border-box; font-family: monospace; position: relative; background-color: black; color: white;">
            <div style="font-size: 11px; margin-bottom: 1mm;">
              <span style="display: inline-block; width: 100%; border-bottom: 1px solid white; padding-bottom: 0.2mm;">${item.code}</span>
            </div>
            <div style="display: flex; align-items: center;">
              <span style="white-space: nowrap; margin-right: 1mm;">名称:</span>
              <span style="flex-grow: 1; border-bottom: 1px solid white; height: 2em; margin-left: 1mm;">${item.name}</span>
            </div>
            <div style="display: flex; position: absolute; bottom: 2mm; left: 2mm; right: 2mm; height: 34mm;">
              <div style="display: flex; flex-direction: column; justify-content: center; align-items: flex-start; width: 13mm; margin-right: 1mm;">
                <span style="font-size: 11px; margin-bottom: 0.5mm; margin-top:2mm; white-space: nowrap;">数量: ${item.amount}</span>
                <span style="font-size: 5px; line-height: 1; margin-top: auto; white-space: nowrap;">${formattedDate}</span>
              </div>
              <div style="width: 34mm; height: 34mm; margin-left: auto; display: flex; align-items: flex-end; justify-content: flex-end;">
                <img style="width: 100%; height: 100%;" src="${qrCodeData}" alt="QR Code">
              </div>
            </div>
          </div>`)
                  if(printCodeName.value.length > 1 && i < printCodeName.value.length - 1){
        qrCodeElement.innerHTML += 
        `<div style="height:3mm; background-color: white; color: white;width:103mm;margin-left:-3mm">
            
          </div>`
       }
      }
    })
  )
}

defineExpose({ open })
</script>

<style scoped lang="scss">
/* 预览样式 - 仅用于屏幕显示 */
.page {
  width: 100mm;
  min-height: 60mm;
  margin: auto;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  background-color: black;
  color: white;
  padding: 2mm;
  box-sizing: border-box;
  
  /* 临时隐藏下划线，打印时会显示 */
  .code-line span, .name-underline {
    display: none;
  }
}

/* 确保打印样式优先 */
@media print {
  .page {
    background-color: black !important;
    color: white !important;
    
    .code-line span, .name-underline {
      display: inline-block;
    }
  }
}
</style>