import Dragbox from './drag';
import commonTool from './utils.js';
import Message from '@core/component/message';
import Tooltips from '@core/component/toast/tooltips';
import tpl from '../picEditorTpl';
const Editor = (($) => {
    let nowMinZoom = 1, 
        nowPicZoom = 1, 
        canvasKbRatio = -1,
        arrDoApplyRecord = [],          
        arrReDoApplyRecord = [];        
    let tool = {
        
        css: function(jDom, styleName){
            return Math.round(parseFloat(getComputedStyle(jDom[0], null).getPropertyValue(styleName)));
        },
        
        autoSplitPic: function(picInfo, perPicSize, callback){
            let countSubPic = 0,        
                arrPicPoint = commonTool.getAutoCutArrPoints(picInfo.width, picInfo.height, picInfo.src, picInfo.size, perPicSize),
                mainPicSrc = picInfo.src,
                item = commonTool.mapSrcToInfo[mainPicSrc];
            handle(item.src);
            function handle(picIO){
                if(picInfo.type === 'jpg'){
                    for (let i = 0; i < arrPicPoint.length; i++) {
                        arrPicPoint[i].name = picInfo.name;
                        arrPicPoint[i].type = picInfo.type;
                    }
                    for (let i = 0; i < arrPicPoint.length; i++) {
                        (function(pic, listLen){
                            commonTool.getLocalPicKb(function (len, src, subPicStream, newType) {
                                pic.type = newType;
                                pic.src = subPicStream;
                                pic.size = len / 1.3333;
                                pic.sizeKb = ~~(pic.size / 1024);
                                if(++countSubPic === listLen){
                                    let data = {list: arrPicPoint},
                                        html = template.compile(tpl.AUTO_CUT_EDIT_LIST)(data);
                                    $('.J_edit-menu-auto .J_sliced-list').html(html);
                                    $('.J_edit-menu-auto .J_sliced-list > a').eq(0).trigger('click');
                                    typeof callback === 'function' && callback(arrPicPoint);
                                }
                            }, pic.type, 0, pic.y, pic.width, pic.height, pic.src, pic.width, pic.height, picInfo.quality, true, perPicSize);
                        })(arrPicPoint[i], arrPicPoint.length);
                    }
                }else if(picInfo.type === 'png'){
                    commonTool.getPngAutoCutArrData(item.width, item.height, item.size, picIO, perPicSize).then((arrPng) => {
                        for (let i = 0; i < arrPng.length; i++) {
                            arrPng[i].name = picInfo.name + '-' + (i + 1);
                            arrPng[i].type = picInfo.type;
                            arrPng[i].src = arrPng[i].data;
                        }
                        let data = {list: arrPng},
                            html = template.compile(tpl.AUTO_CUT_EDIT_LIST)(data);
                        $('.J_edit-menu-auto .J_sliced-list').html(html);
                        $('.J_edit-menu-auto .J_sliced-list > a').eq(0).trigger('click');
                        typeof callback === 'function' && callback(arrPng);
                    });
                }
            }
        }
    };
    class Editor {
        constructor(config) {
            this._config = this._getConfig(config);
            this.parent = this._config.parent;                     
            this._editMode = this._config.editMode;               
            this._editorPicData = this._config.editorPic;               
            this.jContainer = this._config.jContainer;              
            this._sizeLimit = this._config.sizeLimit;               
            this._initData(this._editorPicData.src, this._editorPicData.name);
            this._bindEvent();
        }
        
        _getConfig(config) {
            let newConfig = $.extend({initCallback: () => {
                }}, config);
            newConfig.editMode = config.config.editMode;
            newConfig.sizeLimit = config.config.sizeLimit;
            newConfig.perPicSize = config.config.perPicSize;
            newConfig.cateId = config.config.cateId;
            return newConfig;
        }
        
        _initData(fileSrc, fileName) {
            let that = this;
            commonTool.pngIsTransparent((result) => {
                if(result && that._editorPicData.type.match(/png/i)){
                    that._pngIsTransparent = true;
                }else{
                    that._pngIsTransparent = false;
                }
                if(that._editorPicData.type.match(/png/i) && result === true){
                    commonTool.setZipMenuAvailable(false);
                }else {
                    commonTool.setZipMenuAvailable(true);
                }
            }, that._editorPicData.src);
            $('.J_editing-name').text(that._editorPicData.name + '.' + that._editorPicData.type);
            commonTool.updateAndShowFileInfo(that._editorPicData, true);
            commonTool.getLocalPicKb(function(canvasKb){
                canvasKbRatio = that._editorPicData.size / canvasKb;
                $('body').trigger('canvasKbRatioCompleted');
            }, that._editorPicData.type, 0, 0, that._editorPicData.width, that._editorPicData.height, fileSrc, that._editorPicData.width, that._editorPicData.height, that._editorPicData.quality);
            $('.J_pic-wrap-cut img').unbind('load').bind('load', function(){
                let picWidth = this.naturalWidth,
                    picHeight = this.naturalHeight;
                nowMinZoom = commonTool.getContainZoom();
                commonTool.picZoom(nowPicZoom = nowMinZoom, nowMinZoom, true);
                if(nowPicZoom != nowMinZoom && nowMinZoom < 1){
                    $('.J_zoom-wrap').addClass('d-can-move');
                }else{
                    $('.J_zoom-wrap').removeClass('d-can-move');
                }
                commonTool.setAutoMenuAvailable(picWidth, that._sizeLimit);
                commonTool.centerPic();
                let task = {
                    global: function(){
                        $('.J_edit-menu').attr('originWidth', picWidth).attr('originHeight', picHeight);
                        if(that._editMode === 'multiple'){
                            $('.J_colose-editor').removeClass('d-hidden');
                            $('#popWinClose', top.document).hide();
                        }
                    },
                    pannelCut: function(){
                        let jPicWrapCut = $('.J_pic-wrap-cut'),
                            getKbTimer = 0;
                        $('.J_ope-origin').attr('fixVal', picWidth + ':' + picHeight);
                        let cutDragObj = new Dragbox({
                            compute: '.J_pic-wrap-cut .J_drag-control',
                            container: '.J_pic-wrap-cut .J_drag-control',
                            pannel: '.J_pic-area',
                            left: 0,
                            top: 0,
                            width: ~~$('.J_pic-wrap-cut .J_drag-control').width(),
                            height: ~~$('.J_pic-wrap-cut .J_drag-control').height(),
                            needUpdateBg: true,
                            doubleClick: function(target){
                                let jTarget = $(target),
                                    fullWidth = ~~$('.J_pic-wrap-cut .J_drag-control').width(),
                                    fullHeight = ~~$('.J_pic-wrap-cut .J_drag-control').height(),
                                    cssSet = {
                                        top: parseFloat(jTarget.css('top')),
                                        left: parseFloat(jTarget.css('left')),
                                        width: jTarget.outerWidth(),
                                        height: jTarget.outerHeight()
                                    };
                                if(cssSet.width !== fullWidth || cssSet.height !== fullHeight){
                                    jTarget.data('prevCssSet', JSON.parse(JSON.stringify(cssSet)));
                                    cssSet.top = 0;
                                    cssSet.left = 0;
                                    cssSet.width = fullWidth;
                                    cssSet.height = fullHeight;
                                }else{
                                    cssSet = jTarget.data('prevCssSet');
                                }
                                $('.J_pic-wrap-cut')[0].picDragObj.lockByFixPx(cssSet, 'd-control-transition', false);
                            },
                            changeCallback: function (mapCss) {
                                mapCss.width = Math.ceil(mapCss.width);
                                mapCss.height = Math.ceil(mapCss.height);
                                $('.J_drag-info-bar .J_width-val').text(mapCss.width);
                                $('.J_drag-info-bar .J_height-val').text(mapCss.height);
                                $('.J_user-width').val(mapCss.width).attr('preVal', mapCss.width);
                                $('.J_user-height').val(mapCss.height).attr('preVal', mapCss.height);
                                $('.J_editing-size').text(mapCss.width + ' x ' + mapCss.height);
                                clearTimeout(getKbTimer);
                                getKbTimer = setTimeout(function(){
                                    let newUrl = $('.J_pic-wrap-main img').attr('src');
                                    if(nowPicZoom !== 1){
                                        let jPic = $('.J_pic-wrap-cut .J_zoom-wrap'),
                                            preWidth = Math.round(jPic.width() * nowPicZoom),
                                            preHeight = Math.round(jPic.height() * nowPicZoom);
                                        commonTool.getLocalPicKb(function(len, src, base64){
                                            commonTool.getLocalPicKb(function(len, src, base64){
                                                $('.J_editing-kb').text(~~(len / 1.3333 / 1024)).attr('size', len / 1.3333);
                                            }, that._editorPicData.type, mapCss.left, mapCss.top, mapCss.width, mapCss.height, base64, mapCss.width, mapCss.height, that._editorPicData.quality);
                                        }, that._editorPicData.type, 0, 0, jPic.width(), jPic.height(), newUrl, preWidth, preHeight, that._editorPicData.quality);
                                    }else{
                                        commonTool.getLocalPicKb(function(len, src, base64){
                                            $('.J_editing-kb').text(~~(len / 1.3333 / 1024)).attr('size', len / 1.3333);
                                        }, that._editorPicData.type, mapCss.left, mapCss.top, mapCss.width, mapCss.height, newUrl, mapCss.width, mapCss.height, that._editorPicData.quality);
                                    }
                                }, 100);
                            }
                        });
                        cutDragObj.disable = true;
                        jPicWrapCut[0].picDragObj = cutDragObj;
                    },
                    pannelModify: function(){
                        $('.J_modify-user-width').val(picWidth);
                        $('.J_modify-user-height').val(picHeight);
                    },
                    pannelAuto: function(){
                        $('body').off('canvasKbRatioCompleted').on('canvasKbRatioCompleted', function(){
                            $('.J_edit-menu-auto .J_sliced-list', that.jContainer).on('click', 'a', function(){
                                let jTarget = $(this),
                                    width = $(this).attr('point-w'),
                                    height = $(this).attr('point-h'),
                                    top = $(this).attr('point-y'),
                                    src = $(this).attr('point-src'),
                                    size = $(this).attr('point-kb');
                                $(this).addClass('d-current').siblings().removeClass('d-current');
                                $('.J_pic-wrap-auto .J_pic-mask-current').removeClass('d-hidden').css({top: top + 'px', height: height + 'px'}).addClass('d-current');
                                $('.J_editing-size').text(width + ' x ' + height);
                                if(size){
                                    $('.J_editing-kb').text(size);
                                }else{
                                    let b = src.length / 1.3333,
                                        kb = ~~(b / 1024);
                                    jTarget.attr('point-kb', kb);
                                    $('.J_editing-kb').text(kb).attr('size', b);
                                }
                            });
                        });
                        if(canvasKbRatio !== -1){
                            $('body').trigger('canvasKbRatioCompleted');
                        }
                    }
                };
                for(let fun in task){
                    task[fun]();
                }
                that._config.initCallback && that._config.initCallback();
                that._config.initCallback = null;
            });
            $('.J_pic-area img').attr('src', fileSrc);
            new Tooltips();
        }
        
        _bindEvent() {
            let that = this;
            let enterInit = {
                cut: function(fileSrc, picWidth, picHeight){
                    $('.J_page-name').text('裁剪');
                    $('.J_file-ope-desc').text('裁剪框尺寸');
                    $('.J_user-width').val(picWidth).attr('preVal', picWidth);
                    $('.J_user-height').val(picHeight).attr('preVal', picHeight);
                    $('.J_ope-user').attr('fixVal', picWidth + ':' + picHeight);
                    $('.J_editing-size').text(picWidth + ' x ' + picHeight);
                    commonTool.getLocalPicKb(function(size){
                        $('.J_editing-kb').text(~~(size * canvasKbRatio / 1024));
                    }, that._editorPicData.type, 0, 0, picWidth, picHeight, fileSrc, picWidth, picHeight, that._editorPicData.quality);
                    setTimeout(function(){
                        commonTool.adjustDragArea(nowPicZoom, $('.J_pic-wrap-cut'));
                        let newWidth = $('.J_drag-control:visible').width(),
                            newHeight = $('.J_drag-control:visible').height();
                        $('.J_user-width').val(newWidth).attr('preVal', newWidth);
                        $('.J_user-height').val(newHeight).attr('preVal', newHeight);
                        $('.J_user-width').trigger('blur');
                        let jPicWrapCut = $('.J_pic-wrap-cut');
                        jPicWrapCut[0].picDragObj.clearBox();
                        jPicWrapCut[0].picDragObj.addBox('d-drag-box', 0, 0, Math.round(picWidth * nowPicZoom), Math.round(picHeight * nowPicZoom), fileSrc, nowPicZoom * 100 + '%');
                    }, 0);
                    if(that._sizeLimit){
                        setTimeout(function(){
                            $('.J_edit-menu-cut .J_ope-rule').trigger('click');
                        }, 0);
                    }else{
                        setTimeout(function(){
                            $('.J_edit-menu-cut .J_ope-user').trigger('click');
                        }, 0);
                    }
                },
                modify: function(fileSrc){
                    $('.J_page-name').text('修改尺寸');
                    
                },
                zip: function(fileSrc, picWidth, picHeight){
                    $('.J_page-name').text('文件压缩');
                    $('.J_edit-menu-zip > a').removeClass('d-current').eq(0).addClass('d-current');
                },
                auto: function(picInfo, callback){
                    $('.J_page-name').text('自动切图');
                    that.parent._loading.show();
                    tool.autoSplitPic(picInfo, that._config.perPicSize, () => {
                        that.parent._loading.hide();
                        typeof callback === 'function' && callback();
                    });
                }
            };
            let task = {
                global: function(){
                    if(that._editMode === 'multiple'){
                        $('.J_colose-editor', that.jContainer).on('click', function(){
                            $('.J_btn-return').trigger('click');
                        });
                    }
                    $('.J_edit-menu > a').on('click', function(){
                        if($(this).hasClass('cd-menu-disable')){
                            return;
                        }
                        let index = $(this).index(),
                            jWrap = $('.J_pic-wrap'),
                            jEditPic = $('.J_pic-wrap-main img'),
                            operateType = $(this).attr('type');     
                        $('.J_btn-return, .J_editor-btn-ok, .J_ope-undo, .J_ope-redo').addClass('d-hidden');
                        $('.J_btn-cancel, .J_btn-apply').removeClass('d-hidden');
                        if(operateType === 'auto'){
                            enterInit[operateType](commonTool.mapSrcToInfo[jEditPic.attr('src')]);
                        }else{
                            enterInit[operateType](jEditPic.attr('src'), jEditPic.width(), jEditPic.height());
                        }
                        $(this).parent().addClass('d-hidden');
                        jWrap.eq(0).addClass('d-hidden');
                        $('.J_sub-edit-menu').eq(index).removeClass('d-hidden');
                        jWrap.eq(index + 1).removeClass('d-hidden');
                    });
                    $(window).unbind('resize.picEditor').bind('resize.picEditor', function(){
                        commonTool.centerPic();
                        nowMinZoom = commonTool.getContainZoom();
                        if(nowMinZoom > nowPicZoom){
                            commonTool.picZoom(nowPicZoom = nowMinZoom, nowMinZoom, true);
                            if(nowPicZoom != nowMinZoom && nowMinZoom < 1){
                                $('.J_zoom-wrap').addClass('d-can-move');
                            }else{
                                $('.J_zoom-wrap').removeClass('d-can-move');
                            }
                        }
                    });
                    $('.J_zoom-control-wrap', that.jContainer).on('click', function(e){
                        let leftPx = e.pageX - $('.J_zoom-control-wrap').offset().left;
                        nowPicZoom = 1 - (100 - leftPx) / 100 * (1 - nowMinZoom);
                        if(nowPicZoom != nowMinZoom && nowMinZoom < 1){
                            $('.J_zoom-wrap').addClass('d-can-move');
                        }else{
                            $('.J_zoom-wrap').removeClass('d-can-move');
                        }
                        $('.J_zoom-control').addClass('d-trans-left');
                        commonTool.picZoom(nowPicZoom, nowMinZoom, true);
                        setTimeout(function(){
                            $('.J_zoom-control').removeClass('d-trans-left');
                        }, 200);
                    }).on('mousemove', function(e){
                        let newPx = e.pageX - ~~$('.J_zoom-control-wrap').offset().left;
                        $('.J_zoom-info').css('left', newPx - 5).text('比例：' + Number(((1 - (100 - (newPx - 12)) / 100 * (1 - nowMinZoom)) * 100).toFixed(2)) + '%');
                    });
                    $('.J_zoom-tool').hover(function(){
                        $('.J_zoom-info').removeClass('d-hidden');
                    }, function(){
                        $('.J_zoom-info').addClass('d-hidden');
                    });
                    $('.J_ope-undo', that.jContainer).on('click', function(){
                        if($(this).hasClass('d-usable')){
                            let recordInfo = arrDoApplyRecord.pop();
                            arrReDoApplyRecord.push(commonTool.mapSrcToInfo[$('.J_pic-wrap-main img').attr('src')]);
                            $('.J_pic-wrap img').attr('src', recordInfo.src);
                            commonTool.centerPic();
                            commonTool.updateAndShowFileInfo(recordInfo);
                            arrDoApplyRecord.length === 0 && $(this).removeClass('d-usable');
                            $('.J_ope-redo').addClass('d-usable');
                        }
                    });
                    $('.J_ope-redo', that.jContainer).on('click', function(){
                        if($(this).hasClass('d-usable')){
                            let recordInfo = arrReDoApplyRecord.pop();
                            arrDoApplyRecord.push(commonTool.mapSrcToInfo[$('.J_pic-wrap-main img').attr('src')]);
                            $('.J_pic-wrap img').attr('src', recordInfo.src);
                            commonTool.centerPic();
                            commonTool.updateAndShowFileInfo(recordInfo);
                            arrReDoApplyRecord.length === 0 && $(this).removeClass('d-usable');
                            $('.J_ope-undo').addClass('d-usable');
                        }
                    });
                    
                    let CSS3_TRANSFORM = commonTool.css3Prefix.TRANSFORM;
                    $('.J_list-left', that.jContainer).on('click', function(){
                        let jWrap = $(this).closest('.J_sub-edit-menu'),
                            jSlideItem = jWrap.find('.J_sliced-list > a'),
                            jSlide = jSlideItem.parent();
                        if(jSlideItem.length && !jSlide.hasClass('d-working')){
                            let oneWidth = jSlideItem.outerWidth(true),
                                containerWidth = jSlide.width(),
                                left = ~~jSlide.attr('left'),
                                difference = -left;
                            if(difference > 0){
                                jSlide.addClass('d-working');
                                let moveDistance = difference > containerWidth? containerWidth : difference,
                                    newLeft = left + moveDistance;
                                jSlide.css(CSS3_TRANSFORM, 'translateX(' + newLeft + 'px)').attr('left', newLeft);
                                setTimeout(function(){
                                    $('.J_sliced-list', jWrap).removeClass('d-working');
                                }, 600);
                            }
                        }
                    });
                    $('.J_list-right', that.jContainer).on('click', function(){
                        let jWrap = $(this).closest('.J_sub-edit-menu'),
                            jSlideItem = jWrap.find('.J_sliced-list > a'),
                            jSlide = jSlideItem.parent();
                        if(jSlideItem.length && !jSlide.hasClass('d-working')){
                            let oneWidth = jSlideItem.outerWidth(true),
                                totalWidth = oneWidth * jSlideItem.length,
                                containerWidth = jSlide.width(),
                                left = ~~jSlide.attr('left'),
                                difference = totalWidth + left - containerWidth;
                            if(difference > 0){
                                jSlide.addClass('d-working');
                                let moveDistance = difference > containerWidth? containerWidth : difference,
                                    newLeft = left - moveDistance;
                                jSlide.css(CSS3_TRANSFORM, 'translateX(' + newLeft + 'px)').attr('left', newLeft);
                                setTimeout(function(){
                                    $('.J_sliced-list', jWrap).removeClass('d-working');
                                }, 600);
                            }
                        }
                    });
                    
                    function saveHandleByPicInfo(pic){
                        let originSrc = $('.J_pic-wrap-main img').attr('src');
                        arrDoApplyRecord.push(commonTool.mapSrcToInfo[originSrc]);
                        $('.J_ope-undo').addClass('d-usable');
                        $('.J_pic-wrap-main').data('editedPic', pic);
                        commonTool.mapSrcToInfo[pic.src] = pic;
                        $('.J_edit-menu-zip > a')[0].picSize = pic.size;
                        $('.J_edit-menu-zip > a')[0].picSrc = pic.src;
                        $('.J_pic-wrap-main').addClass('d-v-hidden');
                        $('.J_pic-area img').attr('src', pic.src);
                        commonTool.centerPic();
                        commonTool.updateAndShowFileInfo(pic);
                        $('.J_pic-wrap-main').removeClass('d-v-hidden');
                        $('.J_page-name').text('图片编辑');
                        $('.J_btn-return, .J_editor-btn-ok, .J_ope-undo, .J_ope-redo').removeClass('d-hidden');
                        $('.J_btn-cancel, .J_btn-apply').addClass('d-hidden');
                        $('.J_edit-menu').removeClass('d-hidden').nextAll().addClass('d-hidden');
                        $('.J_edit-menu-cut > a').removeClass('d-current');
                        $('.J_pic-wrap-main').removeClass('d-hidden').nextAll().addClass('d-hidden');
                    }
                    
                    function editorSaveHandle(){
                        let jAutoCut = $('.J_edit-menu-auto .J_sliced-list > a');
                        if(jAutoCut.length > 1){
                            let jMainPic = $('.J_pic-wrap-main img');
                            tool.autoSplitPic(commonTool.mapSrcToInfo[jMainPic.attr('src')], that._config.perPicSize, function(arrData){
                                that.parent._loading.hide();
                                let arrHtml = [];
                                arrData.forEach((item, index) => {
                                    item.index = index + 1;
                                    let html = template.compile(tpl.EDITED_LIST)(item);
                                    arrHtml.push(html);
                                });
                                let picData = $('.J_pic-wrap-main').data('editedPic');
                                $('.J_pending-list > li.J_editing .J_comp-list').html(arrHtml.join('')).removeClass('d-hidden').data('editedPic', picData);
                                $('.J_pending-list > li.J_editing').removeClass('J_editing');
                                $('.J_btn-auto-cut').removeClass('d-running').attr('state', 'edited').text('继续上传');
                                $('.J_btn-return').trigger('click');
                            });
                        }else{
                            let src = $('.J_pic-wrap-main img').attr('src');
                            if(src !== that._editorPicData.src){
                                let picData = commonTool.mapSrcToInfo[src],
                                    html = template.compile(tpl.EDITED_LIST)(picData);
                                $('.J_pending-list > li.J_editing .J_comp-list').html(html).removeClass('d-hidden').data('editedPic', picData);
                                $('.J_pending-list > li.J_editing').removeClass('J_editing');
                            }
                            $('.J_btn-auto-cut').removeClass('d-running').attr('state', 'edited').text('完成');
                            $('.J_btn-return').trigger('click');
                            that.parent._loading.hide();
                        }
                    }
                    $('.J_editor-btn-ok').bind('click', function(){
                        let sizeCheckPass = true,
                            kbCheckPass = true,
                            jPic = $('.J_pic-wrap-main img'),
                            nowEditorKb = Number($('.J_editing-kb').attr('size'));
                        if(that._sizeLimit){
                            let width = tool.css(jPic, 'width'),
                                height = tool.css(jPic, 'height');
                            if(!(width >= that._sizeLimit.minWidth && width <= that._sizeLimit.maxWidth && height >= that._sizeLimit.minHeight && height <= that._sizeLimit.maxHeight)){
                                sizeCheckPass = false;
                            }
                        }
                        if(nowEditorKb > that._config.perPicSize){
                            kbCheckPass = false;
                        }
                        const $autoCutPic = $('.J_edit-menu-auto .J_sliced-list > a');
                        if(!$autoCutPic.length){
                            if(sizeCheckPass === false){
                                Message.error(`当前图片尺寸不符合规则要求，请编辑后再进行完成操作`);
                                return;
                            }else if(kbCheckPass === false){
                                Message.error(`当前图片大小不符合规则要求，请编辑后再进行完成操作`);
                                return;
                            }
                        }else{
                            const {minWidth, maxWidth, minHeight, maxHeight} = that._sizeLimit;
                            sizeCheckPass = $autoCutPic.map(function(index, dom){
                                const picWidth = ~~$(dom).attr('point-w');
                                const picHeight = ~~$(dom).attr('point-h');
                                const isWidthOk = minWidth <= picWidth && picWidth <= maxWidth;
                                const isHeightOk = minHeight <= picHeight && picHeight <= maxHeight;
                                return isWidthOk && isHeightOk;
                            }).toArray().every(val => val);
                            if(!sizeCheckPass) {
                                Message.error('当前图片尺寸不符合规则要求，请编辑后再进行完成操作');
                                return;
                            }
                        }
                        that.parent._loading.show();
                        if(that._editMode === 'single'){
                            let jPic = $('.J_pic-wrap-main img'),
                                imageUrl = jPic.attr('src'),
                                width = jPic.width(),
                                height = jPic.height();
                            let jAutoCut = $('.J_edit-menu-auto .J_sliced-list > a');
                            if(jAutoCut.length > 1){
                                tool.autoSplitPic(commonTool.mapSrcToInfo[imageUrl], that._config.perPicSize, function(arrData){
                                    let count = 0;
                                    arrData.forEach((item, index) => {
                                        commonTool.uploadImageByUrl(item.src, function(){
                                            count++;
                                            if(count === arrData.length){
                                                Message.success('自动切成了' + arrData.length + '张图片，并已存入图片空间');
                                                typeof that.parent._config.uploadCallback === 'function' && that.parent._config.uploadCallback(arrData, true);
                                                setTimeout(function(){
                                                    that.parent.close();
                                                }, 1000);
                                            }
                                        }, item.name + '.' + item.type, that._config.cateId);
                                    });
                                });
                            }else if(imageUrl !== that._editorPicData.src) {
                                commonTool.uploadImageByUrl(imageUrl, function(picInfo){
                                    that.parent._loading.hide();
                                    typeof that.parent._config.uploadCallback === 'function' && that.parent._config.uploadCallback(picInfo);
                                    setTimeout(function(){
                                        that.parent.close();
                                    }, 1000);
                                }, that._editorPicData.name + '-1.' + that._editorPicData.type, that._config.cateId);
                            }
                            else{
                                that.parent.close();
                            }
                        }else{
                            editorSaveHandle();
                        }
                    });
                    $('.J_btn-return').bind('click', function(){
                        if(that._editMode === 'single') {
                            that.parent.close();
                        }else{
                            $('.J_list-page').removeClass('d-hidden');
                            $('.J_editor-page').addClass('d-hidden');
                            $('.J_colose-editor').addClass('d-hidden');
                            $('#popWinClose', top.document).show();
                            $('.J_pic-area img').attr('src', '');
                            arrDoApplyRecord = [];
                            arrReDoApplyRecord = [];
                            $('.J_ope-undo,.J_ope-redo').removeClass('d-usable');
                        }
                    });
                    $('.J_btn-cancel').bind('click', function(){
                        if($('.J_sub-edit-menu:visible').hasClass('J_edit-menu-auto')){
                            $('.J_edit-menu-auto .J_sliced-list').html('');
                            $('.J_edit-menu-auto .J_pic-mask-current').addClass('d-hidden');
                        }else if($('.J_sub-edit-menu:visible').hasClass('J_edit-menu-modify')){
                            let jImg = $('.J_pic-wrap-modify img');
                            $('.J_modify-user-width').val(jImg[0].naturalWidth);
                            $('.J_modify-user-height').val(jImg[0].naturalHeight);
                            $('.J_pic-wrap-modify').find('img').css({width: '', height: ''});
                        }
                        $('.J_page-name').text('图片编辑');
                        $('.J_file-ope-desc').text('图片尺寸');
                        $('.J_btn-return, .J_editor-btn-ok, .J_ope-undo, .J_ope-redo').removeClass('d-hidden');
                        $('.J_btn-cancel, .J_btn-apply').addClass('d-hidden');
                        $('.J_edit-menu').removeClass('d-hidden').nextAll().addClass('d-hidden');
                        $('.J_edit-menu-cut > a').removeClass('d-current');
                        $('.J_pic-wrap-main').removeClass('d-hidden').nextAll().addClass('d-hidden');
                        commonTool.centerPic();
                        commonTool.updateAndShowFileInfo(commonTool.mapSrcToInfo[$('.J_pic-wrap-main img').attr('src')]);
                    });
                    $('.J_btn-apply').bind('click', function(){
                        let jImg = $('.J_pic-wrap img:visible'),
                            newUrl = jImg.attr('src'),
                            naturalWidth = jImg[0].naturalWidth,
                            naturalHeight = jImg[0].naturalHeight;
                        $('.J_pic-area')[0].scrollTop = 0;
                        $('.J_file-ope-desc').text('图片尺寸');
                        let jEditingPic = $('.J_pic-wrap:visible');
                        if(jEditingPic.hasClass('J_pic-wrap-cut')){
                            let jBox = jEditingPic.find('.j-hotspots-box'),
                                
                                cssSet ={width: tool.css(jBox, 'width'), height: tool.css(jBox, 'height'), left: parseInt(jBox.css('left')), top: parseInt(jBox.css('top'))};
                            if(cssSet.left === 0 && cssSet.top === 0 && cssSet.width === naturalWidth && cssSet.height === naturalHeight){
                                $('.J_btn-cancel').trigger('click');
                            }else{
                                if(nowPicZoom !== 1){
                                    let jPic = $('.J_pic-wrap-cut .J_zoom-wrap'),
                                        preWidth = Math.round(jPic.width() * nowPicZoom),
                                        preHeight = Math.round(jPic.height() * nowPicZoom);
                                    commonTool.getLocalPicKb(function(len, src, base64){
                                        commonTool.getLocalPicKb(function(len, src, base64, newType){
                                            let picInfo = {name: that._editorPicData.name, src: base64, size: len / 1.3333, width: cssSet.width, height: cssSet.height};
                                            picInfo.sizeKb = ~~(picInfo.size / 1024);    
                                            that._editorPicData.type = newType;
                                            picInfo.type = that._editorPicData.type;
                                            saveHandleByPicInfo(picInfo);
                                        }, that._editorPicData.type, cssSet.left, cssSet.top, cssSet.width, cssSet.height, base64, cssSet.width, cssSet.height, that._editorPicData.quality, true, that._config.perPicSize, false, that._pngIsTransparent);
                                    }, that._editorPicData.type, 0, 0, jPic.width(), jPic.height(), newUrl, preWidth, preHeight, that._editorPicData.quality);
                                }else{
                                    commonTool.getLocalPicKb(function(len, src, base64, newType){
                                        let picInfo = {name: that._editorPicData.name, src: base64, size: len / 1.3333, width: cssSet.width, height: cssSet.height};
                                        picInfo.sizeKb = ~~(picInfo.size / 1024);    
                                        that._editorPicData.type = newType;
                                        picInfo.type = that._editorPicData.type;
                                        saveHandleByPicInfo(picInfo);
                                    }, that._editorPicData.type, cssSet.left, cssSet.top, cssSet.width, cssSet.height, newUrl, cssSet.width, cssSet.height, that._editorPicData.quality, true, that._config.perPicSize, false, that._pngIsTransparent);
                                }
                            }
                        }else if(jEditingPic.hasClass('J_pic-wrap-modify')){
                            if(~~$('.J_modify-user-width').val() !== naturalWidth || ~~$('.J_modify-user-height').val() !== naturalHeight){
                                let jPic = $('.J_pic-wrap-cut .J_zoom-wrap'),
                                    inputWidth = $('.J_modify-user-width').val(),
                                    inputHeight = $('.J_modify-user-height').val();
                                commonTool.getLocalPicKb(function(len, src, base64){
                                    let picInfo = {name: that._editorPicData.name, src: base64, size: len / 1.3333, width: inputWidth, height: inputHeight};
                                    picInfo.sizeKb = ~~(picInfo.size / 1024);    
                                    picInfo.type = that._editorPicData.type;
                                    saveHandleByPicInfo(picInfo);
                                }, that._editorPicData.type, 0, 0, jPic.width(), jPic.height(), newUrl, inputWidth, inputHeight, that._editorPicData.quality);
                            }else{
                                $('.J_btn-cancel').trigger('click');
                            }
                        }else if(jEditingPic.hasClass('J_pic-wrap-zip')){
                            let jZipPic = $('.J_pic-wrap-zip img'),
                                newPicType = jZipPic.attr('newPicType'),
                                zipPicSrc = jZipPic.attr('src'),
                                realSize = zipPicSrc.length / 1.3333,
                                picInfo = {name: that._editorPicData.name, src: zipPicSrc, size: realSize, width: jZipPic[0].naturalWidth, height: jZipPic[0].naturalHeight};
                            picInfo.sizeKb = ~~(realSize / 1024);    
                            if(newPicType){
                                that._editorPicData.type = newPicType;
                            }
                            picInfo.type = that._editorPicData.type;
                            saveHandleByPicInfo(picInfo);
                        }else if(jEditingPic.hasClass('J_pic-wrap-auto')){
                            $('.J_page-name').text('图片编辑');
                            $('.J_btn-return, .J_editor-btn-ok, .J_ope-undo, .J_ope-redo').removeClass('d-hidden');
                            $('.J_btn-cancel, .J_btn-apply').addClass('d-hidden');
                            $('.J_edit-menu').removeClass('d-hidden').nextAll().addClass('d-hidden');
                            $('.J_edit-menu-cut > a').removeClass('d-current');
                            $('.J_pic-wrap-main').removeClass('d-hidden').nextAll().addClass('d-hidden');
                        }
                    });
                },
                pannelCut: function(){
                    $('.J_edit-menu-cut > a').bind('click', function(){
                        if(!$(this).hasClass('d-current')){
                            
                            $(this).addClass('d-current').siblings().removeClass('d-current');
                            let fixType = $(this).attr('fixType'),
                                fixVal = $(this).attr('fixVal'),
                                needFix = $(this).attr('fixNeed'),
                                jPic = $('.J_pic-wrap:visible');
                            if(fixType === 'scale'){
                                fixVal = fixVal.split(':');
                                $('.J_pic-wrap-cut')[0].picDragObj.lockByFixScale(fixVal[0] / fixVal[1], 'd-control-transition');
                            }else if(fixType === 'px'){
                                needFix === 'false' && $('.J_pic-wrap-cut')[0].picDragObj.unlockFixed();
                                fixVal = fixVal.split(':');
                                let newWidth = parseInt($('.J_user-width').val()),
                                    newHeight = parseInt($('.J_user-height').val()),
                                    picOriginWidth = jPic.width(),
                                    picOriginHeight = jPic.height();
                                let limitRule = null;
                                if($(this).hasClass('J_ope-rule')){
                                    newWidth = parseInt(fixVal[0]);
                                    newHeight = parseInt(fixVal[1]);
                                    limitRule = {
                                        minWidth: newWidth,
                                        minHeight: newHeight,
                                        maxWidth: newWidth,
                                        maxHeight: newHeight
                                    };
                                }
                                $('.J_pic-wrap-cut')[0].picDragObj.lockByFixPx({width: Math.round(newWidth), height: Math.round(newHeight)}, 'd-control-transition', needFix === 'true'?  true: false, picOriginWidth * nowMinZoom, picOriginHeight * nowMinZoom, nowMinZoom, (newZoom) => {
                                    nowPicZoom = newZoom;
                                }, limitRule);
                                
                            }else if(fixType === 'range'){
                                $('.J_pic-wrap-cut')[0].picDragObj.unlockFixed();
                                fixVal = JSON.parse(fixVal);
                                for(let a in fixVal){
                                    fixVal[a] = Math.round(fixVal[a]);
                                }
                                $('.J_pic-wrap-cut')[0].picDragObj.lockByFixRange(fixVal, 'd-control-transition', ~~(jPic.width() * nowMinZoom), ~~(jPic.height() * nowMinZoom), nowMinZoom, (newZoom) => {
                                    nowPicZoom = newZoom;
                                });
                            }
                        }else{
                            $(this).removeClass('d-current');
                        }
                    });
                    let keyupTimer = 0;
                    $('.J_ope-user input').bind('keyup', function(e){
                        clearTimeout(keyupTimer);
                        if(e.keyCode === 13){
                            this.blur();
                        }
                        keyupTimer = setTimeout(() => {
                            this.blur();
                        }, 1500);
                    }).bind('focus', function(){
                        $(this).attr('preVal', $(this).val());
                        typeof this.select === 'function' && this.select();
                    }).bind('blur', function(){
                        if(!$(this).val()){
                            $(this).val($(this).attr('preVal'));
                        }
                        let jWidth = $('.J_user-width'),
                            jHeight = $('.J_user-height'),
                            jPic = $('.J_pic-wrap:visible'),
                            picOriginWidth = jPic.width(),
                            picOriginHeight = jPic.height(),
                            width = ~~jWidth.val(),
                            height = ~~jHeight.val(),
                            originWidth = ~~$('.J_edit-menu').attr('originWidth'),       
                            originHeight = ~~$('.J_edit-menu').attr('originHeight');     
                        if(width && height){
                            if(width <= 0 || width > originWidth || width <= 0 || height > originHeight){
                                $(this).val($(this).attr('preVal'));
                                return;
                            }
                            if($('.J_cut-user-lock').hasClass('d-locked')){
                                if(this === jWidth[0]){
                                    jHeight.val(Math.round(width / (originWidth / originHeight)));
                                }else{
                                    jWidth.val(Math.round(height * (originWidth / originHeight)));
                                }
                                width = ~~jWidth.val();
                                height = ~~jHeight.val();
                            }
                            $(this).closest('a').attr('fixVal', width + ':' + height);
                            $('.J_pic-wrap-cut')[0].picDragObj.lockByFixPx({width: width, height: height}, 'd-control-transition', false, ~~(picOriginWidth * nowMinZoom), ~~(picOriginHeight * nowMinZoom), nowMinZoom, function(newZoom){
                                if(newZoom !== -1){
                                    nowPicZoom = newZoom;
                                    if(nowPicZoom != nowMinZoom && nowMinZoom < 1){
                                        $('.J_zoom-wrap').addClass('d-can-move');
                                    }else{
                                        $('.J_zoom-wrap').removeClass('d-can-move');
                                    }
                                }
                            });
                        }
                    });
                    $('.J_cut-user-lock').bind('click', function(){
                        if($(this).hasClass('d-locked')){
                            $(this).removeClass('d-locked').attr('title', '点击使用宽高约束比例');
                        }else{
                            $(this).addClass('d-locked').attr('title', '点击解除宽高约束比例');
                        }
                    });
                },
                pannelModify: function(){
                    $('.J_modify-user-lock').bind('click', function(){
                        if($(this).hasClass('d-locked')){
                            $(this).removeClass('d-locked').attr('title', '点击使用宽高约束比例');
                        }else{
                            $(this).addClass('d-locked').attr('title', '点击解除宽高约束比例');
                        }
                    });
                    let keyupTimer = 0;
                    $('.J_modify-user-width, .J_modify-user-height').bind('keyup', function(e){
                        clearTimeout(keyupTimer);
                        if(e.keyCode === 13){
                            this.blur();
                        }
                        keyupTimer = setTimeout(() => {
                            this.blur();
                        }, 1500);
                    }).bind('focus', function(){
                        $(this).attr('preVal', $(this).val());
                        typeof this.select === 'function' && this.select();
                    }).bind('blur', function(){
                        let jWidth = $('.J_modify-user-width'),
                            jHeight = $('.J_modify-user-height'),
                            widthInput = ~~jWidth.val(),
                            heightInput = ~~jHeight.val(),
                            originWidth = ~~$('.J_edit-menu').attr('originWidth'),       
                            originHeight = ~~$('.J_edit-menu').attr('originHeight');     
                        if(widthInput === '' || heightInput === ''){
                            $(this).val($(this).attr('preVal'));
                            return;
                        }
                        if($('.J_modify-user-lock').hasClass('d-locked')){
                            if(this === jWidth[0]){
                                jHeight.val(Math.round(widthInput / (originWidth / originHeight)));
                            }else{
                                jWidth.val(Math.round(heightInput * (originWidth / originHeight)));
                            }
                        }
                        let jWrap = $('.J_pic-wrap-modify');
                        widthInput = jWidth.val();
                        heightInput = jHeight.val();
                        jWrap.find('img').css({width: widthInput, height: heightInput});
                        $(window).trigger('resize');
                        let inputWidth = $('.J_modify-user-width').val(),
                            inputHeight = $('.J_modify-user-height').val();
                        commonTool.getLocalPicKb(function(len, src, base64){
                            let realSize = base64.length / 1.3333;
                            $('.J_editing-kb').text(~~(realSize / 1024)).attr('size', realSize);
                        }, that._editorPicData.type, 0, 0, originWidth, originHeight, $('.J_pic-wrap-main img').attr('src'), inputWidth, inputHeight, that._editorPicData.quality);
                        $('.J_editing-size').text(widthInput + ' x ' + heightInput);
                    });
                },
                pannelZip: function(){
                    $('body').on('fullPicSizeCompleted', function(){
                        $('.J_edit-menu-zip > a')[0].picSize = $('.J_editing-kb').attr('size');
                        $('.J_edit-menu-zip > a')[0].picSrc = $('.J_pic-wrap:visible img').attr('src');
                    });
                    $('.J_edit-menu-zip > a').bind('click', function(){
                        if(!$(this).hasClass('d-current')){
                            $(this).addClass('d-current').siblings().removeClass('d-current');
                            let jTarget = $(this),
                                jMainImg = $('.J_pic-wrap-main img'),       
                                jZipPic = $('.J_pic-wrap-zip img'),         
                                type = ~~jTarget.attr('type'),
                                needAutoLimit = jTarget.attr('autoFitLimit'),
                                picSize = jTarget[0].picSize,
                                picSrc = jTarget[0].picSrc;
                            if(type === 'origin'){
                                jZipPic.attr('src', picSrc);
                                $('.J_editing-kb').text(~~(picSize / 1024));
                            }else{
                                if(picSize){
                                    jZipPic.attr('src', picSrc);
                                    $('.J_editing-kb').text(~~(picSize / 1024));
                                }else{
                                    let naturalWidth = jMainImg[0].naturalWidth,
                                        naturalHeight = jMainImg[0].naturalHeight,
                                        arrParam = [(len, src, base64, newPicType) => {
                                            jZipPic.attr('newPicType', newPicType);
                                            let realSize = base64.length / 1.3333;
                                            jTarget[0].picSize = realSize;
                                            jTarget[0].picSrc = base64;
                                            jZipPic.attr('src', base64);
                                            $('.J_editing-kb').text(~~(realSize / 1024));
                                        }, that._editorPicData.type, 0, 0, naturalWidth, naturalHeight, jMainImg.attr('src'), naturalWidth, naturalHeight, type * that._editorPicData.quality / 100];
                                    if(needAutoLimit){
                                        arrParam = arrParam.concat([true, that._config.perPicSize]);
                                    }else{
                                        arrParam = arrParam.concat([null, that._config.perPicSize, true]);
                                    }
                                    commonTool.getLocalPicKb(...arrParam);
                                }
                            }
                        }
                    });
                }
            };
            for(let fun in task){
                task[fun]();
            }
        }
        
        updateZoomByLeftPx(leftPx) {
            nowPicZoom = 1 - (100 - leftPx) / 100 * (1 - nowMinZoom);
            if(nowPicZoom != nowMinZoom && nowMinZoom < 1){
                $('.J_zoom-wrap').addClass('d-can-move');
            }else{
                $('.J_zoom-wrap').removeClass('d-can-move');
            }
            commonTool.picZoom(nowPicZoom, nowMinZoom);
        }
        
        dispose() {
            $('.J_edit-menu-auto .J_sliced-list', this.jContainer).off('click');
            $('.J_edit-menu > a', this.jContainer).off('click');
            $('.J_colose-editor', this.jContainer).off('click');
            $('.J_zoom-control-wrap', this.jContainer).off('click').off('mousemove');
            $('.J_ope-undo', this.jContainer).off('click');
            $('.J_ope-redo', this.jContainer).off('click');
            $('.J_list-left', this.jContainer).off('click');
            $('.J_list-right', this.jContainer).off('click');
        }
    }
    return Editor;
})($);
export default Editor;