<template>
  <ele-modal
    title="打码"
    :visible.sync="visible"
    v-if="visible"
    width="40%"
    :maxable="true"
    append-to-body
  >
    <div class="encoding-dialog">
      <div class="encoding-content">
        <div v-for="(item, index) in batchList" :key="index" class="batch-card">
          <div class="card-header">
            <span class="card-title">{{
              item.materialName || '产品标识卡'
            }}</span>
          </div>
          <div class="card-body">
            <div class="info-area">
              <div class="info-row">
                <span class="label">产品编码</span>
                <span class="value">{{ item.productCode || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">零(部)件编码</span>
                <span class="value">{{ item.materialCode || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">零(部)件名称</span>
                <span class="value">{{ item.materialName || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">本厂批次号</span>
                <span class="value">{{ item.batchNo || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">入库数量</span>
                <span class="value">{{ item.quantity || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">合格证号</span>
                <span class="value">{{ item.certificateNumber || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">原厂批号</span>
                <span class="value">{{ item.originalBatchNo || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">原厂合格证号</span>
                <span class="value">{{
                  item.originalCertificateNumber || '-'
                }}</span>
              </div>
            </div>
            <div class="qr-area">
              <div class="qr-box">
                <img
                  v-if="item.qrCodeUrl"
                  :src="item.qrCodeUrl"
                  alt="二维码"
                  class="qr-img"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div slot="footer">
      <el-button size="small" @click="printPreview">打印预览</el-button>
      <el-button size="small" @click="close">关闭</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import QRCode from 'qrcode';

  export default {
    name: 'EncodingDialog',
    data() {
      return {
        visible: false,
        dataList: [],
        batchList: []
      };
    },
    methods: {
      open(data) {
        this.visible = true;
        this.dataList = Array.isArray(data) ? data : [data];
        this.buildBatchList();
      },

      close() {
        this.visible = false;
        this.batchList = [];
      },

      buildBatchList() {
        this.batchList = this.dataList.map((item) => ({
          productCode: item.productCode || '',
          materialCode: item.categorycodes || '',
          materialName: item.categoryNames || '',
          batchNo: item.batchNo || '',
          quantity: item.chNo || '',
          originalBatchNo: item.originalBatchNo || '',
          certificateNumber: item.certificateNumber || '',
          originalCertificateNumber: item.originalCertificateNumber || '',
          codeStr: [
            item.productCode,
            item.categorycodes,
            item.categoryNames,
            item.batchNo,
            item.chNo,
            item.originalBatchNo,
            item.certificateNumber,
            item.originalCertificateNumber
          ]
            .filter(Boolean)
            .join(';'),
          qrCodeUrl: ''
        }));

        this.generateQRCodes();
      },

      generateQRCodes() {
        this.batchList.forEach((item, index) => {
          const content = item.codeStr || item.productCode || String(index);
          QRCode.toDataURL(content, { width: 240, margin: 1 })
            .then((url) => {
              this.$set(this.batchList[index], 'qrCodeUrl', url);
            })
            .catch((err) => {
              console.error('QRCode生成失败:', err);
            });
        });
      },

      refresh() {
        this.buildBatchList();
      },

      printPreview() {
        const printContent = this.$el.querySelector('.encoding-content');
        if (!printContent) return;

        const html = printContent.innerHTML;

        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
          <html>
            <head>
              <title>打码打印预览</title>
              <style>
                @page {
                  size: 100mm 80mm;
                  margin: 0;
                }
                * { box-sizing: border-box; margin: 0; padding: 0; }
                html, body {
                  font-family: 'Microsoft Yahei', Arial, sans-serif;
                  width: 100mm;
                  margin: 0;
                  padding: 0;
                  color: #1f2329;
                  -webkit-print-color-adjust: exact;
                  print-color-adjust: exact;
                }
                .encoding-content { width: 100mm; }
                .batch-card {
                  width: 100mm;
                  height: 80mm;
                  padding: 2.5mm;
                  page-break-after: always;
                  page-break-inside: avoid;
                  break-inside: avoid;
                  overflow: hidden;
                  display: flex;
                  flex-direction: column;
                }
                .batch-card:last-child { page-break-after: avoid; }
                .batch-card > .card-header,
                .batch-card > .card-body {
                  width: 100%;
                }
                .card-header {
                  min-height: 8mm;
                  background: #1f2329;
                  color: #fff;
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 1mm 3mm;
                  border-radius: 1mm 1mm 0 0;
                  flex-shrink: 0;
                }
                .card-header .card-title {
                  flex: 1;
                  font-size: 9pt;
                  font-weight: 700;
                  letter-spacing: 0.3mm;
                  line-height: 1.3;
                  word-break: break-all;
                }
                .card-body {
                  flex: 1;
                  border: 1px solid #000;
                  border-top: none;
                  border-radius: 0 0 1mm 1mm;
                  display: flex;
                  align-items: stretch;
                  overflow: hidden;
                }
                .info-area {
                  flex: 1;
                  display: flex;
                  flex-direction: column;
                  border-right: 1px solid #000;
                }
                .info-row {
                  flex: 1;
                  display: flex;
                  align-items: center;
                  border-bottom: 1px dashed #c0c4cc;
                  padding: 0 2mm;
                  min-height: 0;
                }
                @media print {
                  .info-row {
                    border-bottom: none;
                    background-image: linear-gradient(
                      to right,
                      #000 50%,
                      transparent 50%
                    );
                    background-size: 2px 1px;
                    background-repeat: repeat-x;
                    background-position: left bottom;
                  }
                  .info-row:last-child { background-image: none; }
                }
                .info-row:last-child { border-bottom: none; }
                .info-row .label {
                  width: 18mm;
                  font-size: 8pt;
                  color: #606266;
                  flex-shrink: 0;
                  line-height: 1.2;
                  height: 100%;
                  display: flex;
                  align-items: center;
                  background-image: linear-gradient(
                    to bottom,
                    #000 50%,
                    transparent 50%
                  );
                  background-size: 1px 2px;
                  background-repeat: repeat-y;
                  background-position: right top;
                }
                .info-row .value {
                  flex: 1;
                  font-size: 8pt;
                  font-weight: 600;
                  color: #1f2329;
                  word-break: break-all;
                  line-height: 1.2;
                  padding-left: 2mm;
                }
                .qr-area {
                  width: 32mm;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  padding: 1.5mm;
                  background: #fafbfc;
                }
                .qr-box {
                  width: 28mm;
                  height: 28mm;
                  padding: 1mm;
                  background: #fff;
                  border: 1px solid #000;
                  border-radius: 0.8mm;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                }
                .qr-img { width: 100%; height: 100%; }
              </style>
            </head>
            <body>${html}</body>
          </html>
        `);
        printWindow.document.close();
        printWindow.onload = function () {
          setTimeout(() => {
            printWindow.print();
          }, 300);
        };
      }
    }
  };
</script>

<style lang="scss" scoped>
  .encoding-dialog {
    .encoding-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      gap: 10px;
    }

    .encoding-content {
      max-height: 60vh;
      overflow-y: auto;
    }

    .batch-card {
      margin-bottom: 16px;
      border-radius: 6px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid #ebeef5;
      background: #fff;

      .card-header {
        min-height: 40px;
        background: linear-gradient(90deg, #1f2329 0%, #2c3138 100%);
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 16px;

        .card-title {
          flex: 1;
          font-size: 15px;
          font-weight: 600;
          letter-spacing: 1px;
          line-height: 1.4;
          word-break: break-all;
        }

        .card-sub {
          flex-shrink: 0;
          margin-left: 12px;
          font-size: 12px;
          opacity: 0.75;
          letter-spacing: 2px;
        }
      }

      .card-body {
        display: flex;
        align-items: stretch;
      }

      .info-area {
        flex: 1;
        display: flex;
        flex-direction: column;
        border-right: 1px dashed #dcdfe6;
      }

      .info-row {
        flex: 1;
        display: flex;
        align-items: center;
        padding: 10px 14px;
        border-bottom: 1px solid #f2f3f5;
        min-height: 38px;

        &:last-child {
          border-bottom: none;
        }

        .label {
          width: 110px;
          font-size: 13px;
          color: #909399;
          flex-shrink: 0;
        }

        .value {
          flex: 1;
          font-size: 14px;
          color: #1f2329;
          font-weight: 500;
          word-break: break-all;
        }
      }

      .qr-area {
        width: 160px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 12px;
        background: #fafbfc;

        .qr-box {
          width: 124px;
          height: 124px;
          padding: 6px;
          background: #fff;
          border: 1px solid #ebeef5;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;

          .qr-img {
            width: 100%;
            height: 100%;
          }
        }

        .qr-tip {
          margin-top: 8px;
          font-size: 12px;
          color: #909399;
          letter-spacing: 1px;
        }
      }
    }
  }
</style>
