<template>
  <div class="trade_print">
    <iframe
      ref="iframe"
      width="100%"
      height="100%"
      sandbox="allow-same-origin allow-scripts allow-forms allow-modals"
      @load="onIframeLoad"
    />
  </div>
</template>

<script>
import { queryDealReceipt, queryDealQueryList } from '@/api/dcsApi';
import { isEmpty } from 'lodash';
export default {
  name: 'TradePrint',
  props: {
    dealId: {
      type: Number || String,
      default: '',
    },
    product: {
      type: Number || String,
      default: '',
    },
    instrument: {
      type: Number || String,
      default: '',
    },
  },
  data() {
    return {
      iframeDocument: null,
      iframeWindow: null,
      htmlTemplatePre: `
        <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>交易打印</title><style>.print-table{font-family:仿宋;font-size:18px;width:95%;border:0;border-collapse:collapse}.print-tr{height:20px}.print-th0{text-align:center;width:9%;border:solid#000 1px;font-weight:bold}.print-th1{text-align:center;width:9%;border:solid#000 1px;font-weight:bold}.print-th2{text-align:center;width:9%;border:solid#000 1px;font-weight:bold}.print-th3{text-align:center;width:12%;border:solid#000 1px;font-weight:bold}.print-th4{text-align:center;width:24%;border:solid#000 1px;font-weight:bold}.print-th5{text-align:center;width:14%;border:solid#000 1px;font-weight:bold}.print-th6{text-align:center;width:9%;border:solid#000 1px;font-weight:bold}.print-th7{text-align:center;width:14%;border:solid#000 1px;font-weight:bold}.print-td{text-align:left;width:100%;border:solid#000 1px;font-weight:bold}.print-td0{text-align:center;width:9%;border:solid#000 1px}.print-td1{text-align:center;width:9%;border:solid#000 1px}.print-td2{text-align:center;width:9%;border:solid#000 1px}.print-td3{text-align:center;width:12%;border:solid#000 1px}.print-td4{text-align:left;width:24%;border:solid#000 1px}.print-td5{text-align:left;width:14%;border:solid#000 1px}.print-td6{text-align:center;width:9%;border:solid#000 1px}.print-td7{text-align:right;width:14%;border:solid#000 1px}.print-log-table{font-family:仿宋;font-size:18px;width:95%;border:0;border-collapse:collapse}.print-log-th0{text-align:center;width:15%;border:solid#000 1px;font-weight:bold}.print-log-th1{text-align:center;width:10%;border:solid#000 1px;font-weight:bold}.print-log-th2{text-align:center;width:15%;border:solid#000 1px;font-weight:bold}.print-log-th3{text-align:center;width:15%;border:solid#000 1px;font-weight:bold}.print-log-th4{text-align:center;width:25%;border:solid#000 1px;font-weight:bold}.print-log-th5{text-align:center;width:20%;border:solid#000 1px;font-weight:bold}.print-log-td0{text-align:center;width:15%;border:solid#000 1px}.print-log-td1{text-align:center;width:10%;border:solid#000 1px}.print-log-td2{text-align:center;width:15%;border:solid#000 1px}.print-log-td3{text-align:center;width:15%;border:solid#000 1px}.print-log-td4{text-align:center;width:25%;border:solid#000 1px}.print-log-td5{text-align:center;width:20%;border:solid#000 1px}.print-log-td{text-align:left;width:100%;font-weight:bold;border:solid#000 1px}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-thumb{border-radius:5px;background:#ffffff}::-webkit-scrollbar-thumb:hover{background:rgba(0,0,0,0.2)}</style></head><body id="printContentBody">
      `,
      htmlTemplateSuf: `</body></html>`,
      cssFileUrl: '', // 实际的 CSS 文件路径
      insertCount: 0,
    };
  },
  mounted() {
    // 初始化 iframe 加载
    this.$refs.iframe.src = 'about:blank';
  },
  methods: {
    onIframeLoad() {
      if (!this.dealId || !this.product) {
        console.warn('dealId is empty');
        return;
      }

      this.initHtml();
    },
    async initHtml() {
      if (this.insertCount > 0) { return; }
      const str = await this.assemblyHtmlStr();
      this.insertHtmlStr(str);
      this.insertCount++;
    },
    async insertHtmlStr(str) {
      this.iframeDocument = this.$refs.iframe.contentDocument;
      this.iframeWindow = this.$refs.iframe.contentWindow;

      const html = this.htmlTemplatePre + str + this.htmlTemplateSuf;
      // 设置 iframe 的 HTML 内容为表单模板
      this.iframeDocument.open();
      this.iframeDocument.write(html);
      this.iframeDocument.close();

      // TODO 目前不考虑，在不依赖 nginx 情况下先做内联 css 处理
      // 动态加载额外的 CSS 文件
      // const link = this.iframeDocument.createElement('link');
      // link.rel = 'stylesheet';
      // link.href = this.cssFileUrl;
      // this.iframeDocument.head.appendChild(link);
    },
    print() {
      this.iframeWindow.print();
    },
    async assemblyHtmlStr() {
      const result = await Promise.all([this.getDealReceipt(), this.getDealQueryList()]);
      return result.join('');
    },
    async getDealReceipt() {
      const data = await queryDealReceipt({ 'dealId': this.dealId, 'product': this.product, 'instrument': this.instrument });
      if (data?.success && data?.data.result) {
        return data?.data.result.replace(/@{2}([^@]*)@{2}/g, (match, key) => {
          return this.$t(key);
        });
      } else {
        return '';
      }
    },
    async getDealQueryList() {
      if (this.product === 'REPO' || this.product === 'SECLB' || this.product === 'REPOOUT') {
        const data = await queryDealQueryList({ 'queryParam.dealId': this.dealId });
        const dealData = data?.data.result ?? [];
        if (dealData.length > 0) {
          let guaranteeTable = '';
          if (!isEmpty(dealData[0].guaranteeEos) && dealData[0].guaranteeEos.length > 0) {
            const guaranteeTableStart =
                       `
                           <table class="print-log-table">
                               <tbody>
                                   <thead>
                                       <tr class="print-tr">
                                           <td class="print-log-th1">债券编码</td>
                                           <td class="print-log-th1">货币</td>
                                           <td class="print-log-th2">全价</td>
                                           <td class="print-log-th3">债券面额</td>
                                           <td class="print-log-th1">折扣率(%)</td>
                                           <td class="print-log-th3">折算汇率</td>
                                       </tr>
                                   </thead>
                       `;
            const guaranteeTableEnd =
                       `
                           </tbody>
                                   </table>
                       `;
            dealData[0].guaranteeEos.forEach(function(item) {
              guaranteeTable += `<tr class="print-tr">
                            <td  class="print-log-td" style="width:20%">${item.underlying}</td>
                            <td  class="print-log-td" style="width:10%">${item.ccy}</td>
                            <td  class="print-log-td" style="width:12%">${item.price}</td>
                            <td  class="print-log-td" style="width:18%">${item.nominal}</td>
                            <td  class="print-log-td" style="width:11%">${item.haircut}</td>
                            <td  class="print-log-td" style="width:11%">${item.spotRate}</td>
                        </tr>`;
            });
            return guaranteeTableStart + guaranteeTable + guaranteeTableEnd + '<br/>';
          } else {
            return '';
          }
        }
      } else {
        return '';
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.trade_print {
  height: 460px;
  background-color: #fff;
}
</style>
