let type = function (str) {
    return typeof str;
};
let jsonpID = 0,
    key,
    name,
    rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
    scriptTypeRE = /^(?:text|application)\/javascript/i,
    xmlTypeRE = /^(?:text|application)\/xml/i,
    jsonType = 'application/json',
    htmlType = 'text/html',
    blankRE = /^\s*$/

let ajax = function (options) {
    let settings = extend({}, options || {})
    for (key in ajax.settings) if (settings[key] === undefined) settings[key] = ajax.settings[key]

    ajaxStart(settings)

    if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
        RegExp.$2 != location.host

    let dataType = settings.dataType, hasPlaceholder = /=\?/.test(settings.url)
    if (dataType == 'jsonp' || hasPlaceholder) {
        if (!hasPlaceholder) settings.url = appendQuery(settings.url, (options.jsonp || 'callback') + '=?')
        return ajax.JSONP(settings)
    }

    if (!settings.url) settings.url = location.toString()
    serializeData(settings)

    let mime = settings.accepts[dataType],
        baseHeaders = {},
        protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : location.protocol,
        xhr = ajax.settings.xhr(), abortTimeout

    if (!settings.crossDomain) baseHeaders['X-Requested-With'] = 'XMLHttpRequest'
    if (mime) {
        baseHeaders['Accept'] = mime
        if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
        xhr.overrideMimeType && xhr.overrideMimeType(mime)
    }
    if (settings.contentType || (settings.data && settings.type.toUpperCase() != 'GET'))
        baseHeaders['Content-Type'] = (settings.contentType || 'application/x-www-form-urlencoded')
    settings.headers = extend(baseHeaders, settings.headers || {})

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            clearTimeout(abortTimeout)
            let result, error = false
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
                dataType = dataType || mimeToDataType(xhr.getResponseHeader('content-type'))
                result = xhr.responseText

                try {
                    if (dataType == 'script') (1, eval)(result)
                    else if (dataType == 'xml') result = xhr.responseXML
                    else if (dataType == 'json') result = blankRE.test(result) ? null : JSON.parse(result)
                } catch (e) {
                    error = e
                }

                if (error) ajaxError(error, 'parsererror', xhr, settings)
                else ajaxSuccess(result, xhr, settings)
            } else {
                ajaxError(null, 'error', xhr, settings)
            }
        }
    }

    let async = 'async' in settings ? settings.async : true;
    //S2101250100light-H5项目，跨域请求返回无法设置cookie，并且跨域请求无法携带cookie。能够支持跨域请求携带cookie
    xhr.withCredentials = settings.withCredentials;
    xhr.open(settings.type, settings.url, async)

    for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name])

    if (ajaxBeforeSend(xhr, settings) === false) {
        xhr.abort()
        return false
    }

    if (settings.timeout > 0) abortTimeout = setTimeout(function () {
        xhr.onreadystatechange = empty
        xhr.abort()
        ajaxError(null, 'timeout', xhr, settings)
    }, settings.timeout)

    // avoid sending empty string (#319)
    xhr.send(settings.data ? settings.data : null)
    return xhr
}


// trigger a custom event and return false if it was cancelled
function triggerAndReturn(context, eventName, data) {
    //todo: Fire off some events
    //let event = $.Event(eventName)
    //$(context).trigger(event, data)
    return true;//!event.defaultPrevented
}

// trigger an Ajax "global" event
function triggerGlobal(settings, context, eventName, data) {
    if (settings.global) return triggerAndReturn(context || document, eventName, data)
}

// Number of active Ajax requests
ajax.active = 0

function ajaxStart(settings) {
    if (settings.global && ajax.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
}

function ajaxStop(settings) {
    if (settings.global && !(--ajax.active)) triggerGlobal(settings, null, 'ajaxStop')
}

// triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
function ajaxBeforeSend(xhr, settings) {
    let context = settings.context
    if (settings.beforeSend.call(context, xhr, settings) === false ||
        triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
        return false

    triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
}

function ajaxSuccess(data, xhr, settings) {
    let context = settings.context, status = 'success'
    settings.success.call(context, data, status, xhr)
    triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
    ajaxComplete(status, xhr, settings)
}

// type: "timeout", "error", "abort", "parsererror"
function ajaxError(error, type, xhr, settings) {
    let context = settings.context
    settings.error.call(context, xhr, type, error)
    triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error])
    ajaxComplete(type, xhr, settings)
}

// status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
function ajaxComplete(status, xhr, settings) {
    let context = settings.context
    settings.complete.call(context, xhr, status)
    triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
    ajaxStop(settings)
}

// Empty function, used as default callback
function empty() {
}

ajax.JSONP = function (options) {
    if (!('type' in options)) return ajax(options)

    let callbackName = options.jsonpCallback || ('jsonp' + (++jsonpID)),
        script = document.createElement('script'),
        abort = function () {
            //todo: remove script
            //$(script).remove()
            if (callbackName in window) window[callbackName] = empty
            ajaxComplete('abort', xhr, options)
        },
        xhr = {abort: abort}, abortTimeout,
        head = document.getElementsByTagName("head")[0]
            || document.documentElement

    if (options.error) script.onerror = function () {
        xhr.abort()
        options.error()
    }

    window[callbackName] = function (data) {
        clearTimeout(abortTimeout)
        //todo: remove script
        //$(script).remove()
        delete window[callbackName]
        ajaxSuccess(data, xhr, options)
    }

    serializeData(options)
    script.src = options.url.replace(/=\?/, '=' + callbackName)

    // Use insertBefore instead of appendChild to circumvent an IE6 bug.
    // This arises when a base node is used (see jQuery bugs #2709 and #4378).
    head.insertBefore(script, head.firstChild);

    if (options.timeout > 0) abortTimeout = setTimeout(function () {
        xhr.abort()
        ajaxComplete('timeout', xhr, options)
    }, options.timeout)

    return xhr
}

ajax.settings = {
    // Default type of request
    type: 'GET',
    // Callback that is executed before request
    beforeSend: empty,
    // Callback that is executed if the request succeeds
    success: empty,
    // Callback that is executed the the server drops error
    error: empty,
    // Callback that is executed on request complete (both: error and success)
    complete: empty,
    // The context for the callbacks
    context: null,
    // Whether to trigger "global" Ajax events
    global: true,
    // Transport
    xhr: function () {
        return new XMLHttpRequest()
    },
    // MIME types mapping
    accepts: {
        script: 'text/javascript, application/javascript',
        json: jsonType,
        xml: 'application/xml, text/xml',
        html: htmlType,
        text: 'text/plain'
    },
    // Whether the request is to another domain
    crossDomain: false,
    // Default timeout
    timeout: 0
}

function mimeToDataType(mime) {
    return mime && (mime == htmlType ? 'html' :
        mime == jsonType ? 'json' :
            scriptTypeRE.test(mime) ? 'script' :
                xmlTypeRE.test(mime) && 'xml') || 'text'
}

function appendQuery(url, query) {
    return (url + '&' + query).replace(/[&?]{1,2}/, '?')
}

// serialize payload and append it to the URL for GET requests
function serializeData(options) {
    if (type(options.data) === 'object') options.data = param(options.data)
    if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
        options.url = appendQuery(options.url, options.data)
}

ajax.get = function (url, success) {
    return ajax({url: url, success: success})
}

ajax.post = function (url, data, success, dataType) {
    if (type(data) === 'function') dataType = dataType || success, success = data, data = null
    return ajax({type: 'POST', url: url, data: data, success: success, dataType: dataType})
}

ajax.getJSON = function (url, success) {
    return ajax({url: url, success: success, dataType: 'json'})
}

ajax.request = function (params) {
    return new Promise(function (resolve) {
        let success = params.success;
        params.success = function (data) {
            resolve(data);
        }
        ajax(params);
    })
}

let escape = encodeURIComponent

function serialize(params, obj, traditional, scope) {
    let array = type(obj) === 'array';
    for (let key in obj) {
        let value = obj[key];

        if (scope) key = traditional ? scope : scope + '[' + (array ? '' : key) + ']'
        // handle data in serializeArray() format
        if (!scope && array) params.add(value.name, value.value)
        // recurse into nested objects
        else if (traditional ? (type(value) === 'array') : (type(value) === 'object'))
            serialize(params, value, traditional, key)
        else params.add(key, value)
    }
}

function param(obj, traditional) {
    let params = []
    params.add = function (k, v) {
        this.push(escape(k) + '=' + escape(v))
    }
    serialize(params, obj, traditional)
    return params.join('&').replace('%20', '+')
}

function extend(target) {
    let slice = Array.prototype.slice;
    slice.call(arguments, 1).forEach(function (source) {
        for (key in source)
            if (source[key] !== undefined)
                target[key] = source[key]
    })
    return target
}
// 93817 light开发框架增加cache参数，对请求的数据进行本地化缓存
let cachedAJAX = function (params) {
    //142437 lighting框架light.ajax接口，当被请求的地址非https协议，开发阶段 console一个警告
    if (/^http:\/\//.test(params.url) && process.env.NODE_ENV === "dev") {
      console.warn(`Light.ajax：检测到请求地址${params.url}中使用了http协议，请使用https协议地址，以保障通信安全！`);
    }
    const cacheKEY = `${params.url}#${JSON.stringify(params.body)}#${JSON.stringify(params.headers)}#${params.type}`;
    let originSuccess = params.success;

    if(params.cache === true){
        //web环境
        const cachedData = localStorage.getItem(cacheKEY);
        if(cachedData){
            originSuccess(JSON.parse(cachedData))
        }else {
            params.success = function (data) {
                localStorage.setItem(cacheKEY,JSON.stringify(data))
                originSuccess(data);
            };
            ajax(params);
        }
    }else{
        //no cache
        // ajax兼容，当同步xhr时需要返回xhr给前端使用
        return ajax(params)
    }
};

// 93817 light开发框架增加cache参数，对请求的数据进行本地化缓存
['get','post','getJSON','request'].forEach(function (key) {
    cachedAJAX[key] = ajax[key];
});

export default cachedAJAX;