import $ from "@/assets/map/jquery.min";
export function jqAjax(url, params, reqType = 'GET', dataProcess, 
                errFunc = function (xhr, status) {console.log("Error: " + status);}) { //AJAX异步请求数据
    //param: {y: 2020}
    $.ajax({ //使用ajax需注意在服务器端web.xml中配置跨域过滤器filter
        async: true,
        url: url,
        data: params,
        dataType: 'json',    //服务器返回数据类型
        type: reqType,       //HTTP请求类型
        timeout: 10000,      //超时时间
        success: dataProcess,
        error: errFunc,
    });
}

//数值检测函数
export function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}
//颜色解析函数
export function parseColor(hexStr) {
    return hexStr.length === 4 ? hexStr.substr(1).split('').map(function (s) { return 0x11 * parseInt(s, 16); }) : [hexStr.substr(1, 2), hexStr.substr(3, 2), hexStr.substr(5, 2)].map(function (s) { return parseInt(s, 16); })
}
export function pad(s) { // zero-pad 1 digit to 2
    return (s.length === 1) ? '0' + s : s;
}
/*
 *颜色梯度函数：返回起始颜色和结束颜色之间的渐变色带（按steps划分）
 */
export function gradientColors(start, end, steps) {
    //start 开始颜色: #FF0000
    //end 结束颜色: #0000FF
    //steps 颜色分解步长: max-min
    //gamma 透明度（伽马）
    var i, j, ms, me, output = [], so = [];
    var gamma = 2;
    var normalize = function (channel) {
        return Math.pow(channel / 255, gamma);
    };
    start = parseColor(start).map(normalize);
    end = parseColor(end).map(normalize);
    for (i = 0; i < steps; i++) {
        ms = i / (steps - 1);
        me = 1 - ms;
        for (j = 0; j < 3; j++) {
            so[j] = pad(Math.round(Math.pow(start[j] * me + end[j] * ms, 1 / gamma) * 255).toString(16));
        }
        output.push('#' + so.join(''));
    }
    return output;
}

export function labelZoomSize(z0, zoom) {
    //alert(zoom);
    var zoomDefault = z0; //z0=5;
    var lst = [0, 10, 12, 14, 16, 18, 20]; //font-size
    var i = parseInt(zoom - zoomDefault);
    if (i >= lst.length) {
        i = lst.length - 1;
    }
    if (i < 0) {
        i = 0;
    }
    return lst[i];
}

export function markerZoomSize(z0, zoom) {
    //alert(zoom);
    var zoomDefault = z0;
    var lst = [];//
    lst[0] = 8;
    var step = 4;
    for (var i = 1; i < 10; i++) { //div-marker-width/height
        lst[i] = lst[0] + step * i; //[8,12,16,20,24,28,32,36,40,44]
    }
    var delta = zoom - zoomDefault;
    var i = Math.round(delta, 0); //不能使用parseInt()，不安全，比如parseInt(0.0000000000000000002)返回2;
    //console.log("--->i= "+i+", z0="+z0+", zoom="+zoom);
    if (i >= lst.length) {
        i = lst.length - 1;
    }
    if (i < 0) {
        i = 0;
    }
    return lst[i];
}

export function getMin(arr) {
    var len = arr.length;
    var min = 999999999;
    for (var i = 0; i < len; i++) {
        min = min > arr[i] ? arr[i] : min;
    }
    return min;
}

export function getMax(arr) {
    var len = arr.length;
    var max = -999999999;
    for (var i = 0; i < len; i++) {
        max = max < arr[i] ? arr[i] : max;
    }
    return max;
}

export function getAverage(arr) {
    var len = arr.length;
    var sum = 0;
    for (var i = 0; i < len; i++) {
        sum = sum + arr[i];
    }
    return sum / len;
}

export function colorRGBtoHex(color) {
    var rgb = color.split(',');
    var r = parseInt(rgb[0]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2]);
    var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
}

Date.prototype.format = function (formatStr) { //日期对象格式化
    var date = this;
    /*  
    函数：填充0字符  
    参数：value-需要填充的字符串, length-总长度  
    返回：填充后的字符串  
    */
    var zeroize = function (value, length) {
        if (!length) {
            length = 2;
        }
        value = new String(value);
        for (var i = 0, zeros = ''; i < (length - value.length); i++) {
            zeros += '0';
        }
        return zeros + value;
    };
    return formatStr.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function ($0) {
        switch ($0) {
            case 'd': return date.getDate();
            case 'dd': return zeroize(date.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][date.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
            case 'M': return date.getMonth() + 1;
            case 'MM': return zeroize(date.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()];
            case 'yy': return new String(date.getFullYear()).substr(2);
            case 'yyyy': return date.getFullYear();
            case 'h': return date.getHours() % 12 || 12;
            case 'hh': return zeroize(date.getHours() % 12 || 12);
            case 'H': return date.getHours();
            case 'HH': return zeroize(date.getHours());
            case 'm': return date.getMinutes();
            case 'mm': return zeroize(date.getMinutes());
            case 's': return date.getSeconds();
            case 'ss': return zeroize(date.getSeconds());
            case 'l': return date.getMilliseconds();
            case 'll': return zeroize(date.getMilliseconds());
            case 'tt': return date.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return date.getHours() < 12 ? 'AM' : 'PM';
        }
    });
}