"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.assemblePageBreak = assemblePageBreak;
exports.createPrintFrame = createPrintFrame;
exports.destroyPageBreak = destroyPageBreak;
exports.printHtml = void 0;
exports.trimHtml = trimHtml;
var _xeUtils = _interopRequireDefault(require("xe-utils"));
var _dom = require("../../ui/src/dom");
var _log = require("../../ui/src/log");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
// 打印
var printFrame;
// 默认导出或打印的 HTML 样式
var defaultHtmlStyle = 'body{padding:0;color:rgba(0,0,0,0.7);font-family:"Microsoft YaHei",微软雅黑,"MicrosoftJhengHei",华文细黑,STHeiti,MingLiu;}body *{-webkit-box-sizing:border-box;box-sizing:border-box;}.vxe-table{border-collapse:collapse;text-align:left;border-spacing:0;}.vxe-table.is--default-width,.vxe-table.is--auto-width{width:100%;}.vxe-table.is--scale-width{table-layout:fixed;}.vxe-table,.vxe-table th,.vxe-table td,.vxe-table td{word-break:break-all;border-color:#D0D0D0;border-style:solid;border-width:0;}.border--default,.border--full,.border--outer{border-top-width:1px;}.border--default,.border--full,.border--outer{border-left-width:1px}.border--outer,.border--default th,.border--default td,.border--full th,.border--full td,.border--outer th,.border--inner th,.border--inner td{border-bottom-width:1px;}.border--default,.border--outer,.border--full th,.border--full td{border-right-width:1px;}.border--default th,.border--full th,.border--outer th{background-color:#f8f8f9;}.vxe-table td>div,.vxe-table th>div{padding:0.5em 0.4em;}.col--center{text-align:center;}.col--right{text-align:right;}.vxe-table .col--ellipsis>div{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;word-break:break-all;}.vxe-table--tree-node{text-align:left;}.vxe-table--tree-node-wrapper{position:relative;}.vxe-table--tree-icon-wrapper{position:absolute;top:50%;width:1em;height:1em;text-align:center;-webkit-transform:translateY(-50%);transform:translateY(-50%);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;}.vxe-table--tree-unfold-icon,.vxe-table--tree-fold-icon{position:absolute;width:0;height:0;border-style:solid;border-width:0.5em;border-right-color:transparent;border-bottom-color:transparent;}.vxe-table--tree-unfold-icon{left:.3em;top:0;border-left-color:#939599;border-top-color:transparent;}.vxe-table--tree-fold-icon{left:0;top:.3em;border-left-color:transparent;border-top-color:#939599;}.vxe-table--tree-cell{display:block;padding-left:1.5em;}.vxe-table input[type="checkbox"]{margin:0;}.vxe-table input[type="checkbox"],.vxe-table input[type="radio"],.vxe-table input[type="checkbox"]+span,.vxe-table input[type="radio"]+span{vertical-align:middle;padding-left:0.4em}';
function trimHtml(html) {
  return "".concat(html).replace(/(<!---->)/, '');
}
function createPrintFrame() {
  var frame = document.createElement('iframe');
  frame.className = 'vxe-table--print-frame';
  return frame;
}
function appendPrintFrame() {
  if (!printFrame.parentNode) {
    document.body.appendChild(printFrame);
  }
}
function afterPrintEvent() {
  requestAnimationFrame(removeFrame);
}
function removeFrame() {
  if (printFrame) {
    if (printFrame.parentNode) {
      try {
        printFrame.contentDocument.write('');
      } catch (e) {}
      printFrame.parentNode.removeChild(printFrame);
    }
    printFrame = null;
  }
}
function getExportBlobByString(str, type) {
  return new Blob([str], {
    type: "text/".concat(type, ";charset=utf-8;")
  });
}
var defaultPrintMargin = 50;
var defaultFontColor = '#000000';
function parsePageStyle(val) {
  var styOpts = Object.assign({}, val);
  var headStyOpts = Object.assign({}, styOpts.header);
  var titStyOpts = Object.assign({}, styOpts.title);
  var footStyOpts = Object.assign({}, styOpts.footer);
  var pnStyOpts = Object.assign({}, styOpts.pageNumber);
  var mVal = defaultPrintMargin;
  var marginTop = mVal;
  var marginBottom = mVal;
  var marginLeft = mVal;
  var marginRight = mVal;
  if (_xeUtils.default.isNumber(styOpts.margin) || _xeUtils.default.isString(styOpts.margin)) {
    mVal = styOpts.margin;
    marginTop = mVal;
    marginBottom = mVal;
    marginLeft = mVal;
    marginRight = mVal;
  }
  return {
    marginTop: (0, _dom.toCssUnit)(styOpts.marginTop || marginTop),
    marginBottom: (0, _dom.toCssUnit)(styOpts.marginBottom || marginBottom),
    marginLeft: (0, _dom.toCssUnit)(styOpts.marginLeft || marginLeft),
    marginRight: (0, _dom.toCssUnit)(styOpts.marginRight || marginRight),
    fontSize: (0, _dom.toCssUnit)(styOpts.fontSize),
    color: styOpts.color,
    textAlign: styOpts.textAlign,
    header: {
      height: (0, _dom.toCssUnit)(headStyOpts.height),
      textAlign: headStyOpts.textAlign
    },
    title: {
      color: titStyOpts.color,
      fontSize: (0, _dom.toCssUnit)(titStyOpts.fontSize),
      textAlign: titStyOpts.textAlign
    },
    footer: {
      height: (0, _dom.toCssUnit)(footStyOpts.height),
      textAlign: footStyOpts.textAlign
    },
    pageNumber: {
      color: pnStyOpts.color,
      fontSize: (0, _dom.toCssUnit)(pnStyOpts.fontSize),
      textAlign: pnStyOpts.textAlign
    }
  };
}
function createCssLink(urls) {
  if (urls) {
    return urls.map(function (url) {
      return "<link rel=\"stylesheet\" href=\"".concat(url, "\">");
    }).join('\n');
  }
  return '';
}
function createHtmlPage(opts, printHtml) {
  var pageStyle = opts.pageStyle,
    customStyle = opts.customStyle,
    styleUrls = opts.styleUrls;
  var pageStyObj = parsePageStyle(pageStyle);
  var headStyOpts = pageStyObj.header;
  var titStyOpts = pageStyObj.title;
  var footStyOpts = pageStyObj.header;
  var pnStyOpts = pageStyObj.pageNumber;
  var isPbMode = opts._pageBreaks || opts.pageBreaks && opts.pageBreaks.length;
  return ['<!DOCTYPE html><html>', '<head>', '<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui">', "<title>".concat(opts.title || '', "</title>"), createCssLink(styleUrls), "<style media=\"print\">@page{size:auto;".concat(isPbMode ? 'margin: 0mm;' : '', "}</style>"), "<style>body{font-size:".concat(pageStyObj.fontSize || '14px', ";color:").concat(pageStyObj.color || defaultFontColor, ";text-align:").concat(pageStyObj.textAlign || 'left', ";}</style>"), '<style>', '.vxe-print-slots{display:none;}', '.vxe-print-page-break.align--center{text-align:center;}', '.vxe-print-page-break.align--left{text-align:left;}', '.vxe-print-page-break.align--right{text-align:right;}', '.vxe-print-page-break{break-before:always;page-break-before:always;display:flex;flex-direction:column;height:100vh;overflow:hidden;}', '.vxe-print-page-break--body{display:flex;flex-direction:row;flex-grow:1;overflow:hidden;}', '.vxe-print-page-break--left,.vxe-print-page-break--right{flex-shrink:0;height:100%;}', ".vxe-print-page-break--left{width:".concat(pageStyObj.marginLeft, ";}"), ".vxe-print-page-break--right{width:".concat(pageStyObj.marginRight, ";}"), '.vxe-print-page-break--header,.vxe-print-page-break--footer{display:flex;justify-content:center;flex-direction:column;flex-shrink:0;width:100%;}', ".vxe-print-page-break--header{height:".concat(headStyOpts.height || pageStyObj.marginTop, ";padding:0 ").concat(pageStyObj.marginLeft, " 0 ").concat(pageStyObj.marginRight, ";text-align:").concat(headStyOpts.textAlign || 'left', ";}"), ".vxe-print-page-break--header-title{font-size:".concat(titStyOpts.fontSize || '1.6em', ";color:").concat(titStyOpts.color || defaultFontColor, ";text-align:").concat(opts.headerAlign || pnStyOpts.textAlign || 'center', ";}"), ".vxe-print-page-break--footer{height:".concat(footStyOpts.height || pageStyObj.marginBottom, ";padding:0 ").concat(pageStyObj.marginLeft, " 0 ").concat(pageStyObj.marginRight, ";text-align:").concat(footStyOpts.textAlign || 'left', ";}"), '.vxe-print-page-break--content{flex-grow:1;overflow:hidden;}', ".vxe-print-page-break--footer-page-number{font-size:".concat(pnStyOpts.fontSize || '1.2em', ";color:").concat(pnStyOpts.color || defaultFontColor, ";text-align:").concat(opts.footerAlign || pnStyOpts.textAlign || 'center', ";}"), '</style>', "<style>".concat(defaultHtmlStyle, "</style>"), isPbMode ? '<style>body{margin:0;}</style>' : '', customStyle ? "<style>".concat(customStyle, "</style>") : '', '</head>', '<body>', "".concat(printHtml), '</body>', '</html>'].join('');
}
function handlePrint(opts) {
  var printHtml = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var browseObj = _xeUtils.default.browse();
  var beforeMethod = opts.beforeMethod,
    styleUrls = opts.styleUrls;
  if (styleUrls && styleUrls.length) {
    styleUrls.forEach(function (url) {
      if (!/.css$/.test(url)) {
        (0, _log.warnLog)('vxe.error.errProp', [url, "".concat(url, ".css")]);
      }
    });
  }
  if (beforeMethod) {
    printHtml = beforeMethod({
      content: printHtml,
      html: printHtml,
      options: opts
    }) || '';
  }
  printHtml = createHtmlPage(opts, printHtml);
  var blob = getExportBlobByString(printHtml, 'html');
  return new Promise(function (resolve) {
    if (browseObj.msie) {
      removeFrame();
      printFrame = createPrintFrame();
      appendPrintFrame();
      var contentDocument = printFrame.contentDocument;
      if (contentDocument) {
        contentDocument.write(printHtml);
        contentDocument.execCommand('print');
      }
      setTimeout(function () {
        resolve({
          status: true
        });
      }, 300);
    } else {
      if (!printFrame) {
        printFrame = createPrintFrame();
        printFrame.onload = function (evnt) {
          var frameEl = evnt.target;
          if (frameEl.src) {
            try {
              var contentWindow = frameEl.contentWindow;
              if (contentWindow) {
                contentWindow.onafterprint = afterPrintEvent;
                contentWindow.print();
              }
            } catch (e) {}
          }
          resolve({
            status: true
          });
        };
        printFrame.onerror = function () {
          resolve({
            status: false
          });
        };
      }
      appendPrintFrame();
      printFrame.src = URL.createObjectURL(blob);
    }
  });
}
function createPageBreak(opts) {
  var title = opts.title,
    showPageNumber = opts.showPageNumber,
    align = opts.align,
    headerAlign = opts.headerAlign,
    footerAlign = opts.footerAlign,
    showAllPageTitle = opts.showAllPageTitle;
  var pageBreaks = opts.pageBreaks || [];
  var pageCount = pageBreaks.length;
  return pageBreaks.map(function (item, index) {
    var bodyHtml = item.bodyHtml;
    var headerHtml = item.headerHtml || opts.headerHtml;
    var footerHtml = item.footerHtml || opts.footerHtml;
    var leftHtml = item.leftHtml || opts.leftHtml;
    var rightHtml = item.rightHtml || opts.rightHtml;
    var currentPage = index + 1;
    var params = {
      currentPage: currentPage,
      pageCount: pageCount
    };
    return ["<div class=\"".concat(['vxe-print-page-break', align ? "align--".concat(align) : ''].join(' '), "\">"), "<div class=\"".concat(['vxe-print-page-break--header', headerAlign ? "align--".concat(headerAlign) : ''].join(' '), "\">"), headerHtml ? "".concat(_xeUtils.default.isFunction(headerHtml) ? headerHtml(params) : headerHtml || '') : title && (showAllPageTitle || !index) ? "<div class=\"vxe-print-page-break--header-title\">".concat(title || '', "</div>") : '', '</div>', '<div class="vxe-print-page-break--body">', "<div class=\"vxe-print-page-break--left\">".concat(_xeUtils.default.isFunction(leftHtml) ? leftHtml(params) : leftHtml || '', "</div>"), "<div class=\"vxe-print-page-break--content\">".concat(_xeUtils.default.isFunction(bodyHtml) ? bodyHtml(params) : bodyHtml || '', "</div>"), "<div class=\"vxe-print-page-break--right\">".concat(_xeUtils.default.isFunction(rightHtml) ? rightHtml(params) : rightHtml || '', "</div>"), '</div>', "<div class=\"".concat(['vxe-print-page-break--footer', footerAlign ? "align--".concat(footerAlign) : ''].join(' '), "\">"), footerHtml ? "".concat(_xeUtils.default.isFunction(footerHtml) ? footerHtml(params) : footerHtml || '') : showPageNumber ? "<div class=\"vxe-print-page-break--footer-page-number\">".concat(currentPage, "/").concat(pageCount, "</div>") : '', '</div>', '</div>'].join('');
  }).join('');
}
var printHtml = exports.printHtml = function printHtml(options) {
  var opts = Object.assign({
    _pageBreaks: false,
    customLayout: true
  }, options);
  if (opts.sheetName) {
    opts.title = opts.title || opts.sheetName;
  }
  if (opts.style) {
    opts.customStyle = opts.customStyle || opts.style;
  }
  if (opts.beforePrintMethod) {
    opts.beforeMethod = opts.beforeMethod || opts.beforePrintMethod;
  }
  if (opts.pageBreaks && opts.pageBreaks.length) {
    return handlePrint(opts, createPageBreak(opts));
  }
  var printHtml = opts.html || opts.content;
  return handlePrint(opts, printHtml);
};
function assemblePageBreak($xePageBreak, elem, pageBreakConfig) {
  var staticPageBreaks = $xePageBreak.reactData.staticPageBreaks;
  var parentElem = elem.parentNode;
  if (parentElem && staticPageBreaks) {
    staticPageBreaks.splice(_xeUtils.default.arrayIndexOf(parentElem.children, elem), 0, pageBreakConfig);
    $xePageBreak.reactData.staticPageBreaks = staticPageBreaks.slice(0);
  }
}
function destroyPageBreak($xePageBreak, pageBreakConfig) {
  $xePageBreak.reactData.staticPageBreaks = $xePageBreak.reactData.staticPageBreaks.filter(function (item) {
    return item.id !== pageBreakConfig.id;
  });
}