<template>
  <ele-modal
    title="入库单"
    :visible.sync="QRvisible"
    v-if="QRvisible"
    width="80%"
  >
    <div
      id="printSection"
      style="
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
      "
    >
      <div
        style="
          text-align: center;
          font-size: 20px;
          font-weight: 800;
          text-decoration: underline;
          margin-bottom: 10px;
        "
        >{{ groupName + '入库单' || '湖南万隆智能科技有限公司采购入库单' }}</div
      >
      <div
        style="
          display: flex;
          justify-content: space-between;
          width: 100%;
          min-width: 800px; 
          margin-bottom: 10px;
          font-size: 13px;
        "
      >
        <span style="flex: 2; white-space: nowrap; padding-right: 10px"
          >供应商：{{ formData.supplierName }}</span
        >
        <span style="flex: 1; white-space: nowrap; padding: 0 10px"
          >日期：{{ formData.receiveDate }}</span
        >
        <span style="flex: 2; white-space: nowrap; padding-left: 10px"
          >编号：{{ formData.receiveNo }}</span
        >
      </div>
      <div
        style="
          display: flex;
          justify-content: space-between;
          width: 100%;
          margin-bottom: 10px;
          font-size: 13px;
        "
      >
        <span style="flex: 1">摘要：</span>
      </div>
      <table
        cellspacing="0"
        border
        style="
          width: 100%;
          table-layout: fixed;
          word-break: break-all;
          word-wrap: break-word;
          font-size: 12px;
          margin-bottom: 10px;
        "
      >
        <tbody>
          <tr align="center">
            <td style="padding: 5px" width="50px"> 编号 </td>
            <td style="padding: 5px"> 物料编码 </td>
            <td style="padding: 5px"> 物料名称 </td>
            <td style="padding: 5px">规格型号 </td>
            <td style="padding: 5px">单位 </td>
            <td style="padding: 5px"> 数量</td>
            <td style="padding: 5px"> 单价</td>
            <td style="padding: 5px"> 金额</td>
            <td style="padding: 5px"> 批次号</td>
            <td style="padding: 5px"> 备注</td>
          </tr>

          <tr align="center" v-for="(item, index) in formData?.productList">
            <td style="padding: 5px"> {{ index + 1 }} </td>
            <td style="padding: 5px"> {{ item.productCode }} </td>
            <td style="padding: 5px"> {{ item.productName }} </td>
            <td style="padding: 5px">
              {{ item.specification || ''
              }}{{ item.modelType ? '/' + item.modelType : '' }}
            </td>
            <td style="padding: 5px"> {{ item.measuringUnit }}</td>
            <td style="padding: 5px"> {{ item.totalCount }}</td>
            <td style="padding: 5px"> {{ item.singlePrice }}</td>
            <td style="padding: 5px"> {{ item.totalPrice }}</td>
            <td style="padding: 5px"> {{ item.batchNo }}</td>
            <td style="padding: 5px"> {{ item.remark }}</td>
          </tr>
          <tr align="center">
            <td style="padding: 5px" colspan="2">合计 </td>
            <td style="padding: 5px; text-align: left;" colspan="8">
              <div style="display: flex;">
                <span style="flex: 1"
                  >本页数量小计：{{ this.getAll('totalCount') }}</span
                >
                <span style="flex: 1"
                  >本页金额小计：{{ this.getAll('totalPrice') }}</span
                >
                <span style="flex: 1"
                  >汇总数量：{{ this.getAll('totalCount') }}</span
                >
                <span style="flex: 1"
                  >汇总金额：{{ this.getAll('totalPrice') }}</span
                >
              </div>
            </td>
          </tr>
          <tr align="center">
            <td style="padding: 5px" colspan="2">合计金额（大写金额） </td>
            <td style="padding: 5px; text-align: left;" colspan="8">
              <div style="display: flex; margin-top: 6px;">
                <span style="flex: 1"
                  >{{ convertToChinese(getAll('totalPrice')) }}</span
                >
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <div style="display: flex; justify-content: space-between; width: 100%; font-size: 13px;">
        <span style="flex: 1">收货单审核人：{{formData.reviewerName}}</span>
        <span style="flex: 1">采购发起人：{{formData.purchaseInitiatorName}}</span>
        <span style="flex: 1">质检人：{{formData.qualityName}}</span>
        <span style="flex: 1">仓管员：{{formData.warehouseKeeperName}}</span>
        <!-- <span style="flex: 1">采购收货发起人：{{ formData.purchaseInitiatorName }}</span> -->
      </div>
    </div>
    <div slot="footer">
      <el-button @click="exportExcel">导出</el-button>
      <el-button @click="print">打印预览</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </ele-modal>
</template>

<script>
import { getReceiveSaleOrderrecordDetail } from '@/api/purchasingManage/purchaseorderreceive';
import { formatPrice } from '@/BIZComponents/setProduct.js';
import { mapGetters } from 'vuex';
import { saveAs } from 'file-saver';
import { convertToChinese } from '@/utils/util';
export default {
  name: 'print',
  computed: {
    ...mapGetters(['user'])
  },
  props: {
    groupName: ''
  },
  data() {
    return {
      QRvisible: false,
      formData: {}
    };
  },

  methods: {
    convertToChinese,
    numToChinese(num) {
      console.log('num~~~', num);
    const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];
    const decimalUnits = ['角', '分'];

    num = Number(num).toFixed(2); 
    const [integerStr, decimalStr] = num.split('.');
    let result = '';

    const integerLen = integerStr.length;
    if (integerLen === 0 || (integerLen === 1 && integerStr === '0')) {
      result += '零元';
    } else {
      for (let i = 0; i < integerLen; i++) {
        const digit = parseInt(integerStr[i]);
        const unitIndex = integerLen - 1 - i; 

        if (digit === 0) {
          if (i < integerLen - 1 && parseInt(integerStr[i + 1]) !== 0) {
            result += '零';
          }
        } else {
          if (!(unitIndex === 1 && digit === 1 && i === 0)) {
            result += digits[digit];
          }
          result += units[unitIndex];
        }
      }
      result += '元'; 
    }

    const jiao = parseInt(decimalStr[0]);
    const fen = parseInt(decimalStr[1]);
    if (jiao === 0 && fen === 0) {
      result += '整'; 
    } else {
      if (jiao !== 0) result += digits[jiao] + decimalUnits[0]; 
      if (fen !== 0) result += digits[fen] + decimalUnits[1]; 
    }

    return result;
  },
    async open(id) {
      this.formData = await getReceiveSaleOrderrecordDetail(id);
      this.QRvisible = true;
    },
    close() {
      this.QRvisible = false;
    },
    getAll(key) {
      let num = 0;
      this.formData.productList.forEach((item) => {
        if (item[key]) {
          num += Number(item[key]);
        }
      });
      return num ? formatPrice(num) : '';
    },
    print() {
      const printSection = document.getElementById('printSection');
      // 创建打印任务
      const printWindow = window.open('', '_blank');
      printWindow.document.open();
      printWindow.document.write('<html><head><title>打印预览</title>');
      printWindow.document.write(
        '<link rel="stylesheet" href="your-stylesheet-url.css" type="text/css" />'
      );
      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 list = this.formData?.productList || [];
      const totalCount = this.getAll('totalCount');
      const totalPrice = this.getAll('totalPrice');

      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 colWidths = [50, 100, 120, 100, 60, 80, 90, 100, 80, 120];
      const colGroup = colWidths.map((w) => `<col width="${w}" style="width:${w}pt;" />`).join('');

      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.productCode || ''}</td>
          <td align="center" valign="middle" style="${td}">${item.productName || ''}</td>
          <td align="center" valign="middle" style="${td}">${item.specification || ''}${item.modelType ? '/' + item.modelType : ''}</td>
          <td align="center" valign="middle" style="${td}">${item.measuringUnit || ''}</td>
          <td align="center" valign="middle" style="${td}">${item.totalCount ?? ''}</td>
          <td align="center" valign="middle" style="${td}">${item.singlePrice ?? ''}</td>
          <td align="center" valign="middle" style="${td}">${item.totalPrice ?? ''}</td>
          <td align="center" valign="middle" style="${td}">${item.batchNo || ''}</td>
          <td align="center" valign="middle" style="${td}">${item.remark || ''}</td>
        </tr>`).join('');

      const title = `${this.groupName || ''}入库单`;
      const table = `
        <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="10" 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="4" align="left" valign="middle" style="${labelLeft}">供应商：${this.formData.supplierName || ''}</td>
            <td colspan="3" align="left" valign="middle" style="${labelLeft}">日期：${this.formData.receiveDate || ''}</td>
            <td colspan="3" align="left" valign="middle" style="${labelLeft}">编号：${this.formData.receiveNo || ''}</td>
          </tr>
          <tr height="26" style="height:26pt;">
            <td colspan="10" align="left" valign="middle" style="${labelLeft}">摘要：</td>
          </tr>
          <tr height="28" style="height:28pt;">
            <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>
            <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 align="center" valign="middle" style="${td};font-weight:bold;">合计</td>
            <td colspan="9" align="left" valign="middle" style="${td};font-weight:bold;">
              <span>本页数量小计：${totalCount}</span>
              <span style="margin-left:40px;">本页金额小计：${totalPrice}</span>
              <span style="margin-left:40px;">汇总数量：${totalCount}</span>
              <span style="margin-left:40px;">汇总金额：${totalPrice}</span>
            </td>
          </tr>
          <tr height="26" style="height:26pt;">
            <td align="center" valign="middle" style="${td};font-weight:bold;">合计金额（大写金额）</td>
            <td colspan="9" align="left" valign="middle" style="${td};font-weight:bold;">
              ${convertToChinese(totalPrice)}
            </td>
          </tr>
          <tr height="28" style="height:28pt;">
            <td colspan="2" align="left" valign="middle" style="${labelLeft}">收货单审核人：${this.formData.reviewerName || ''}</td>
            <td colspan="2" align="left" valign="middle" style="${labelLeft}">采购发起人：${this.formData.purchaseInitiatorName || ''}</td>
            <td colspan="2" align="left" valign="middle" style="${labelLeft}">质检人：${this.formData.qualityName || ''}</td>
            <td colspan="4" align="left" valign="middle" style="${labelLeft}">仓管员：${this.formData.warehouseKeeperName || ''}</td>
          </tr>
        </table>`;

      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>${table}</body></html>`;

      const blob = new Blob(['﻿' + html], {
        type: 'application/vnd.ms-excel;charset=utf-8'
      });
      saveAs(blob, `${title}_${this.formData.receiveNo || ''}.xls`);
    }
  }
};
</script>

<style lang="scss"></style>
