'use strict';
/**
 * @description
 * 1.拖放文件到编辑区域，自动上传并插入到选区
 * 2.插入粘贴板的图片，自动上传并插入到选区
 * @author Nero
 * @date 2015-07-20
 */

UE.plugin.register('autoupload', function () {
    var domUtils = baidu.editor.dom.domUtils;
    function sendAndInsertFile(file, editor) {
        var me = editor;
        //模拟数据
        var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
            loadingHtml, errorHandler, successHandler,
            filetype = /image\/\w+/i.test(file.type) ? 'image' : 'file',
            loadingId = 'loading_' + (+new Date()).toString(36);

        fieldName = me.getOpt(filetype + 'FieldName');
        urlPrefix = '';//返回的地址是全路径，不需要拼接
        maxSize = me.getOpt(filetype + 'MaxSize');
        allowFiles = me.getOpt(filetype + 'AllowFiles');
        actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
        errorHandler = function (title) {
            var loader = me.document.getElementById(loadingId);
            loader && domUtils.remove(loader);
            me.fireEvent('showmessage', {
                'id': loadingId,
                'content': title,
                'type': 'error',
                'timeout': 4000
            });
            wxbEditor.store.storeContent();
        };

        if (filetype == 'image') {
            loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
            me.options.themePath + me.options.theme +
            '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
            successHandler = function (data) {
                var link = urlPrefix + data.url,
                    loader = me.document.getElementById(loadingId);
                if (loader) {
                    loader.setAttribute('src', link);
                    loader.setAttribute('_src', link);
                    loader.setAttribute('data-src', link);
                    loader.setAttribute('style', 'height: auto !important; width: auto;');
                    loader.removeAttribute('id');
                    loader.removeAttribute('title');
                    loader.removeAttribute('word_img');
                    domUtils.removeClasses(loader, 'loadingclass');
                }
                wxbEditor.store.storeContent();
            };
        } else {
            errorHandler('不支持的文件');
        }

        /* 插入loading的占位符 */
        me.execCommand('inserthtml', loadingHtml);

        /* 判断文件大小是否超出限制 */
        if (file.size > maxSize) {
            errorHandler(me.getLang('autoupload.exceedSizeError'));
            return;
        }
        /* 判断文件格式是否超出允许 */
        var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')) : '';
        if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
            errorHandler(me.getLang('autoupload.exceedTypeError'));
            return;
        }

        var reader = new FileReader();
        reader.onload = function (event) {
            var _winTop = window.top;
            var match = event.target.result.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
            var buffer = _winTop.Wechat.base64ToBin(match[2]);
            var account = _winTop.Accounts.getCurrentEditorAccount();
            _winTop.Wechat.uploadFileDataToWechat(buffer, file.name, account).then(function (response) {
                var result = {
                    state: 'SUCCESS',
                    url: response.url
                };
                successHandler(result);
            }).catch(function (e) {
                errorHandler(JSON.stringify(e));
            });
        };
        reader.readAsDataURL(file);
    }

    function getPasteImage(e) {
        return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items : null;
    }

    function getDropImage(e) {
        return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : null;
    }

    return {
        outputRule: function (root) {
            UE.utils.each(root.getNodesByTagName('img'), function (n) {
                if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
                    n.parentNode.removeChild(n);
                }
            });
            UE.utils.each(root.getNodesByTagName('p'), function (n) {
                if (/\bloadpara\b/.test(n.getAttr('class'))) {
                    n.parentNode.removeChild(n);
                }
            });
        },
        bindEvents: {
            //插入粘贴板的图片，拖放插入图片
            'ready': function (e) {
                var me = this;
                if (window.FormData && window.FileReader) {
                    domUtils.on(me.body, 'paste drop', function (e) {
                        var hasImg = false,
                            items;
                        //获取粘贴板文件列表或者拖放文件列表
                        items = e.type == 'paste' ? getPasteImage(e) : getDropImage(e);
                        if (items) {
                            var len = items.length,
                                file;
                            while (len--) {
                                file = items[len];
                                if (file.getAsFile) file = file.getAsFile();
                                if (file && file.size > 0) {
                                    sendAndInsertFile(file, me);
                                    hasImg = true;
                                }
                            }
                            hasImg && e.preventDefault();
                        }

                    });
                    //取消拖放图片时出现的文字光标位置提示
                    domUtils.on(me.body, 'dragover', function (e) {
                        if (e.dataTransfer.types[0] == 'Files') {
                            e.preventDefault();
                        }
                    });

                    //设置loading的样式
                    UE.utils.cssRule('loading',
                        '.loadingclass{display:inline-block;cursor:default;background: url(\''
                        + this.options.themePath
                        + this.options.theme + '/images/loading.gif\') no-repeat center center transparent !important;height: 22px;width: 22px;}\n' +
                        '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
                        + this.options.themePath
                        + this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
                        '}',
                        this.document);
                }
            }
        }
    }
});


// plugins/simpleupload.js
/**
 * @description
 * 简单上传:点击按钮,直接选择文件上传
 * @author Nero
 * @date 2015-07-24
 */
UE.plugin.register('simpleupload', function () {
    var me = this,
        isLoaded = false,
        containerBtn;

    var domUtils = baidu.editor.dom.domUtils;
    function initUploadBtn() {
        var w = containerBtn.offsetWidth || 20,
            h = containerBtn.offsetHeight || 20,
            btnIframe = document.createElement('iframe'),
            btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';

        domUtils.on(btnIframe, 'load', function () {

            var timestrap = (+new Date()).toString(36),
                wrapper,
                btnIframeDoc,
                btnIframeBody;

            btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
            btnIframeBody = btnIframeDoc.body;
            wrapper = btnIframeDoc.createElement('div');

            wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" target="edui_iframe_' + timestrap + '" method="POST" enctype="multipart/form-data" action="' + me.getOpt('serverUrl') + '" ' +
            'style="' + btnStyle + '">' +
            '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
            'style="' + btnStyle + '">' +
            '</form>' +
            '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';

            wrapper.className = 'edui-' + me.options.theme;
            wrapper.id = me.ui.id + '_iframeupload';
            btnIframeBody.style.cssText = btnStyle;
            btnIframeBody.style.width = w + 'px';
            btnIframeBody.style.height = h + 'px';
            btnIframeBody.appendChild(wrapper);

            if (btnIframeBody.parentNode) {
                btnIframeBody.parentNode.style.width = w + 'px';
                btnIframeBody.parentNode.style.height = w + 'px';
            }

            var form = btnIframeDoc.getElementById('edui_form_' + timestrap);
            var input = btnIframeDoc.getElementById('edui_input_' + timestrap);
            var iframe = btnIframeDoc.getElementById('edui_iframe_' + timestrap);

            domUtils.on(input, 'change', function () {
                if (!input.value) return;
                var loadingId = 'loading_' + (+new Date()).toString(36);

                var allowFiles = me.getOpt('imageAllowFiles');

                me.focus();
                me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme + '/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');

                function callback(json) {
                    input.value='';
                    try {
                        var link, loader;
                        link = json.url;
                        loader = me.document.getElementById(loadingId);
                        if (json.state == 'SUCCESS' && json.url) {
                            loader.setAttribute('src', link);
                            loader.setAttribute('_src', link);
                            loader.setAttribute('data-src', link);
                            loader.setAttribute('style', 'height: auto !important; width: auto;');
                            loader.removeAttribute('id');
                            loader.removeAttribute('title');
                            loader.removeAttribute('word_img');
                            domUtils.removeClasses(loader, 'loadingclass');
                        } else {
                            showErrorLoader && showErrorLoader(json);
                        }
                    } catch (er) {
                        showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
                    }
                    wxbEditor.store.storeContent();
                }

                function showErrorLoader(title) {
                    if (loadingId) {
                        var loader = me.document.getElementById(loadingId);
                        loader && domUtils.remove(loader);
                        me.fireEvent('showmessage', {
                            'id': loadingId,
                            'content': title,
                            'type': 'error',
                            'timeout': 4000
                        });
                    }
                }

                // 判断文件格式是否错误
                var filePath = input.value,
                    fileext = filePath ? filePath.substr(filePath.lastIndexOf('.')) : '';
                if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
                    showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
                    return;
                }

                //上传文件

                var filePath=input.value;
                var fileName = filePath.substr(filePath.lastIndexOf('\\') + 1);
                var _winTop = window.top;
                var account = _winTop.Accounts.getCurrentEditorAccount();
                _winTop.Wechat.uploadFile(filePath, fileName, account).then(function (result) {
                    var result = {
                        state: 'SUCCESS',
                        url: result.url
                    };
                    callback(result);
                }).catch(function (e) {
                    callback(JSON.stringify(e.message));
                });
            });

            var stateTimer;
            me.addListener('selectionchange', function () {
                clearTimeout(stateTimer);
                stateTimer = setTimeout(function () {
                    var state = me.queryCommandState('simpleupload');
                    if (state == -1) {
                        input.disabled = 'disabled';
                    } else {
                        input.disabled = false;
                    }
                }, 400);
            });
            isLoaded = true;
        });

        btnIframe.style.cssText = btnStyle;
        containerBtn.appendChild(btnIframe);
    }

    return {
        bindEvents: {
            'ready': function () {
                //设置loading的样式
                UE.utils.cssRule('loading',
                    '.loadingclass{display:inline-block;cursor:default;background: url(\''
                    + this.options.themePath
                    + this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
                    '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
                    + this.options.themePath
                    + this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
                    '}',
                    this.document);
            },
            /* 初始化简单上传按钮 */
            'simpleuploadbtnready': function (type, container) {
                containerBtn = container;
                me.afterConfigReady(initUploadBtn);
            }
        },
        outputRule: function (root) {
            UE.utils.each(root.getNodesByTagName('img'), function (n) {
                if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
                    n.parentNode.removeChild(n);
                }
            });
        },
        commands: {
            'simpleupload': {
                queryCommandState: function () {
                    return isLoaded ? 0 : -1;
                }
            }
        }
    }
});


// plugins/catchremoteimage.js
///import core
///commands 远程图片抓取
///commandsName  catchRemoteImage,catchremoteimageenable
///commandsTitle  远程图片抓取
/**
 * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
 */
UE.catchRemoteImageNum=0;//需要抓取的图片
UE.plugins['catchremoteimage'] = function () {
    var me = this;
    var remoteUrl=/^https?:\/\/mmbiz\.q(logo|pic)\.cn\/mmbiz/i;//http://mmbiz.qpic.cn/mmbiz/ | http://mmbiz.qlogo.cn/mmbiz/ 为微信本地的资源
    var domUtils = baidu.editor.dom.domUtils;
    if(window.top.Material){
        var transforImgUrl=window.top.Material.transforImgUrl;
    }
    me.addListener("afterpaste", function () {
        me.fireEvent("catchRemoteImage");
    });

    me.addListener("catchRemoteImage", function () {

        var remoteImages = [],
            imgs = domUtils.getElementsByTagName(me.document, "img"),
            test = function (src, urls) {
                if (src.match(remoteUrl) == null || /(^\.)|(^\/)/.test(src)) {
                    return true;
                }
                if (urls) {
                    for (var j = 0, url; url = urls[j++];) {
                        if (src.indexOf(url) !== -1) {
                            return true;
                        }
                    }
                }
                return false;
            };

        for (var i = 0, ci; ci = imgs[i++];) {
            if (ci.getAttribute("word_img")) {
                continue;
            }
            var src = ci.getAttribute("_src") || ci.src || "";
            var newSrc=transforImgUrl(src);
            if(src!=newSrc){
                domUtils.setAttributes(ci, {
                    "src": newSrc,
                    "data-src": newSrc,
                    "_src": newSrc
                });
                continue;
            }
            if (test(src)) {
                remoteImages.push(src);
            }
        }

        if (remoteImages.length) {
            catchremoteimage(remoteImages, {
                //成功抓取
                success: function (newPathList) {
                    /* 获取源路径和新路径 */
                    var i, j, ci, cj, oldSrc, newSrc;

                    for (i = 0; ci = imgs[i++];) {
                        oldSrc = ci.getAttribute("_src") || ci.src || "";
                        for (j = 0; cj = newPathList[j++];) {
                            if (oldSrc == cj.source ) {  //抓取失败时不做替换处理
                                newSrc =cj.url;
                                if(cj.state == "SUCCESS"){
                                    domUtils.setAttributes(ci, {
                                        "src": newSrc,
                                        "data-src": newSrc,
                                        "_src": newSrc
                                    });
                                }else if(cj.state == "ERROR"){
                                    domUtils.setAttributes(ci, {
                                        "src": newSrc,
                                        "data-src": newSrc,
                                        "alt": oldSrc,
                                        "_src": newSrc
                                    });
                                }

                                break;
                            }
                        }
                    }
                    me.fireEvent('catchremotesuccess');
                    wxbEditor.store.storeContent();

                },
                //回调失败，本次请求超时
                error: function () {
                    me.fireEvent("catchremoteerror");
                    wxbEditor.store.storeContent();

                }
            });
        }

        function catchremoteimage(imgs, callbacks) {
            var _winTop = window.top;
            var account = _winTop.Accounts.getCurrentEditorAccount();
            var doneIms=[];
            var pList=[]
            for (var i = 0; i < imgs.length; i++) {
                (function(i){
                    var  img_path = imgs[i];

                    pList.push(_winTop.Wechat.uploadFile(img_path, '自动上传图片', account,i*300).then(function (result) {
                        return Promise.resolve({source:img_path,url:result.url,state:'SUCCESS'});
                    }).catch(function (e) {
                        //无法抓取到的图片 显示 错误图片，与微信官方保持一致
                        var errImgPath='http://mmbiz.qpic.cn/mmbiz/G1lssUsxJOsVVJNUIuKfUP7bLm5EVWxXl5znicMum6Os0CMJHPdeHicicZ4W5MGOVa8ooSXYuE61Ek/0?tp=webp&wxfrom=5';
                        UE.catchRemoteImageNum++;
                        return Promise.resolve({source:img_path,url:errImgPath,state:'ERROR'});
                        console.log('one error',e);
                    }));
                })(i);

            }
            Promise.all(pList).then(function (list) {
                callbacks.success(list);
            }).catch(function (e) {
                callbacks.error(e);
                console.log(e);
            });


        }

    });
};