{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge，chrome=1">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta http-equiv="Cache-Control" content="max-age=7200" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="keywords" content="{% block keyword %}{% endblock %}mrdoc"/>
    <meta name="description" content="{% block description %}{% endblock %}" />
    <title>{% block title %}{% endblock %} - 觅道文档MrDoc</title>
    <link href="{% static 'layui/css/layui.css' %}?version={{mrdoc_version}}" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'editor.md/css/editormd.css' %}?version={{mrdoc_version}}" />
    <link rel="stylesheet" href="{% static 'katex/katex.min.css' %}?version={{mrdoc_version}}" />
    <link rel="icon" href="{% static 'favicon_16.png' %}"/>
    <link href="{% static 'mrdoc.css' %}?version={{mrdoc_version}}" rel="stylesheet">
    <style>
        /* 编辑器图标样式 */
        .editormd-menu i{
            color: #333;
            font-size: 16px;
        }
        ul.editormd-menu{
            margin-bottom: 0;
        }
        /* 编辑器预览列表样式 */
        .markdown-body ul li{
            list-style:disc;
        }
        .markdown-body ul > li > ul > li{
            list-style-type: circle;
        }
        .markdown-body ol li{
            list-style-type: decimal;
        }
        .markdown-body ol ol ul,.markdown-body ol ul ul,.markdown-body ul ol ul,.markdown-body ul ul ul li{
            list-style-type: square;
        }
        /* 选择上级文档样式 */
        .selected-parent-doc{
            text-decoration-line: underline;
            font-weight: 700;
            color: black;
        }
        /* 选择图片 - 图片列表样式 */
        .select-img-list{
            cursor: pointer;
            position: relative;
            display:flex;
            float: left;
            align-items:center;
            width: 120px;
            height:120px;
            margin: 0 20px 30px 0;
            text-align: center;
            overflow: hidden;
        }

        .select-img-list:hover{
            background-color: #EAFFEA;
        }
        .select-img-list-i{
            display: block;
            width: 100%;
            height: auto;
            -webkit-background-size: contain;
            border: 1px solid transparent;
            border-radius: 3px;
            overflow: hidden;
        }
        /* layui分页组件样式 */
        .layui-laypage .layui-laypage-curr .layui-laypage-em{
            background-color: #1E9FFF !important;
        }
        .layui-form-select dl dd.layui-this{
            background-color: #1E9FFF !important;
        }
        /* HTML预览样式 */
        .markdown-body h1{
            font-size: 1.7em;
        }
        .markdown-body h2{
            font-size: 1.5em;
        }
        .markdown-body h3{
            font-size: 1.25em;
        }
        .markdown-body h4{
            font-size: 1em;
        }
        .markdown-body h5{
            font-size: .875em;
        }
        .markdown-body h6{
            font-size: .85em;
        }
        /* 引用块样式 */
        .editormd-preview-container blockquote, .editormd-html-preview blockquote{
            border-left: 4px solid #333;
        }
    </style>
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->

</head>
<body>
<div class="doc layui-fluid" style="padding-left:0px;">
    <!-- 左侧工具栏 -->
    <div class="doc-summary">
        <div class="project-title"><i class="fa fa-edit"></i> MrDoc文档编辑器<br>
            <span style="font-size: 14px;">你正在：{% block editor_type %}{% endblock %}</span>
        </div>
        
        <hr>
        {% block left_opera %}
        {% endblock %}
    </div>
    <!-- 左侧工具栏结束 -->

    <!-- 右侧编辑器栏 -->
    <div class="doc-body">
        <!-- 文档导航 -->
        <div class="doc-header" role="navigation">

            <a class="btn pull-left js-toolbar-action" aria-label="" href="javascript:void(0);" title="切换侧边栏">
                <i class="fa fa-align-justify"></i>
            </a>
            <!-- 顶部工具栏 -->
            {% block head_toolbar %}
            {% endblock %}
            <a class="btn pull-right" aria-label="" href="{% url 'pro_list' %}">
                <i class="fa fa-home"></i> <span class="layui-hide-xs">首页</span>
            </a>
        </div>
        <!-- 文档主体 -->
        <div class="doc-body-content" style="padding-left: 15px;">
            <div class="mrdoc-body-content-div">
                <!-- 文档内容 -->
                <div class="mrdoc-editor-content">
                    <!-- 正文开始 -->
                    <div class="markdown-body" id="content">
                        {% block content %}
                        {% endblock %}
                    </div>
                    <!-- 正文结束 -->
                </div>
            </div>

        </div>
    </div>
    <!-- 右侧编辑器结束 -->
</div>

<script src="{% static 'jquery/3.1.1/jquery.min.js' %}"></script>
<script src="{% static 'layui/layui.all.js' %}"></script>
<script src="{% static 'editor.md/lib/marked.min.js' %}"></script>
<script src="{% static 'editor.md/lib/prettify.min.js' %}"></script>
<script src="{% static 'editor.md/lib/raphael.min.js' %}"></script>
<script src="{% static 'editor.md/lib/underscore.min.js' %}"></script>
<script src="{% static 'editor.md/lib/sequence-diagram.min.js' %}"></script>
<script src="{% static 'editor.md/lib/flowchart.min.js' %}"></script>
<script src="{% static 'editor.md/lib/jquery.flowchart.min.js' %}"></script>
<!-- 脑图开始 -->
<script src="{% static 'mindmap/d3@5.js' %}"></script>
<script src="{% static 'mindmap/transform.js' %}"></script>
<script src="{% static 'mindmap/view.js' %}"></script>
<!-- <script src="{% static 'mindmap/markmap.js' %}"></script> -->
<!-- 脑图结束 -->
<script src="{% static 'editor.md/editormd.js' %}"></script>
<!-- <script src="{% static 'editor.md/editormd.min.js' %}"></script> -->
<script src="{% static 'mrdoc.editor.js' %}"></script>
<script src="{% static 'mrdoc.js' %}?version={{mrdoc_version}}"></script>
<script>
    $.ajaxSetup({
        data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
    });
    var tree = layui.tree;
    //加载页面时执行一次
    changeSidebar();
    //监听浏览器宽度的改变
    window.onresize = function(){
        changeSidebar();
    };
    function changeSidebar(){
        // 获取匹配指定的媒体查询
        var screen_width = window.matchMedia('(max-width: 768px)');
        //判断匹配状态
        if(screen_width.matches){
            //如果匹配到，切换侧边栏
            //console.log('小屏幕')
            $("body").addClass("big-page");
        }else{
            $("body").removeClass("big-page");
        }
    }
    </script>
    <!-- 切换隐藏侧边栏 -->
    <script>
        // 切换侧边栏
        $(function(){
            $(".js-toolbar-action").click(toggleSidebar);
        });
        //切换侧边栏显示隐藏
        function toggleSidebar(){
            console.log("切换侧边栏")
            $("body").toggleClass("big-page");
            return false;
        }
    </script>

    <!-- 展开收起左边目录 -->
    <script>
        $(function(){
            $(".switch-toc").click(SwitchToc);
        });
        function SwitchToc(i){
            var $me = $(this);
            $(this).parent().next("ul").toggleClass("toc-close"); //切换展开收起样式
            $(this).toggleClass("fa-chevron-left fa-chevron-down");//切换图标
        };
    </script>
<script>
    $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
        });
    var layer = layui.layer;
    var form = layui.form;
    var element = layui.element;
    var laypage = layui.laypage;
    var md_changed = false; //初始化一个变量，用于判断编辑器是否修改
    //初始化editormd
    var editor = editormd("editor-md", {
        width       :   "100%",
        height      :   "800px",
        placeholder :   "开始使用Markdown书写MrDoc文档，编辑器支持以下功能：\n1.粘贴上传图片\n2.六级标题\n3.代码高亮\n4.本地图片和外链图片\n5.表格\n6.多级列表和任务列表\n7.Katex公式\n8.流程图\n9.时序图\n……",
        toolbarIcons : function() {
            return [
                "undo", "redo", "|",
                "bold", "del", "italic", "quote","kaiSpan", "|",
                "h1", "h2", "h3", "|",
                "list-ul", "list-ol", "hr", "link", "reference-link", "|",
                "mindmap","imgUpload", "attachment" ,"code", "code-block", "htmltable", "|","datetime", "emoji", "html-entities", "pagebreak", "|",
                "watch", "preview", "|",
                "help"
            ]
        },
        //自定义工具栏添加楷体按钮
        toolbarIconTexts : {
            kaiSpan : "楷",
        },
        //自定义工具栏添加图片按钮
        toolbarIconsClass : {
            imgUpload:'fa-image',
            attachment:'fa-upload',
            htmltable:'fa-table',
            mindmap:'fa-sitemap',
        },
        //设置自定义工具栏按钮的事件
        toolbarHandlers : {
            /**
             * @param {Object}      cm         CodeMirror对象
             * @param {Object}      icon       图标按钮jQuery元素对象
             * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
             * @param {String}      selection  编辑器选中的文本
             */
             // 点击“楷”字图标的响应函数
            kaiSpan : function(cm, icon, cursor, selection) {
                //var cursor    = cm.getCursor();     //获取当前光标对象，同cursor参数
                //var selection = cm.getSelection();  //获取当前选中的文本，同selection参数
                // 替换选中文本，如果没有选中文本，则直接插入
                cm.replaceSelection('<span style="font-family:楷体">' + selection + "</span>");
                // 如果当前没有选中的文本，将光标移到要输入的位置
                if(selection === "") {
                    cm.setCursor(cursor.line, cursor.ch + 29);
                }
                // this == 当前editormd实例
                //console.log("testIcon =>", this, cm, icon, cursor, selection);
            },
            // 点击工具栏图片图标的响应函数 - 上传图片和选择图片
            imgUpload : function(cm,icon,cursor,selection){
                layer.ready(function(){
                  element.init();
                });
                layer.open({
                    type:'1',
                    title:'添加图片',
                    area:['800px','600px'],
                    id:'uploadImg',//配置ID,
                    content:$('#upload-img'),
                })
            },
            //点击工具栏文件按钮的响应函数 - 上传和选择附件
            attachment : function(cm,icon,cursor,selection){
                layer.ready(function(){
                  element.init();
                });
                layer.open({
                    type:'1',
                    title:'添加附件',
                    area:['800px','600px'],
                    id:'uploadAttach',//配置ID,
                    content:$('#upload-attach'),
                    success: function(layero, index){
                        layer.load(1);
                        $.post('{% url "manage_attachment" %}',{types:2},function(r){
                            $("#attach_table tbody").empty()
                            if(r.status){
                                //调用分页显示
                                laypage.render({
                                    elem: 'select-attach-page',//分页的div
                                    count: r.data.length, //数据总数
                                    limit:10, //单页数
                                    jump: function(obj){
                                        //渲染HTML
                                        $("#attach_table tbody").empty();
                                        var thisData = r.data.concat().splice(obj.curr*obj.limit - obj.limit, obj.limit);
                                        layui.each(thisData, function(k, v){
                                            var row = "<tr><td>" + v.filename + "</td><td>"+ v.filesize +"</td><td>"+ v.filetime +"</td><td><button class='layui-btn layui-btn-normal layui-btn-sm' data-name='"+ v.filename +"'  data-path='"+ v.filepath +"' onclick='insertAttach(this)'>选择</button></td></tr>"
                                            // arr.push(row);
                                            $("#attach_table tbody").append(row)
                                        });
                                    }
                                });
                                layer.closeAll("loading");//关闭加载提示
                            }else{
                                layer.closeAll("loading");//关闭加载提示
                                layer.msg("获取附件失败，请稍后重试！")
                            }
                        })

                    }
                })
            },
            //点击工具栏表格按钮的响应函数 - 添加表格
            htmltable:function(cm,icon,cursor,selection){
                layer.ready(function(){
                  element.init();
                });
                layer.open({
                    type:1,
                    id:'addTable',
                    title:'添加表格',
                    area:['600px','400px'],
                    content:$("#layer-table"),
                    btn:['确定','取消'], //添加按钮
                    yes:function(index,layero){
                        var current_tab_id = $("#insert-table-div .layui-tab-title .layui-this").attr("lay-id");
                        console.log(current_tab_id)
                        //粘贴的表格
                        if(current_tab_id == 'pasteTable'){
                            // console.log("插入粘贴的表格")
                            editor.insertValue("\n" + $("#pasteExcel").val())
                            layer.close(index)
                        }else{//创建编辑的表格
                            try {
                                var table_md = convertTable("DataTable1")
                                // console.log(table_md)
                                editor.insertValue("\n" + table_md);
                                layer.close(index)
                            } catch (error) {
                                layer.msg("请生成表格")
                            }
                        }
                        
                        $("#TableGroup").empty();//清空表格
                        $("#pasteExcel").val('');
                        
                    },
                    btn2:function(index,layero){
                        $("#TableGroup").empty();//清空表格
                        $("#pasteExcel").val('');
                        layer.close(index) // 关闭弹出框
                    }
                });
            },
            mindmap:function(cm,icon,cursor,selection){
                cm.replaceSelection('```mindmap\n' + selection + "\n```");
                if(selection === "") {
                    cm.setCursor(cursor.line+1, cursor.ch);
                }
            }
        },
        //设置语言
        lang : {
            toolbar : {
                kaiSpan : "添加楷体span标签",
                imgUpload:"添加图片到文档",
                attachment:"添加附件",
                htmltable:"添加表格",
                mindmap:"添加思维导图",
            }
        },
        //配置项
        pageBreak : true, //分页符
        path        :   "/static/editor.md/lib/",
        saveHTMLToTextarea : true,
        atLink      :   false,//禁用@链接
        tex         :   true,//开启科学公式
        tocm        :   true,//开启下拉目录
        taskList    :   true,//开启任务列表
        tocTitle    :   '文章导读',//目录标题
        tocContainer:   '',
        tocDropdown :   false,
        emoji       :   true,//开启Emoji
        flowChart   :   true, //开启流程图
        sequenceDiagram : true, //开启序列图
        imageUpload    : true, //开启图片上传
        codeFold       :true, //代码折叠
        htmlDecode     : "link,style,script,iframe|on*", //解析部分HTML标签
        imageFormats   : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL : "{% url 'upload_doc_img' %}",
        onchange:function(){
            md_changed = true
        },
        onload : function() {
            // this.insertValue(" ")
        }
    });
    //粘贴上传图片
    $("#editor-md").on('paste', function (ev) {
        var data = ev.clipboardData;
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (var index in items) {
            var item = items[index];
            if (item.kind === 'file') {
                var blob = item.getAsFile();
                var reader = new FileReader();
                reader.onload = function (event) {
                    var base64 = event.target.result;
                    //ajax上传图片
                    layer.load(1);
                    $.post("{% url 'upload_doc_img' %}",{base:base64}, function (ret) {
                        layer.msg(ret.message);
                        if (ret.success === 1) {
                            //新一行的图片显示
                            layer.closeAll("loading");
                            editor.insertValue("\n![](" + ret.url + ")");
                        }else{
                            layer.closeAll("loading");
                            layer.msg("粘贴图片失败！")
                        }
                    });
                }; // data url!
                var url = reader.readAsDataURL(blob);
            }
        }
    });
    
    //未保存离开提示
    window.onbeforeunload =function() {
    　　 if(md_changed){
            //console.log("页面未保存数据")
            return 1;
        }else{
            return null;
        }
    };
    //监听图片Tab选项卡切换
    element.on('tab(img-tab)', function(data){
      //console.log(this); //当前Tab标题所在的原始DOM元素
      //console.log(data.index); //得到当前Tab的所在下标
      //console.log(data.elem); //得到当前的Tab大容器
      if(data.index == 1){
        layer.load(1);
        console.log('选择图片')
        $("#select-img-group").empty(); //删除已有分组按钮
        //请求新的分组数据
        $.post("{% url 'manage_img_group' %}",{'types':3},function(r){
            if(r.status){
                group_btn_str = ''
                for(var i in r.data){
                    group_btn_str += '<button class="layui-btn layui-btn-normal layui-btn-sm" onclick="switchImgGroup(' + r.data[i].group_id +')">' + r.data[i].group_name + '(' + r.data[i].group_cnt + ')</button>'
                };
                $("#select-img-group").append(group_btn_str)
            }
        });
        //请求全部图片数据
        $.post("{% url 'manage_image' %}",{'types':2,'group_id':0},function(r){
            if(r.status){
                //调用分页显示
                laypage.render({
                    elem: 'select-img-page',//分页的div
                    count: r.data.length, //数据总数
                    limit:15, //单页数
                    jump: function(obj){
                        //渲染HTML
                        document.getElementById('select-img').innerHTML = function(){
                            var arr = []
                            var thisData = r.data.concat().splice(obj.curr*obj.limit - obj.limit, obj.limit);
                            layui.each(thisData, function(index, item){
                                arr.push('<li class="select-img-list"><img class="select-img-list-i" onclick="insertImg(this);" src="' + item.path + '" title="' + item.name + '" /></li>');
                            });
                        return arr.join('');
                        }();
                    }
                });
                layer.closeAll("loading");
            }else{
                layer.closeAll("loading");
                layer.msg("获取图片失败")
            }
        })
      }
    });
    //插入选择的图片到编辑器
    insertImg = function(e){
        console.log(e.src);
        editor.insertValue("\n![](" + e.src + ")");
    };
    //切换图片分组
    switchImgGroup = function(e){
        layer.load(1);
        $.post("{% url 'manage_image' %}", {
            'types': 2,
            'group_id': e
        },
        function(r) {
            if (r.status) {
                //调用分页显示
                laypage.render({
                    elem: 'select-img-page',//分页的div
                    count: r.data.length,//数据总数
                    limit: 15,//单页数
                    jump: function(obj) {
                        //渲染HTML
                        document.getElementById('select-img').innerHTML = function() {
                            var arr = []
                            var thisData = r.data.concat().splice(obj.curr * obj.limit - obj.limit, obj.limit);
                            layui.each(thisData,
                            function(index, item) {
                                arr.push('<li class="select-img-list"><img class="select-img-list-i" onclick="insertImg(this);" src="' + item.path + '" title="' + item.name + '" /></li>');
                            });
                            return arr.join('');
                        } ();
                    }
                });
                layer.closeAll("loading"); //关闭加载提示
            } else {
                layer.closeAll("loading");
                layer.msg("获取分组图片失败")
            }
        })
    };
    //插入选择的附件到编辑器
    insertAttach = function(e){
        editor.insertValue("\n[【附件】"+ $(e).data('name') + "](/media/" + $(e).data('path') + ")");
        layer.closeAll();
    }
</script>
{% block custom_script %}
{% endblock %}
</body>
{% block custom_div %}
{% endblock %}
<!-- 选择和上传图片div -->
<div id="upload-img" style="display:none;margin:20px;">
    <div class="layui-tab" lay-filter="img-tab">
      <ul class="layui-tab-title">
        <li class="layui-this">上传图片</li>
        <li>选择图片</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
            <button class="layui-btn layui-btn-normal layui-btn-fluid" id="upload_img"><i class="layui-icon layui-icon-upload"></i> 点击上传图片</button>
        </div>
        <div class="layui-tab-item">
            <div class="layui-row" id="select-img-group">
            </div><hr>
            <div class="layui-row" id="select-img"></div>
            <div id="select-img-page"></div>
        </div>
      </div>
    </div>
</div>
<!-- 选择和上传附件div -->
<div id="upload-attach" style="display:none;margin:20px;">
    <span>* 仅支持.zip格式的压缩文件作为附件，文件大小不超过50Mb</span>
    <div style="margin: 10px 0 0 10px;">
        <button class="layui-btn layui-btn-normal layui-btn-sm" id="upload_attachment"><i class="layui-icon layui-icon-upload"></i> 点击上传附件</button>
        <a class="layui-btn layui-btn-normal layui-btn-sm" href="{% url 'manage_attachment' %}" target="_blank"><i class="fa fa-cubes"></i> 管理附件</a>
    </div>
    <table class="layui-table" id="attach_table" style="margin: 10px;width:90%;">
        <thead>
            <th>附件名称</th>
            <th>附件大小</th>
            <th>上传时间</th>
            <th>操作</th>
        </thead>
        <tbody>
        </tbody>
    </table>
    <div id="select-attach-page"></div>
</div>
<!-- 添加表格div -->
<div id="layer-table" style="display: none;margin: 10px;">
    <div class="layui-tab" lay-filter="table-tab" id="insert-table-div">
        <ul class="layui-tab-title">
          <li class="layui-this" lay-id="generaTable">生成表格</li>
          <li lay-id="pasteTable">粘贴表格</li>
        </ul>
        <div class="layui-tab-content">
          <div class="layui-tab-item layui-show" >
            <div class="layui-row" style="margin: 10px;">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <div class="layui-input-inline" style="width: 50px;">
                            <input type="number"  placeholder="行" id="row" class="layui-input" value="3">
                        </div>
                        <div class="layui-form-mid">x</div>
                        <div class="layui-input-inline" style="width: 50px;">
                            <input type="number" placeholder="列" id="col"  class="layui-input" value="3">
                        </div>
                        <div class="layui-form-mid" style="width: 100px;">
                            <button class="layui-btn layui-btn-normal layui-btn-xs" onclick="addtable(1)" >生成表格</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row" style="margin:10px;" id="TableGroup"></div>
          </div>

          <div class="layui-tab-item" >
              <textarea placeholder="粘贴Excel或在线电子表格的内容" class="layui-textarea" style="height: 200px;" id="pasteExcel"></textarea>
          </div>
        </div>
    </div>
</div>
<script>
    //按钮选择上传图片
    var upload = layui.upload;
    upload.render({
        elem: '#upload_img',
        url: '{% url "upload_doc_img" %}',
        before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            layer.load(1); //上传loading
        },
        done: function(res, index, upload){ //上传后的回调
            //上传成功
            if(res.success == 1){
                editor.insertValue("\n![](" + res.url + ")");
                layer.closeAll();
                layer.msg("上传成功");
            }else{
                layer.closeAll();
                layer.msg("上传出错，请重试！")
            }
        },
        accept: 'images', //允许上传的文件类型
        acceptMime:'image/*',
        field:'manage_upload',
        size: 5120, //最大允许上传的图片大小

    });
    // 按钮选择上传附件
    var upload_attach = layui.upload;
    upload_attach.render({
        elem: '#upload_attachment',
        url: '{% url "manage_attachment" %}',
        data:{types:0,csrfmiddlewaretoken: '{{ csrf_token }}'},
        before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            layer.load(1); //上传loading
        },
        done: function(res, index, upload){ //上传后的回调
            //上传成功，刷新页面
            if(res.status){
                editor.insertValue("\n[【附件】"+ res.data.name + "](/media/" + res.data.url + ")");
                layer.closeAll();
                layer.msg("上传成功");
            }else{
                layer.msg("上传出错，请重试！")
            }
        },
        accept: 'file', //允许上传的文件类型
        exts:'zip', //允许上传zip压缩文件
        field:'attachment_upload',
        size: 51200, //最大允许上传的文件大小
    })
    //修改预览div中a标签链接新窗口打开
    $('div.editormd-preview').on('click','a',function(e){
        e.target.target = '_blank';
    });
    // 粘贴表格文本框侦听paste粘贴事件
    // 列宽的函数
    function columnWidth(rows, columnIndex) {
        return Math.max.apply(null, rows.map(function(row) {
            return row[columnIndex].length
        }))
    };

    // 检查是否是个表格
    function looksLikeTable(data) {
        return true
    };
    // 编辑器侦听paste粘贴事件
    var pasteExcel = document.getElementById('pasteExcel')
    pasteExcel.addEventListener("paste", function(event) {
        console.log('粘贴Excel')
        var clipboard = event.clipboardData
        var data = clipboard.getData('text/plain')
        data = data.replace(/(?:[\n\u0085\u2028\u2029]|\r\n?)$/, '');

        if(looksLikeTable(data)) {
            event.preventDefault()
        }else{
            return
        }
        // 行
        var rows = data.split((/[\n\u0085\u2028\u2029]|\r\n?/g)).map(function(row) {
            console.log(row)
            return row.split("\t")
        })
        // 列对齐
        var colAlignments = []
        // 列宽
        var columnWidths = rows[0].map(function(column, columnIndex) {
            var alignment = "l"
            var re = /^(\^[lcr])/i
            var m = column.match(re)
            if (m) {
                var align = m[1][1].toLowerCase()
                if (align === "c") {
                    alignment = "c"
                } else if (align === "r") {
                alignment = "r"
                }
            }
            colAlignments.push(alignment)
            column = column.replace(re, "")
            rows[0][columnIndex] = column
            return columnWidth(rows, columnIndex)
        })
        var markdownRows = rows.map(function(row, rowIndex) {
            return "| " + row.map(function(column, index) {
                return column + Array(columnWidths[index] - column.length + 1).join(" ")
            }).join(" | ") + " |"
            row.map
        })
        markdownRows.splice(1, 0, "|" + columnWidths.map(function(width, index) {
            var prefix = ""
            var postfix = ""
            var adjust = 0
            var alignment = colAlignments[index]
            if (alignment === "r") {
                postfix = ":"
                adjust = 1
            } else if (alignment == "c") {
                prefix = ":"
                postfix = ":"
            adjust = 2
            }
            return prefix + Array(columnWidths[index] + 3 - adjust).join("-") + postfix
        }).join("|") + "|")
        event.target.value = markdownRows.join("\n")
        return false
    });
</script>
</html>