import {fetch} from '@core/component//httpClient';
import domain from '@core/util/domain';
let picZoomTimer = 0;
const commonTool = {
    
    getContainZoom: function(){
        let jPic = $('.J_pic-wrap:visible'),
            jContain = $('.J_pic-area'),
            pWdith = jPic.width(),
            pHeight = jPic.height(),
            cWidth = jContain.width(),
            cHeight = jContain.height(),
            zoom = 1;
        if(pWdith / pHeight > cWidth / cHeight){
            zoom = cWidth / pWdith;
        }else{
            zoom = cHeight / pHeight;
        }
        if(zoom > 1){
            zoom = 1;
        }
        return zoom;
    },
    
    preparePicData: async (arr, cateId) => {
        let arrPromise = [];
        arr && arr.length && Array.from(arr).forEach(async (item) => {
            if(Object.prototype.toString.call(item) === '[object File]'){
                arrPromise.push((async () => {
                    let pic = await commonTool.readLocalFile(item);
                    let {quality} = await commonTool.getConvertQuality(pic.size, pic.type, pic.width, pic.height, pic.src);
                    pic.quality = quality;
                    commonTool.mapSrcToInfo[pic.src] = pic;
                    return pic;
                })());
            }else{
                if(window.page_data.isSDKM){
                    arrPromise.push((async () => {
                        let data = item.picInfo,
                            pic = {
                                name: item.name,
                                size : data.size,    
                                sizeKb : ~~(data.size / 1024),    
                                width : data.width,
                                height : data.height,
                                type : data.type.toLowerCase().replace('jpeg', 'jpg')
                            };
                        let {quality, base64Pic} = await commonTool.getConvertQuality(pic.size, pic.type, pic.width, pic.height, item.src);
                        pic.quality = quality;
                        pic.src = base64Pic;            
                        commonTool.mapSrcToInfo[pic.src] = pic;
                        return pic;
                    })());
                }
                else{
                    arrPromise.push((async () => {
                        let data = await commonTool.getUploadPicInfoById(item.imgId, cateId),
                            pic = {
                                name: item.name,
                                size : data.imgSize,    
                                sizeKb : ~~(data.imgSize / 1024),    
                                width : data.imgWidth,
                                height : data.imgHeight,
                                type : data.imgType.toLowerCase().replace('jpeg', 'jpg')
                            };
                        let {quality, base64Pic} = await commonTool.getConvertQuality(pic.size, pic.type, pic.width, pic.height, item.src);
                        pic.quality = quality;
                        pic.src = base64Pic;            
                        commonTool.mapSrcToInfo[pic.src] = pic;
                        return pic;
                    })());
                }
            }
        });
        return Promise.all(arrPromise);
    },
    
    readLocalFile: async (file) => {
        let reader = new FileReader(),
            data = null;
        await new Promise((resolve, reject) => {
            reader.onload = (e) => {
                let img = new Image(),
                    src = e.target.result;
                img.onload = function() {
                    let picWidth = this.naturalWidth,
                        picHeight = this.naturalHeight,
                        arrTemp = file.name.split('.'),
                        fileType = arrTemp[arrTemp.length - 1];
                    data = {
                        name: file.name,
                        width: picWidth,
                        height: picHeight,
                        size: file.size,
                        sizeKb : ~~(file.size / 1024),    
                        type : fileType.toLowerCase().replace('jpeg', 'jpg'),
                        src: e.target.result
                    };
                    resolve();
                };
                img.onerror = () => {
                    reject();
                }
                img.src = src;
            };
            reader.onerror = () => {
                reject();
            };
            reader.readAsDataURL(file);
        });
        return data;
    },
    
    parsePicArr: (data) => {
        if(data.filesVar){
            var arr = data.filesVar.split('.'),
                tempData = window.top;
            for(var i = 0; i < arr.length; i++){
                tempData = tempData[arr[i]];
            }
            data.data = tempData;
        }else{
            console.error('调用图片编辑器参数传递错误，缺少必须的filesVar参数');
        }
    },
    css3Prefix: (() => {
        var divTemp = document.createElement("div"),
            arrCss = ["","webkit","moz","ms"],
            obj = {TRANSFORM: "", TRANSITION: "",TRANSITIONEND:""};
        for(var i = 0; i < arrCss.length; i++){
            var test = arrCss[i]? (arrCss[i] + "Transform"): "transform";
            if(test in divTemp.style){
                obj.TRANSFORM = test;
                break;
            }
        }
        for(i = 0; i < arrCss.length; i++){
            test = arrCss[i]? (arrCss[i] + "Transition"): "transition";
            if(test in divTemp.style){
                obj.TRANSITION = test;
                var temp =  obj.TRANSITION === "transition" ? "end" :"End";
                obj.TRANSITIONEND = test + temp;
                break;
            }
        }
        return obj;
    })(),
    
    getImageIOByUrl: (src, callback) => {
        var protocolHeader = {
                jpg: 'data:image/jpg;base64,',
                png: 'data:image/png;base64,'
            },
            imgType = src.match(/\.[a-zA-Z]+/g);
        if(imgType){
            protocolHeader = protocolHeader[imgType[imgType.length - 1].substring(1)];
        }
        if(typeof protocolHeader !== 'string' && protocolHeader.length === 0){
            console.log('图片地址后缀名不能为空，且格式必须是jpg或者png');
            return;
        }
        $.ajax({
            url: `${domain.node2}/uploadImage/getImageIOByUrl.html`,
            data: {
                imageUrl: src
            },
            success: (data) => {
                if(data.result){
                    callback(protocolHeader + data.data.imgIO);
                }else{
                    console.log('getImageIOByUrl.html接口调用异常');
                }
            }
        });
    },
    
    getImageInfo: async (src) => {
        let result = null;
        await new Promise((resolve, reject) => {
            $.ajax({
                url: `${domain.node2}/uploadImage/getImageInfoJsonpByUrl.html`,
                data: {
                    imageUrl: src
                },
                dataType: 'jsonp',
                success: (data) => {
                    if(data.result === true){
                        result = JSON.parse(data.data.imageInfo);
                        resolve();
                    }else{
                        reject();
                    }
                },
                error: () => {
                    reject();
                }
            });
        });
        return result;
    },
    
    getConvertQuality: async (originSize, picType, width, height, picIO) => {
        let quality = 0.99,
            base64Pic = '',
            type = {'png': 'image/png', 'jpg': 'image/jpeg'};
        if($('#picCanvas').length === 0){
            $('body').append('<canvas id="picCanvas" style="position: absolute; left: 0; top: 0; z-index: 100; visibility: hidden; pointer-events: none;"></canvas>');
        }
        let canvas = $('#picCanvas')[0],
            pic = new Image();
        pic.crossOrigin = 'anonymous';    
        await new Promise((resolve, reject) => {
            pic.onload = () => {
                $('#picCanvas').attr('width', width).attr('height', height);
                let noFind = true,
                    can2d = canvas.getContext('2d');
                can2d.drawImage(pic, 0, 0, width, height);
                if(picType === 'png'){
                    quality = 1;
                    base64Pic = canvas.toDataURL(type[picType], quality);
                    resolve();
                }else{
                    while(noFind){
                        base64Pic = canvas.toDataURL(type[picType], quality);
                        if(base64Pic.length / 1.3333 < originSize){
                            noFind = false;
                            quality = quality + 0.01;
                            resolve();
                        }else{
                            quality = (quality - 0.01) * 100 / 100; 
                        }
                    }
                }
            };
            pic.onerror = () => {
                reject();
            };
            pic.src = picIO;
        });
        return {quality, base64Pic};
    },
    
    setZipMenuAvailable: (can) => {
        let $menu = $('.J_edit-menu .d-ope-zip');
        if(can){
            $menu.removeClass('cd-menu-disable');
        }else{
            $menu.addClass('cd-menu-disable');
        }
    },
    
    setAutoMenuAvailable: (picWidth, sizeLimit) => {
        const $menu = $('.J_edit-menu .d-ope-auto');
        const {minWidth, maxWidth} = sizeLimit;
        if(minWidth <= picWidth && picWidth <= maxWidth){
            $menu.removeClass('cd-menu-disable');
        }else{
            $menu.addClass('cd-menu-disable');
        }
    },
    
    pngIsTransparent: (callback, picSrc) => {
        if($('#picCanvas').length === 0){
            $('body').append('<canvas id="picCanvas" style="position: absolute; left: 0; top: 0; z-index: 100; visibility: hidden; pointer-events: none;"></canvas>');
        }
        var canvas = $('#picCanvas')[0],
            can2d = canvas.getContext('2d'),
            pic = new Image();
        pic.crossOrigin = 'anonymous';    
        pic.onload = () => {
            let isTransparent = false,
                width = pic.naturalWidth,
                height = pic.naturalHeight;
            $('#picCanvas').attr({'width': width, 'height': height});
            can2d.drawImage(pic, 0, 0, width, height);
            let imgData = can2d.getImageData(0, 0, width, height);
            outer: for(let i = 0; i < imgData.height; ++i){
                for(let j = 0; j < imgData.width; ++j){
                    let len = i * 4 * imgData.width + j * 4;  
                    if(imgData.data[len + 3] !== 255){
                        isTransparent = true;
                        break outer;
                    }
                }
            }
            callback(isTransparent);
        };
        pic.src = picSrc;
    },
    
    getLocalPicKb: (callback, picType, x, y, width, height, picIO, canvasWidth, canvasHeight, picQuality, needLimit, perPicSize, needToLimitHalf, pngIsTransparent) => {
        let argLen = arguments.length,
            quality = picQuality || .92,
            picSrc = picIO,    
            newType = picType,  
            type = {'png': 'image/png', 'jpg': 'image/jpeg'};
        if($('#picCanvas').length === 0){
            $('body').append('<canvas id="picCanvas" style="position: absolute; left: 0; top: 0; z-index: 100; visibility: hidden; pointer-events: none;"></canvas>');
        }
        let canvas = $('#picCanvas')[0],
            pic = new Image();
        pic.crossOrigin = 'anonymous';    
        pic.onload = () => {
            width = width || pic.naturalWidth;
            height = height || pic.naturalHeight;
            $('#picCanvas').attr('width', canvasWidth || width).attr('height', canvasHeight || height);
            var can2d = canvas.getContext('2d');
            if(argLen === 2){
                can2d.drawImage(pic, 0, 0, width, height);
            }else{
                can2d.drawImage(pic, x, y, width, height, 0, 0, canvasWidth, canvasHeight);
            }
            if(pngIsTransparent !== true && (needLimit || needToLimitHalf)){
                if(picType === 'png'){
                    base64Pic = canvas.toDataURL('image/jpeg', 1);
                    quality = 1;
                    let newPic = new Image();
                    newPic.src = base64Pic;
                    can2d.drawImage(newPic, 0, 0, width, height);
                    newType = 'jpg';
                    picType = newType;
                }
                let noFind = true;
                while(noFind){
                    let base64Pic = canvas.toDataURL(type[picType], quality);
                    if(base64Pic.length / 1.3333 < perPicSize){
                        noFind = false;
                        if(needToLimitHalf) {
                            let harfQuality = (1 + quality) / 2;
                            base64Pic = canvas.toDataURL(type[picType], harfQuality);
                        }
                        callback(base64Pic.length, picSrc, base64Pic, newType);
                    }else{
                        quality = (quality - 0.01) * 100 / 100; 
                    }
                }
            }else{
                if(picType === 'jpg'){
                    var base64Pic = canvas.toDataURL(type[picType], quality);
                }else if(picType === 'png'){
                    var base64Pic = canvas.toDataURL(type[picType]);
                }
                callback(base64Pic.length, picSrc, base64Pic, newType);
            }
        };
        pic.src = picSrc;
    },
    
    getLocalPngPicKb: (callback, perLimit, startY, width, height, picIO) => {
        if($('#picCanvas').length === 0){
            $('body').append('<canvas id="picCanvas" style="position: absolute; left: 0; top: 0; z-index: 100; visibility: hidden; pointer-events: none;"></canvas>');
        }
        var canvas = $('#picCanvas')[0],
            initHeight = 50,
            pic = new Image();
        pic.crossOrigin = 'anonymous';    
        pic.onload = () => {
            var can2d = canvas.getContext('2d'),
                noFind = true;      
            $('#picCanvas').attr('width', width).attr('height', initHeight);
            can2d.drawImage(pic, 0, startY, width, initHeight, 0, 0, width, initHeight);
            while(noFind){
                var base64Pic = canvas.toDataURL('image/png');
                if(base64Pic.length / 1.3333 > perLimit || initHeight === height - startY){
                    noFind = false;
                    callback({data: base64Pic, x: 0, y: startY, width: width, height: initHeight, size: base64Pic.length / 1.3333});
                }else{
                    initHeight = initHeight + 5 <= height - startY? initHeight + 5: height - startY;       
                    $('#picCanvas').attr('width', width).attr('height', initHeight);
                    can2d.drawImage(pic, 0, startY, width, initHeight, 0, 0, width, initHeight);
                }
            }
        };
        pic.src = picIO;
    },
    
    getAutoCutArrPoints: (width, height, src, fileSize, perPicSize) => {
        var total = Math.ceil(fileSize / perPicSize),
            peiHeight = Math.ceil(height / total),
            arr = [];
        for(var i = 0; i < total; i++){
            if(total === 1){
                arr.push({x: 0, y: 0, width: width, height: height, src: src});
            }else{
                if(i !== total - 1){
                    arr.push({x: 0, y: i * peiHeight, width: width, height: peiHeight, src: src});
                }else{
                    arr.push({x: 0, y: i * peiHeight, width: width, height: height - i * peiHeight, src: src});
                }
            }
        }
        return arr;
    },
    
    getPngAutoCutArrData: (width, height, fileSize, picIO, perPicSize) => {
        var subPicArr = [],
            index = 0,
            nowTop = 0;
        return new Promise((resolve, reject)=>{
            commonTool.getLocalPngPicKb((data) => {
                var canvasSize = data.data.length,
                    total = Math.ceil(canvasSize / (perPicSize * 1.3333)),     
                    realPerSize = ~~(canvasSize / total / 1.3333);         
                function createOne(){
                    index++;
                    commonTool.getLocalPngPicKb((data) => {
                        subPicArr.push(data);
                        nowTop += data.height;
                        if(nowTop < height){
                            createOne(nowTop);
                        }else{
                            resolve(subPicArr);
                        }
                    }, realPerSize, nowTop, width, height, picIO);
                }
                createOne();
            }, 100*1024*1024, nowTop, width, height, picIO);
        });
    },
    
    createPicUrlByParam: (css, quality, zoomSize, src) => {
        var url = src || $('.J_pic-wrap-main img').attr('src'),
            imgType = url.match(/\.[a-zA-Z]+/g),
            type = imgType[imgType.length - 1].substring(1);    
        if(zoomSize){
            url = url.replace('/jfs/','/s' + zoomSize + '_jfs/');
        }
        if(css){
            url += '!cr_' + css.width + 'x' + css.height + '_' + css.left + '_' + css.top;
        }
        if(type === 'jpg'){
            if(quality){
                url += '!q' + quality;
            }else{
                url += '!q100';
            }
            url = url + '.' + type;
        }
        return url;
    },
    
    uploadImageByUrl: (url, callback, fileName, cateId, platform) => {
        var submitData = {
            fileName: fileName,
            cateId: cateId || 0
        };
        if(url.indexOf('data:image') === 0){
            submitData.imageBytes = url.replace(/^data:image\/\w+;base64\,/, '');     
        }
        if(window.page_data.isSDKM){
            fetch({
                url: `${domain.zxDesigner}/sdk/imgspace/uploadImageBase64.html`,
                method: 'post',
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                data: submitData
            }).then((data) => {
                if (data.success) {
                    let picInfo = {cateId: cateId, imgId: data.data.imgId, name: fileName, src: data.data.imgUrl, size: data.data.imgSize, width: data.data.imgWidth, height: data.data.imgHeight};
                    picInfo.sizeKb = ~~(picInfo.size / 1024);    
                    picInfo.type = fileName.match(/\.(\w+)$/)[1].toLowerCase();
                    commonTool.mapSrcToInfo[submitData.imageUrl] = picInfo;
                    callback(picInfo);
                }else{
                    console.log('uploadImageByUrl.html接口调用异常');
                }
            });
        }
        else{
            fetch({
                url: domain.material + '/token/getToken',
                method: 'post',
                dataType: 'json',
                contentType:"application/json;charset=utf-8",
                xhrFields: {
                    withCredentials: true
                }
            }).then((result) => {
                fetch({
                    url: domain.material + '/shopImg/uploadByStr',
                    method: 'post',
                    headers:{
                        materialtoken:result.data
                    },
                    dataType: 'json',
                    contentType:"application/json;charset=utf-8",
                    xhrFields: {
                        withCredentials: true
                    },
                    data: JSON.stringify(submitData)
                }).then((data) => {
                    if(data.code === 0){
                        let picInfo = {cateId: cateId, imgId: data.data.imgId, name: fileName, src: data.data.url, size: data.data.size, width: data.data.width, height: data.data.height};
                        picInfo.sizeKb = ~~(picInfo.size / 1024);    
                        picInfo.type = fileName.match(/\.(\w+)$/)[1].toLowerCase();
                        commonTool.mapSrcToInfo[submitData.imageUrl] = picInfo;
                        callback(picInfo);
                    }else{
                        console.log('uploadImageByUrl.html接口调用异常');
                        let msg = '图片上传失败';
                        if(data.message){
                            msg += '：' + data.message;
                        }
                        alert(msg);
                    }
                });
            });
        }
    },
    
    getUploadPicInfoById: (picId, cateId) => {
        let requestTotal = 0;
        return new Promise((resolve, reject) => {
            let getInfo = () => {
                if(requestTotal > 10){
                    reject();
                }
                requestTotal++;
                fetch({
                    url: domain.material + '/shopImg/getImgRet',
                    method: 'post',
                    dataType: 'json',
                    contentType:"application/json;charset=utf-8",
                    xhrFields: {
                        withCredentials: true
                    },
                    data: JSON.stringify({
                        imgId: picId,
                        cateId: cateId
                    })
                }).then((data) => {
                    if(data.data.result.length === 0){
                        setTimeout(getInfo, 500);
                    }else{
                        resolve(data.data.result[0]);
                    }
                });
            };
            getInfo();
        });
    },
    
    uploadImageSpace: (callback, fileName, imageUrl, cateId, width, height, size, flag) => {
        $.ajax({
            url: `${domain.node2}/uploadImage/uploadImageSpace.html`,
            data: {
                fileName: fileName,
                imageUrl: imageUrl,
                flag: flag || 'app',
                cateId: cateId,
                'imgUploadBean.fileSize': ~~size,
                'imgUploadBean.width': width,
                'imgUploadBean.height': height,
                addTime: Date.now()
            },
            type: 'post',
            success: (data) => {
                if(data.result){
                    callback();
                }else{
                    console.log('uploadImageSpace.html接口调用异常');
                }
            }
        });
    },
    
    centerPic: (jWrap) => {
        var jContent = jWrap || $('.J_pic-wrap:visible'),
            jContainer = $('.J_pic-area'),
            width = jContent.width(),
            height = jContent.height(),
            wrapWidth = jContainer.width(),
            wrapHeight = jContainer.height(),
            left = (wrapWidth - width) / 2,
            top = (wrapHeight - height) / 2;
        $('.J_pic-wrap,.J_pic-wrap-auto-view').css({left: left, top: top}).removeClass('d-v-hidden');
    },
    
    adjustDragArea: (nowPicZoom, jWrap) => {
        jWrap = jWrap || $('.J_pic-wrap:visible');
        var jPicWrap = $('.J_zoom-wrap', jWrap);
        if(jPicWrap.length){
            var jDrager = $('.d-drag-box', jWrap),
                dragLeft = parseFloat(jDrager.css('left')),
                dragTop = parseFloat(jDrager.css('top')),
                width = jPicWrap.width(),
                height = jPicWrap.height(),
                newLeft = Math.round(width * (1 - nowPicZoom) / 2),
                newTop = Math.round(height * (1 - nowPicZoom) / 2),
                newWidth = Math.round(width * nowPicZoom),
                newHeight = Math.round(height * nowPicZoom);
            $('.J_drag-control', jWrap).css({left: newLeft, top: newTop, width: newWidth, height: newHeight});
            jDrager.css('background-size', newWidth + 'px ' + newHeight + 'px');
            if(newWidth < dragLeft + jDrager.width() || newHeight < dragTop + jDrager.height()){
                jWrap[0].picDragObj.lockByFixPx({left: 0, top: 0, width: newWidth, height: newHeight}, 'd-control-transition', false);
            }
            jWrap[0].picDragObj && jWrap[0].picDragObj._updateOffset();
        }
    },
    
    computeAndShowFileInfo: () => {
        var pic = new Image();
        pic.onload = function() {
            var fileSize = ~~(src.length / 1.3333);
            $('.J_editing-size').text(this.naturalWidth + ' x ' + this.naturalHeight);
            $('.J_editing-kb').text(~~(fileSize / 1024)).attr('size', fileSize);
            $('.J_dia-foot').addClass('d-has-val');
            $('.J_edit-menu-zip .J_origin')[0].picSize = fileSize;
            $('body').trigger('fullPicSizeCompleted');
        };
        pic.src = src;
    },
    
    updateAndShowFileInfo: (data, isFirst) => {
        $('.J_editing-size').text(data.width + ' x ' + data.height);
        $('.J_editing-kb').text(~~(data.size / 1024)).attr('size', data.size);
        $('.J_edit-menu-zip > a').each((index, dom) => {
            if(index === 0){
                dom.picSize = data.size;
                dom.picSrc = data.src;
            }else{
                dom.picSize = null;
                dom.picSrc = null;
            }
        });
        if(isFirst){
            $('.J_dia-foot').addClass('d-has-val');
            $('.J_edit-menu-zip .J_origin')[0].picSize = data.size;
            $('body').trigger('fullPicSizeCompleted');
        }
        if(data.src.match(/^(https?:)?\/\//)){
            commonTool.mapSrcToInfo[data.src] = data;
        }
    },
    
    picZoom: (zoom, nowMinZoom, needUpdateControlBar) => {
        $('.J_pic-wrap .J_zoom-wrap').css(commonTool.css3Prefix.TRANSFORM, 'scale(' + zoom + ')');
        if(needUpdateControlBar){
            var jContainer = $('.J_pic-area'),
                jWrap = $('.J_pic-wrap:visible'),
                newPx = (zoom - nowMinZoom) / (1 - nowMinZoom) * 100 + 'px';
            $('.J_zoom-control').css('left', newPx);
            $('.J_zoom-control-bg').width(newPx);
        }
        clearTimeout(picZoomTimer);
        picZoomTimer = setTimeout(() => {
            $('.J_zoom-info').css('left', newPx).text('比例：' + Number((zoom * 100).toFixed(2)) + '%');
        }, 100);
        commonTool.adjustDragArea(zoom);
    },
    mapSrcToInfo: {}        
};
export default commonTool;