<template>
  <ele-modal
    title="入库单"
    :visible.sync="QRvisible"
    v-if="QRvisible"
    width="1100px"
    @close="close"
  >
    <div id="printSectionHt">
      <div
        v-for="(rowItem, idx) in formData"
        :key="rowItem.id || idx"
        style="
          font-family: SimSun, serif;
          padding: 20px;
          width: 24cm;
          min-height: 14cm;
          margin: 0 auto;
          box-sizing: border-box;
          page-break-after: always;
        "
      >
        <!-- 入库单标题 -->
        <div style="text-align: center; margin-bottom: 20px;">
          <h2 style="margin: 0; font-size: 24px; font-weight: bold;">{{ groupName }}入库单</h2>
        </div>
        
        <!-- 供应商/客户信息 -->
        <div style="margin-bottom: 20px; width: 100%;">
          <div style="width: 100%; display: flex;">
            <div style="width: 40%;">
              供应商名称：{{ rowItem.supplierNames || '' }}
            </div>
            <div style="width: 30%;">
              日期：{{ rowItem.storageTime || '' }}
            </div>
            <div style="width: 30%;">
              编号：{{ rowItem.bizNo || '' }}
            </div>
          </div>
        </div>
        
        <!-- 入库物品表格 -->
        <table
          border="1"
          cellspacing="0"
          style="
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
          "
        >
          <thead>
            <tr>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 5%;">编号</th>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 20%;">型号规格</th>
              <th v-if="rowItem.bizType == 6" style="border: 1px solid #000; padding: 4px; text-align: center; width: 12%;">客户</th>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 8%;">颜色</th>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 8%;">单位</th>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 8%;">入库数量</th>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 10%;">批次号</th>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 8%;">单价</th>
              <th style="border: 1px solid #000; padding: 4px; text-align: center; width: 10%;">金额</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in rowItem.outInDetailList" :key="index">
              <td style="border: 1px solid #000; padding: 4px; text-align: center;">{{ index + 1 }}</td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;">{{row.categoryModel || '' }}{{ row.categoryModel && row?.specification ? '/' : '' }}{{ row?.specification || '' }}</td>
              <td v-if="rowItem.bizType == 6" style="border: 1px solid #000; padding: 4px; text-align: center;">{{ rowItem?.clientName || '' }}</td> 
              <td style="border: 1px solid #000; padding: 4px; text-align: center;">{{ row?.colorKey || '' }}</td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;">{{ row?.measureUnit || '' }}</td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;">{{ row?.measureQuantity || '' }}</td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;">{{ row?.batchNo || '' }}</td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
            </tr>
            
            <!-- 合计行 -->
            <tr>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;" colspan="2">合计：</td>
              <td v-if="rowItem.bizType == 6" style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;">{{ getTotalAmount(rowItem) }}</td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
              <td style="border: 1px solid #000; padding: 4px; text-align: center;"></td>
            </tr>
          </tbody>
        </table>
        
        <!-- 签字区域 -->
        <div style="margin-top: 20px; display: flex; width: 100%;">
          <div style="width: 25%;">
            <strong>主管：</strong>{{ rowItem.verifyName || '' }}
          </div>
          <div style="width: 25%;">
            <strong>仓库：</strong>{{ warehouseMap[rowItem.id] || '' }}
          </div>
          <div style="width: 25%;">
            <strong>记账：</strong>{{ rowItem.extInfo?.createUserName || '' }}
          </div>
          <div style="width: 25%;">
            <strong>经手人：</strong>{{ rowItem?.fromUser || '' }}
          </div>
        </div>
      </div>
    </div>

    <div slot="footer">
      <el-button type="primary" @click="exportExcel">导出</el-button>
      <el-button @click="print">打印预览</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import storageApi from '@/api/warehouseManagement';
  import { saveAs } from 'file-saver';
  export default {
    name: 'print',
    components: {},
    props: {
      groupName: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        QRvisible: false,
        formData: [],
        warehouseMap: {}
      };
    },

    methods: {
      // 计算单个入库单的总数量
      getTotalAmount(rowItem) {
        if (!rowItem?.outInDetailList || !Array.isArray(rowItem.outInDetailList)) {
          return 0;
        }
        return rowItem.outInDetailList.reduce((sum, row) => {
          const amount = parseFloat(row.measureQuantity || 0);
          return sum + (isNaN(amount) ? 0 : amount);
        }, 0);
      },

      async init(ids, rows) {
        console.log('ids~~', ids, rows);
        // 批量获取每个入库单的详情
        const res = await storageApi.getInboundDetailsByIds(ids);
        res.map(item => {
          item.supplierNames = [...new Set(item.outInDetailList.map(row => row.supplierName || ''))].join(',');
          return item
        })
        this.formData = res;

        // 构建仓库映射
        this.warehouseMap = {};
        rows.forEach((row) => {
          this.warehouseMap[row.id] = row.warehouseName || '';
        });

        console.log('formData', this.formData, this.warehouseMap);
        this.QRvisible = true;
      },

      close() {
        this.formData = [];
        this.warehouseMap = {};
        this.QRvisible = false;
      },
      
      print() {
        const printSection = document.getElementById('printSectionHt');
        
        // 创建打印任务
        const printWindow = window.open('', '_blank');
        printWindow.document.open();
        printWindow.document.write('<html><head><title>打印预览</title>');
        printWindow.document.write(
          '<style type="text/css">' +
          '@page { size: 24cm 14cm; margin: 0; }' +
          'body { margin: 0; padding: 0; }' +
          'div[style*="page-break-after"] { page-break-after: always; }' +
          '</style>'
        );
        printWindow.document.write('</head><body>');
        printWindow.document.write(printSection.innerHTML);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.onload = function () {
          printWindow.print();
        };
      },

      exportExcel() {
        const border =
          'border-top:1px solid #000;border-right:1px solid #000;border-bottom:1px solid #000;border-left:1px solid #000;';
        const cellBase = `${border}padding:4px;mso-number-format:"\\@";vertical-align:middle;text-align:center;mso-horizontal-align:center;`;
        const th = `${cellBase}font-weight:bold;font-family:'宋体';font-size:12pt;`;
        const td = `${cellBase}font-family:'宋体';font-size:11pt;`;
        const labelLeft = `${border}padding:4px;mso-number-format:"\\@";vertical-align:middle;text-align:left;mso-horizontal-align:left;font-family:'宋体';font-size:11pt;`;

        const title = `${this.groupName || ''}入库单`;

        // 遍历多个单据生成多个表格
        let tables = '';
        this.formData.forEach((rowItem) => {
          const list = rowItem.outInDetailList || [];
          const totalAmount = this.getTotalAmount(rowItem);
          const warehouseName = this.warehouseMap[rowItem.id] || '';
          const isBizType6 = rowItem.bizType == 6;
          const supplierValue = rowItem.supplierNames || '';

          const totalCols = isBizType6 ? 9 : 8;
          const colWidths = isBizType6
            ? [55, 200, 100, 70, 70, 70, 80, 70, 80]
            : [55, 200, 70, 70, 70, 80, 70, 80];
          const colGroup = colWidths
            .map((w) => `<col width="${w}" style="width:${w}pt;" />`)
            .join('');

          const customerTh = isBizType6
            ? `<td align="center" valign="middle" style="${th}">客户</td>`
            : '';

          const rows = list
            .map(
              (item, index) => `
              <tr height="24" style="height:24pt;">
                <td align="center" valign="middle" style="${td}">${index + 1}</td>
                <td align="center" valign="middle" style="${td}">${item.categoryModel || ''}${item.categoryModel && item.specification ? '/' : ''}${item.specification || ''}</td>
                ${isBizType6 ? `<td align="center" valign="middle" style="${td}">${rowItem?.clientName || ''}</td>` : ''}
                <td align="center" valign="middle" style="${td}">${item.colorKey || ''}</td>
                <td align="center" valign="middle" style="${td}">${item.measureUnit || ''}</td>
                <td align="center" valign="middle" style="${td}">${item.measureQuantity || ''}</td>
                <td align="center" valign="middle" style="${td}">${item.batchNo || ''}</td>
                <td align="center" valign="middle" style="${td}"></td>
                <td align="center" valign="middle" style="${td}"></td>
              </tr>`
            )
            .join('');

          const customerEmpty = isBizType6
            ? '<td align="center" valign="middle" style="${td}"></td>'
            : '';

          tables += `
          <table border="1" cellspacing="0" cellpadding="0" align="center"
            style="border-collapse:collapse;border:1px solid #000;mso-border-alt:solid #000 0.5pt;font-family:'宋体';font-size:11pt;text-align:center;">
            <colgroup>${colGroup}</colgroup>
            <tr height="40" style="height:40pt;">
              <td colspan="${totalCols}" align="center" valign="middle" style="${border}padding:6px;text-align:center;font-family:'宋体';font-size:22pt;font-weight:bold;">${title}</td>
            </tr>
            <tr height="26" style="height:26pt;">
              <td colspan="${isBizType6 ? 3 : 3}" align="left" valign="middle" style="${labelLeft}">供应商名称：${supplierValue}</td>
              <td align="left" valign="middle" style="${labelLeft}">日期：${rowItem.storageTime || ''}</td>
              <td colspan="${isBizType6 ? 3 : 2}" align="left" valign="middle" style="${labelLeft}">编号：${rowItem.bizNo || ''}</td>
            </tr>
            
            <tr height="28" style="height:28pt;">
              <td align="center" valign="middle" style="${th}">编号</td>
              <td align="center" valign="middle" style="${th}">型号规格</td>
              ${customerTh}
              <td align="center" valign="middle" style="${th}">颜色</td>
              <td align="center" valign="middle" style="${th}">单位</td>
              <td align="center" valign="middle" style="${th}">入库数量</td>
              <td align="center" valign="middle" style="${th}">批次号</td>
              <td align="center" valign="middle" style="${th}">单价</td>
              <td align="center" valign="middle" style="${th}">金额</td>
            </tr>
            ${rows}
            <tr height="26" style="height:26pt;">
              <td colspan="2" align="center" valign="middle" style="${td};font-weight:bold;">合计：</td>
              ${customerEmpty}
              <td align="center" valign="middle" style="${td}"></td>
              <td align="center" valign="middle" style="${td}"></td>
              <td align="center" valign="middle" style="${td};font-weight:bold;">${totalAmount}</td>
              <td align="center" valign="middle" style="${td}"></td>
              <td align="center" valign="middle" style="${td}"></td>
              <td align="center" valign="middle" style="${td}"></td>
            </tr>
            <tr height="28" style="height:28pt;">
              <td align="left" valign="middle" style="${labelLeft}">主管：${rowItem.verifyName || ''}</td>
              <td align="left" valign="middle" style="${labelLeft}">仓库：${warehouseName}</td>
              <td align="left" valign="middle" style="${labelLeft}">记账：${rowItem.extInfo?.createUserName || ''}</td>
              <td colspan="${isBizType6 ? 6 : 5}" align="left" valign="middle" style="${labelLeft}">经手人：${rowItem.fromUser || ''}</td>
            </tr>
          </table>
          <br style="mso-special-character:line-break;page-break-before:always" />`;
        });

        const html = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
        <head>
        <meta charset="UTF-8" />
        <style>
          br { mso-data-placement: same-cell; }
          table { mso-displayed-decimal-separator:"."; mso-displayed-thousand-separator:","; }
          td { mso-ignore:padding; }
        </style>
        <!--[if gte mso 9]><xml>
        <x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${title}</x:Name>
        <x:WorksheetOptions>
          <x:DefaultRowHeight>260</x:DefaultRowHeight>
          <x:Print><x:ValidPrinterInfo/><x:HorizontalResolution>600</x:HorizontalResolution><x:VerticalResolution>600</x:VerticalResolution></x:Print>
          <x:Selected/>
          <x:DoNotDisplayGridlines/>
        </x:WorksheetOptions>
        </x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>
        </xml><![endif]-->
        </head>
        <body>${tables}</body></html>`;

        const blob = new Blob(['\uFEFF' + html], {
          type: 'application/vnd.ms-excel;charset=utf-8'
        });
        const firstBizNo = this.formData[0]?.bizNo || '';
        const suffix = this.formData.length > 1 ? `等${this.formData.length}条` : firstBizNo;
        saveAs(blob, `${title}_${suffix}.xls`);
      }
    }
  };
</script>

<style scoped lang="scss">
  table {
    border-collapse: collapse;
  }
  th, td {
    border: 1px solid #000;
    text-align: center;
    padding: 8px;
  }
  @media print {
    .no-print {
      display: none;
    }
  }
</style>
