import React, { Component } from 'react';
import PropTypes from 'prop-types';

// todo 支持图表，例如echart
const propTypes = {
  wordId: PropTypes.string, // wordID
  fileName: PropTypes.string, // 导出文件的名字
  title: PropTypes.element, // 名称标题
  styles: PropTypes.string, // word中的样式
};

const defaultProps = {
  wordId: '',
  className:'',
  fileName: 'filename',
  title: '导出Word',
  styles: 'table{width:100%} ',
  success:()=>{},
};

class ExportWord extends Component {

  exportWord = () => {
    const { wordId, fileName } = this.props;
    this.getBlob(wordId, fileName);
  };


  getBlob = (wordId, fileName) => {
    // IE10 以下
    if (typeof window === 'undefined' || (typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent))) {
      return;
    }
    const location =window.location;
    const mHtml = {
      top: `Mime-Version: 1.0\nContent-Base: ${location.href}\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ${location.href}\n\n<!DOCTYPE html>\n<html>\n_html_</html>`,
      head: '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n',
      body: '<body>_body_</body>',
    };

    const activeDoc = document.getElementById(wordId); // 获取 dom 节点

    if(activeDoc.querySelector(".markdown-body")){
      let imgNode =activeDoc.querySelectorAll('.markdown-body img');
      if(imgNode.length){
        for(const item of imgNode){
          let itemSrc=item.getAttribute('src');
          if(itemSrc.indexOf('http')===-1){
            item.setAttribute('src',location.origin+itemSrc);
          }
        }
      }
    }

    // 默认样式
    const defaultStyle = '.text-div{ text-decoration: underline; margin-right: 15px; } .textarea-div{ text-decoration: underline; }  table td,table th{padding: 6px 13px;border: 1px solid #ddd;} table{border-collapse: collapse;}';
    const mHtmlBottom = '\n--NEXT.ITEM-BOUNDARY--';// 文件尾信息

    // 替换模板里的内容
    const fileContent = mHtml.top.replace('_html_', mHtml.head.replace('_styles_', defaultStyle ) + mHtml.body.replace('_body_', activeDoc.innerHTML)) + mHtmlBottom;
    // 创建包含文件内容的blob
    const blob = new Blob([fileContent], { type: 'application/msword;charset=utf-8' });
    // 下载word文件
    this.saveAs(blob, `${fileName}.doc`);
    // 下载成功后执行回调方法
    this.props.success();
  };


  saveAs = (blob, name) => { // 实现下载操作
    // IE 10+ (native saveAs)
    if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {
      return navigator.msSaveOrOpenBlob(blob, name);
    }
    const urlObj = window.URL || window.webkitURL || window;
    const objectUrl = urlObj.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = objectUrl;
    // 模拟点击事件
    a.download = name;
    a.click(); // 下载
  };


  render() {
    const { title,className  } = this.props;
    return (
      <span className="link">
        <span className={className} onClick={this.exportWord}>{title}</span>
      </span>
    );
  }
}

ExportWord.propTypes = propTypes;
ExportWord.defaultProps = defaultProps;
export default ExportWord;
