import PageTable from '@core/component/pageTable';
import ShortPagination from '@core/component/shortPagination';
import sendHttp,{fetch} from '@core/component//httpClient';
import Message from '@core/component/message';
import Modal,{Confirm,Alert} from '@core/component/modal';
import Loading from '@core/component/loading';
import FileUpload from '@core/component/fileUpload';
import Select from '@core/component/select';
import Tooltips from '@core/component/toast/tooltips';
import Dragable from '@core/util/Dragable';
import commonTool from './depend/utils.js';
import Editor from './depend/editor.js'
import tpl from './picEditorTpl';
import './picEditor.scss';
const picEditor = (($) => {
    let defaultConfig = {
        dataSource: [],    
        container: '.j-image-container',    
        editMode: 'single',         
        cateId: 0,                  
        sizeLimit: {minWidth:0, maxWidth: 20000, minHeight: 0, maxHeight: 20000},   
        perPicSize: 300 * 1024,     
        autoCutPercentage: 1,        
        uploadCallback: null        
    };
    let DefaultDialogConfig = {
        title: "<span class='cd-component cd-component-pic-icon'></span>图片编辑器<label class='J_titleDesc'></label>",
        className: "cd-pic-editor",
        content: '',
        type: Modal.ModalType.TYPE_FULL_SCREEN
    };
    let picStreamCompleted = false;
    return class picEditor {
        
        constructor(config) {
            this._config = this._getConfig(config);         
            this._arrPendingData = null;      
            this._zoomDragInstance = null;                          
            this._editorInstance = null;        
            let thisDialogConfig = $.extend(true, {}, DefaultDialogConfig, {
                onDomReady: ($dom) => {
                    this.jContainer = $dom.find('.J_content');    
                    this._loading = new Loading({
                        node: this.jContainer[0]
                    });
                    this._entrance();
                }
            });
            this.modalDialog = new Modal(thisDialogConfig);
        }
        
        _entrance(){
            let that = this;
            let containerHTML = tpl.CONTAINER;
            if(this._config.editMode === 'multiple'){
                containerHTML = containerHTML.replace('{{editorPageClassName}}', 'd-hidden');
            }else{
                containerHTML = containerHTML.replace('{{listPageClassName}}', 'd-hidden');
            }
            $(this.jContainer).append(containerHTML);
            $('.J_btn-auto-cut', this.jContainer).addClass('d-running').text('初始化中…');
            commonTool.preparePicData(this._config.dataSource, this._config.cateId).then((arr) => {
                arr.forEach((item, index) => {
                    if(item.name){
                        let arr = String(item.name).match(/^(.+)\.(\w+)/);
                        if(arr){
                            item.fullName = item.name;
                            item.name = arr[1];
                            item.type = arr[2].toLowerCase().replace('jpeg', 'jpg');
                        }
                    }
                });
                this._initData(arr, function () {
                    that._loading.hide();
                });
                this._bindEvent(arr);
            }, (reason) => {
                console.log('补全图片数组信息失败了：', reason);
            });
        }
        
        _initData(picData, initCallback) {
            let that = this;
            
            let task = {
                common: function(){
                    var sizeLimit = that._config.sizeLimit,
                        perPicSize = that._config.perPicSize;
                    if(sizeLimit){
                        var jRuleNode = $('.J_edit-menu-cut .J_ope-rule');
                        jRuleNode.removeClass('d-hidden');
                        if(sizeLimit.minWidth === sizeLimit.maxWidth && sizeLimit.minHeight === sizeLimit.maxHeight){
                            jRuleNode.attr('fixType', 'px').attr('fixVal', sizeLimit.minWidth + ':' + sizeLimit.minHeight);
                        }else{
                            jRuleNode.attr('fixType', 'range').attr('fixVal', JSON.stringify(sizeLimit));
                        }
                    }
                    if(sizeLimit){
                        $('.J_btn-auto-cut', that._config.jContainer).attr('state', 'edited').text('继续上传');
                    }
                    const TITLE_DESC = '（规则要求：{desc}）';
                    let arrRuleTip = [];
                    if(sizeLimit){
                        let strWH = '';
                        if(sizeLimit.minWidth === sizeLimit.maxWidth){
                            strWH += '宽度' + sizeLimit.minWidth;
                        }else{
                            strWH += '宽度' + sizeLimit.minWidth + '~' + sizeLimit.maxWidth;
                        }
                        if(sizeLimit.minHeight === sizeLimit.maxHeight){
                            strWH += '、高度' + sizeLimit.minHeight;
                        }else{
                            strWH += '、高度' + sizeLimit.minHeight + '~' + sizeLimit.maxHeight;
                        }
                        arrRuleTip.push(strWH);
                    }
                    if(perPicSize){
                        let unitM = perPicSize / 1024 / 1024,
                            unitKB = perPicSize / 1024,
                            strMaxSize = '';
                        if(unitM > 1){
                            strMaxSize = Number(unitM.toFixed(2)) + 'M';
                        }else{
                            strMaxSize = Number(unitKB.toFixed(2)) + 'KB';
                        }
                        arrRuleTip.push('单张图片大小' + strMaxSize);
                    }
                    $('.J_titleDesc').text(TITLE_DESC.replace('{desc}', arrRuleTip.join('，')));
                }
            };
            function single(){
                picData = picData[0];
                that._editorInstance = new Editor({
                    initCallback: () => {
                        let hasIn = false;  
                        if(that._config.sizeLimit){
                            let {minWidth, maxWidth, minHeight, maxHeight} = that._config.sizeLimit;
                            if(picData.width < minWidth || picData.height < minHeight || picData.width > maxWidth || picData.height > maxHeight){
                                hasIn = true;
                                $('.J_edit-menu > a[type="cut"]').trigger('click');
                            }
                        }
                        if(hasIn === false && picData.size > that._config.perPicSize){
                            $('.J_edit-menu > a[type="zip"]').trigger('click');
                        }
                        initCallback();
                    }, editorPic: picData, jContainer: that.jContainer, config: that._config, parent: that
                });
            }
            function multiple(){
                $('.J_pending-num', that._config.jContainer).text(picData.length + '张');
                var html = template.compile(tpl.PENDING_LIST)({list: picData});
                $('.J_pending-list', that._config.jContainer).html(html);
                that._arrPendingData = picData;
                picStreamCompleted = true;
                if(that._config.sizeLimit){
                    $('.J_btn-auto-cut', that._config.jContainer).removeClass('d-running').removeAttr('title');
                }else{
                    $('.J_btn-auto-cut', that._config.jContainer).removeClass('d-running').removeAttr('title').text('系统自动切图');
                }
                initCallback();
            }
            task.common();
            that._config.editMode === 'single'? single(): multiple();
        }
        
        _bindEvent(picData) {
            let that = this;
            var task = {
                common: function(){
                    $('.J_edit-menu-auto-view .J_sliced-list').on('click', 'a', function(){
                        var jContainer = $('.J_pic-area'),
                            size  = $(this).attr('point-kb'),
                            width = $(this).attr('point-w'),
                            height = $(this).attr('point-h'),
                            top = $(this).attr('point-y');
                        $(this).addClass('d-current').siblings().removeClass('d-current');
                        $('.J_pic-wrap-auto-view .J_pic-mask-current').removeClass('d-hidden').css({top: top + 'px', height: height + 'px'}).addClass('d-current');
                        var nowTop = jContainer[0].scrollTop,
                            nowPicZoom = commonTool.getContainZoom(),
                            containerHeight = jContainer.height(),
                            picTop = $('.J_zoom-wrap:visible').height() * (1 - nowPicZoom) / 2 + top * nowPicZoom,
                            picCenterTop = (containerHeight - height * nowPicZoom) / 2,
                            picBottom = picTop + height * nowPicZoom;
                        if(nowTop <= picTop && nowTop + containerHeight >= picBottom){
                        }else if(nowTop > picTop){
                            jContainer[0].scrollTop = picTop - picCenterTop;
                        }else if(nowTop + containerHeight < picBottom){
                            jContainer[0].scrollTop = picBottom + picCenterTop - containerHeight;
                        }
                        $('.J_editing-size').text(width + ' x ' + height);
                        $('.J_editing-kb').text(size);
                    });
                    $('.J_btn-view-return').bind('click', function(){
                        $('.J_list-page').removeClass('d-hidden');
                        $('.J_editor-page').addClass('d-hidden');
                        $('.J_pic-wrap-auto-view img').attr('src', '');
                        $('.J_editor-btn-ok, .J_btn-return, .J_edit-menu, .J_pic-wrap-main').removeClass('d-hidden');
                        $('.J_btn-view-return, .J_edit-menu-auto-view, .J_pic-wrap-auto-view').addClass('d-hidden');
                        $('.J_page-name').text('图片编辑');
                        $('.J_editor-page').addClass('d-hidden');
                        $('.J_list-page').removeClass('d-hidden');
                    });
                    let $zoomControl = $('.J_zoom-control');
                    that._zoomDragInstance = new Dragable({
                        target: $zoomControl,
                        handle: $zoomControl,
                        axis: 'x',
                        containment: '.J_zoom-control-wrap',
                        cursor: 'move',
                        startHandle: function(event,ui){
                            $('.J_zoom-tool').addClass('d-draging');
                        },
                        dragHandle: function(event,ui){
                            let leftPx = ui.position().left;
                            $('.J_zoom-control-bg').width(leftPx);
                            that._editorInstance.updateZoomByLeftPx(leftPx);
                        },
                        stopHandle: function(event,ui){
                            $('.J_zoom-tool').removeClass('d-draging');
                        }
                    });
                    let $dragBg = $('.J_pic-wrap');
                    $dragBg.each((index, dom) => {
                        that['_bgDragInstance' + index] = new Dragable({
                            target: dom,
                            handle: $(dom).find('.J_zoom-wrap'),
                            cursor: '-webkit-grabbing',
                            defineRepaint: (offset) => {
                                let $view = $('.J_pic-area'),
                                    $bg = $(dom).find('.J_zoom-wrap'),
                                    arrTransform = $bg.attr('style').match(/scale\((0\.\d+)\)/);
                                if(!arrTransform){
                                    return {};
                                }
                                let scale = Number(arrTransform[1]),
                                    realBgWidth = $bg.width() * scale,
                                    realBgHeight = $bg.height() * scale,
                                    minLeft = -($bg.width() * (scale + (1 - scale) / 2) - $view.width()),
                                    maxLeft = -$bg.width() * ((1 - scale) / 2),
                                    minTop = -($bg.height() * (scale + (1 - scale) / 2) - $view.height()),
                                    maxTop = -$bg.height() * ((1 - scale) / 2);
                                let x = offset.originX,
                                    y = offset.originY;
                                if(x < minLeft){
                                    x = minLeft;
                                }else if(x > maxLeft){
                                    x = maxLeft;
                                }
                                if(y < minTop){
                                    y = minTop;
                                }else if(y > maxTop){
                                    y = maxTop;
                                }
                                let returnVal = {
                                    x, y
                                };
                                if(realBgWidth < $view.width()){
                                    delete returnVal.x;
                                }
                                if(realBgHeight < $view.height()){
                                    delete returnVal.y;
                                }
                                return returnVal;
                            },
                            startHandle: function(event,ui){
                            },
                            dragHandle: function(event,ui){
                            },
                            stopHandle: function(event,ui){
                            }
                        });
                    });
                },
                autoCut: function(){
                    function closeHandle(pic){
                        typeof that._config.uploadCallback === 'function' && that._config.uploadCallback(pic);
                        setTimeout(function(){
                            that.close();
                        }, 1000);
                    }
                    $('.J_btn-auto-cut', that._config.jContainer).on('click', function(){
                        if($(this).hasClass('d-running')){
                            return;
                        }
                        if($(this).attr('state') === 'edited'){
                            var jPendList = $('.J_pending-list > li').not('.d-hidden'),
                                checkPass = true;
                            jPendList.each(function(){
                                if($(this).find('.J_comp-list > a').length === 0){
                                    checkPass = false;
                                    return false;
                                }
                            });
                            if(!checkPass){
                                Message.warn('系统检测到图片列表中，还有尚未编辑过的图片，请编辑后再进行上传操作');
                                return;
                            }
                            if(that._config.sizeLimit){
                                jPendList.each(function(){
                                    var jA = $(this).find('.J_comp-list > a'),
                                        width = jA.attr('data-width'),
                                        height = jA.attr('data-height');
                                    if(!(width >= that._config.sizeLimit.minWidth && width <= that._config.sizeLimit.maxWidth && height >= that._config.sizeLimit.minHeight && height <= that._config.sizeLimit.maxHeight)){
                                        checkPass = false;
                                        return false;
                                    }
                                });
                            }
                            if(!checkPass){
                                Message.warn('系统检测到图片列表中，还有图片尺寸不满足当前规则要求的，请编辑后再进行上传操作');
                                return;
                            }
                            that._loading.show();
                            var jList = $('.J_comp-list a'),
                                count = 0,
                                arrResult = [];
                            for(var i = 0; i < jList.length; i++){
                                var jItem = $(jList[i]),
                                    fileName = jItem.find('span').eq(0).text(),
                                    imageUrl = jItem.attr('data-source'),
                                    imageWidth = jItem.attr('data-width'),
                                    imageHeight = jItem.attr('data-height'),
                                    fileSize = jItem.attr('data-b');
                                (function(fileName, imageUrl, width , height){
                                    if(imageUrl.indexOf('data:image') === 0){
                                        commonTool.uploadImageByUrl(imageUrl, function(pic){
                                            count++;
                                            arrResult.push(pic);
                                            if(count === jList.length){
                                                closeHandle(arrResult);
                                            }
                                        }, fileName, that._config.cateId);
                                    }else{
                                        commonTool.uploadImageSpace(function(){
                                            count++;
                                            if(count === jList.length){
                                                closeHandle();
                                            }
                                        }, fileName, imageUrl, that._config.cateId, width, height, fileSize);
                                    }
                                })(fileName, imageUrl, imageWidth, imageHeight);
                            }
                        }else{
                            if(picStreamCompleted === false){
                                Message.warn('编辑器还在数据初始化中，请稍后再试');
                                return;
                            }
                            if(!$(this).hasClass('d-running')){
                                that._loading.show();
                                $(this).addClass('d-running').text('处理中…');
                                var jList = $('.J_pending-list > li').not('.d-hidden');
                                if(jList.length){
                                    $('.J_process-area').removeClass('d-hidden');
                                    var completePic = 0;        
                                    for(var i = 0, picLen = that._arrPendingData.length; i < picLen; i++){
                                        var item = that._arrPendingData[i],
                                            totalSubPic = 0,
                                            countSubPic = 0;
                                        jList[i].totalSubPic = 0;
                                        jList[i].countSubPic = 0;
                                        jList[i].process = 0;
                                        $('.J_process-state', jList[i]).text(jList[i].process + '%');
                                        $('.J_process-bar', jList[i]).width(jList[i].process + '%');
                                        if(item.type === 'png'){
                                            (function(jLi, item){
                                                commonTool.getPngAutoCutArrData(item.width, item.height, item.size, item.src, that._config.perPicSize).then((arrData) => {
                                                    item.list = arrData;
                                                    (function(jLi, item, totalSubPic, countSubPic){
                                                        jLi.process = jLi.process + 30;
                                                        $('.J_process-state', jLi).text(jLi.process + '%');
                                                        $('.J_process-bar', jLi).width(jLi.process + '%');
                                                        for(var j = 0; j < item.list.length; j++){
                                                            var cutItem = item.list[j];
                                                            cutItem.src = item.src;
                                                            cutItem.name = item.name;
                                                            cutItem.type = item.type;
                                                            cutItem.stream = item.stream;
                                                            (function(pic, listLen){
                                                                commonTool.getLocalPicKb(function (streamLength, src, subPicStream, newType) {
                                                                    countSubPic++;
                                                                    pic.type = newType;
                                                                    pic.src = subPicStream;
                                                                    pic.size = parseInt(streamLength / 1.3333);
                                                                    pic.sizeKb = parseInt(pic.size / 1024);           
                                                                    if(countSubPic === totalSubPic){
                                                                        completePic++;
                                                                        jLi.process = 100;
                                                                        $('.J_process-state', jLi).text(jLi.process + '%');
                                                                        $('.J_process-bar', jLi).width(jLi.process + '%');
                                                                    }
                                                                    if(completePic === that._arrPendingData.length){
                                                                        var html = template.compile(tpl.PENDING_LIST)({list: that._arrPendingData});
                                                                        $('.J_pending-list').html(html);
                                                                        $('.J_btn-auto-cut').removeClass('d-running').attr('state', 'edited').text('继续上传');
                                                                        that._loading.hide();
                                                                    }
                                                                }, pic.type, 0, pic.y, pic.width, pic.height, pic.src, pic.width, pic.height, item.quality, true, that._config.perPicSize);
                                                            })(cutItem, item.list.length);
                                                        }
                                                    })(jLi, item, item.list.length, countSubPic);
                                                });
                                            })(jList[i], item);
                                        }else if(item.type === 'jpg'){
                                            item.list = commonTool.getAutoCutArrPoints(item.width, item.height, item.src, item.size, that._config.perPicSize);
                                            (function(jLi, item, totalSubPic, countSubPic){
                                                jLi.process = jLi.process + 30;
                                                $('.J_process-state', jLi).text(jLi.process + '%');
                                                $('.J_process-bar', jLi).width(jLi.process + '%');
                                                for(var j = 0; j < item.list.length; j++){
                                                    var cutItem = item.list[j];
                                                    cutItem.src = item.src;
                                                    cutItem.name = item.name;
                                                    cutItem.type = item.type;
                                                    cutItem.stream = item.stream;
                                                    (function(pic, listLen){
                                                        commonTool.getLocalPicKb(function (streamLength, src, subPicStream, newType) {
                                                            countSubPic++;
                                                            pic.type = newType;
                                                            pic.src = subPicStream;
                                                            pic.size = parseInt(streamLength / 1.3333);
                                                            pic.sizeKb = parseInt(pic.size / 1024);           
                                                            if(countSubPic === totalSubPic){
                                                                completePic++;
                                                                jLi.process = 100;
                                                                $('.J_process-state', jLi).text(jLi.process + '%');
                                                                $('.J_process-bar', jLi).width(jLi.process + '%');
                                                            }
                                                            if(completePic === that._arrPendingData.length){
                                                                var html = template.compile(tpl.PENDING_LIST)({list: that._arrPendingData});
                                                                $('.J_pending-list').html(html);
                                                                $('.J_btn-auto-cut').removeClass('d-running').attr('state', 'edited').text('继续上传');
                                                                that._loading.hide();
                                                            }
                                                        }, pic.type, 0, pic.y, pic.width, pic.height, pic.src, pic.width, pic.height, item.quality, true, that._config.perPicSize);
                                                    })(cutItem, item.list.length);
                                                }
                                            })(jList[i], item, item.list.length, countSubPic);
                                        }
                                    }
                                }
                            }
                        }
                    });
                },
                listAction: function(){
                    $('.J_pending-list').on('click', '.J_edited-pic', function(){
                        if($(this).siblings().length){
                            $(this).closest('li').addClass('J_editing');
                            var tempVal = $('body').data('initEditor'),
                                isFirstInitEditor = tempVal === undefined? true: false,
                                jLi = $(this).closest('li'),
                                editingPic = (function(){
                                    var index = jLi.index(),
                                        storeData = jLi.find('.J_comp-list').data('editedPic');
                                    if(storeData){
                                        storeData.name = storeData.name + '.' + storeData.type;
                                        return storeData;
                                    }else{
                                        return picData[index];
                                    }
                                })();
                            if(that._editorInstance){
                                that._editorInstance.dispose();
                            }
                            that._editorInstance = new Editor({editorPic: editingPic, jContainer: that.jContainer, config: that._config, parent: that});
                            if(isFirstInitEditor){
                                $('body').data('initEditor', false);
                            }
                            var jLi = $(this).closest('li'),
                                index = jLi.index(),
                                jEditedPic = jLi.find('.J_comp-list > a'),
                                fullPicSrc = picData[index].src,    
                                fullPicName = picData[index].name + '.' + picData[index].type;    
                            if($(this).closest('.J_comp-list').data('editedPic')){
                                var data = jEditedPic.parent().data('editedPic');
                                fullPicSrc = data.src;
                            }
                            var arrPic = [],
                                countHeight = 0;
                            $(this).parent().find('.J_edited-pic').each(function(){
                                var jItem = $(this),
                                    height = ~~jItem.attr('data-height');
                                arrPic.push({sizeKb: jItem.attr('data-kb'), width: jItem.attr('data-width'), height: jItem.attr('data-height'), y: countHeight, src: jItem.attr('data-source'), name: jItem.attr('data-name')})
                                countHeight += height;
                            });
                            $('.J_pic-wrap-auto-view img').attr('src', fullPicSrc);
                            var html = template.compile(tpl.AUTO_CUT_VIEW_LIST)({list: arrPic});
                            $('.J_edit-menu-auto-view .J_sliced-list').html(html);
                            $('.J_editing-name').text(fullPicName);
                            $('.J_page-name').text('查看生成切图');
                            $('.J_editor-btn-ok, .J_btn-return, .J_ope-undo, .J_ope-redo, .J_edit-menu, .J_pic-wrap-main').addClass('d-hidden');
                            $('.J_btn-view-return, .J_edit-menu-auto-view, .J_pic-wrap-auto-view').removeClass('d-hidden');
                            $('.J_list-page').addClass('d-hidden');
                            $('.J_editor-page').removeClass('d-hidden');
                            commonTool.centerPic($('.J_pic-wrap-auto-view'));
                            $('.J_edit-menu-auto-view .J_sliced-list > a').eq(0).trigger('click');
                        }else{
                            $(this).closest('li').find('.J_action-edit').trigger('click');
                        }
                    });
                    $('.J_pending-list').on('click', '.J_action-edit', function(){
                        if($('.J_btn-auto-cut').hasClass('d-running')){
                            return;
                        }
                        $(this).closest('li').addClass('J_editing');
                        var tempVal = $('body').data('initEditor'),
                            isFirstInitEditor = tempVal === undefined? true: false,
                            jLi = $(this).closest('li'),
                            editingPic = (function(){
                                var index = jLi.index(),
                                    storeData = jLi.find('.J_comp-list').data('editedPic');
                                if(storeData){
                                    storeData.name = storeData.name + '.' + storeData.type;
                                    return storeData;
                                }else{
                                    return picData[index];
                                }
                            })();
                        $('.J_list-page').addClass('d-hidden');
                        $('.J_editor-page').removeClass('d-hidden');
                        if(that._editorInstance){
                            that._editorInstance.dispose();
                        }
                        that._editorInstance = new Editor({editorPic: editingPic, jContainer: that.jContainer, config: that._config, parent: that});
                        if(isFirstInitEditor){
                            $('body').data('initEditor', false);
                        }
                    });
                    $('.J_pending-list').on('click', '.J_action-remove', function(){
                        if($('.J_btn-auto-cut').hasClass('d-running')){
                            return;
                        }
                        var jLi = $(this).closest('li');
                        if(jLi.siblings().length === 0){
                            Message.error('至少应该保留一张待上传图片');
                            return;
                        }
                        that._arrPendingData.splice(jLi.index(), 1);
                        jLi.fadeOut(400, function(){
                            $('.J_pending-num').text(that._arrPendingData.length);
                            $(this).remove();
                        });
                    });
                }
            };
            task.common();
            task.autoCut();
            if(that._config.editMode === 'multiple'){
                task.listAction();
            }
        }
        
        _getConfig(config) {
            return $.extend({}, defaultConfig, config);
        }
        
        close() {
            this.modalDialog.close();
            this.dispose();
        }
        
        dispose() {
            this._zoomDragInstance.dispose();
            $('.J_pic-wrap').each((index) => {
                this['_bgDragInstance' + index].dispose();
            });
            if(this._editorInstance){
                this._editorInstance.dispose();
            }
        }
    };
})($);
export default picEditor;