(function($) {
    var _ajax = $.ajax;
    //重写jquery的ajax方法
    var activeRequests = 0;
    $.ajax = function(opt) {
        //备份opt中error和success方法
        var fn = {
            beforeSend: function(xhr) {},
            error: function(XMLHttpRequest, textStatus, errorThrown) {},
            success: function(data, textStatus) {},
            complete: function(XMLHttpRequest, textStatus) {}
        };
        if (sessionStorage.getItem("xystyle") == "p6s") {
            if (opt.dataType == "json" || opt.dataType == "text" || opt.dataType == "html" || opt.dataType == "script") {
                if(opt.url.indexOf("/client/notify")===-1){
                    opt.url = config.p6sURL + "/" + opt.url;
                }
                // opt.data = opt.data;
                opt.cache = false;
            } else {
                // opt.url = opt.url;
                // opt.data = opt.data;
                opt.cache = false;
            }
        } else if (sessionStorage.getItem("xystyle") == "p2p") {

            if (opt.dataType == "json" || opt.dataType == "text" || opt.dataType == "html" || opt.dataType == "script") {
                // opt.url = opt.url;
                // opt.data = opt.data;
                // opt.success = opt.success;
                opt.cache = false;
            } else {
                opt.cache = false;
                if (opt.dataType == "XML") {
                    opt.dataType = "JSON";
                }

                // 找到冒号的位置
                var colonIndex = opt.url.lastIndexOf(":");
                // 截取端口号
                var portIndex = opt.url.substring(colonIndex + 1);
                var url = portIndex.substring(portIndex.indexOf("/"))
                //1.截取端口号前的url
                //var url = opt.url.substring(22, opt.url.length);

                //2.根据请求类型拼接
                if (opt.type.toLowerCase() == "get") {
                    opt.url = config.baseUrl + "/mixinGet?url=" + url + "&id=" + config.p2pId;
                } else if (opt.type.toLowerCase() == "post") {
                    opt.url = config.baseUrl + "/mixinPost?url=" + url + "&id=" + config.p2pId;
                } else if (opt.type.toLowerCase() == "put") {
                    opt.url = config.baseUrl + "/mixinPut?url=" + url + "&id=" + config.p2pId;
                } else if (opt.type.toLowerCase() == "delete") {
                    opt.url = config.baseUrl + "/mixinDelete?url=" + url + "&id=" + config.p2pId;
                }
            }
        } else {
            if (opt.dataType == "json" || opt.dataType == "text" || opt.dataType == "html" || opt.dataType == "script") {
                opt.url = config.baseUrl + "/" + opt.url;
                // opt.data = opt.data;
                opt.cache = false;
            } else {
                // opt.url = opt.url;
                // opt.data = opt.data;
                opt.cache = true;
            }
        }

        if (opt.beforeSend) {
            fn.beforeSend = opt.beforeSend;
        }

        if (opt.error) {
            fn.error = opt.error;
        }

        if (opt.success) {
            fn.success = opt.success;
        }

        if (opt.complete) {
            fn.complete = opt.complete;
        }

        //扩展增强处理
        var _opt = $.extend(opt, {
            // timeout: config.cgiTimeout,
            beforeSend: function(xhr) {
                if (opt.dataType == "json" || opt.dataType == "text" || opt.dataType == "html" || opt.dataType == "script") {
                    if(opt.url.indexOf("/client/notify")!==-1){
                        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    }else{
                     return;
                    }
                } else {
                    if ((sessionStorage.getItem("xystyle") == "p2p" || sessionStorage.getItem("xystyle") == "p6s")) {
                        if (opt && opt.type&&!opt.isloading) {                        // 增加请求计数器
                            activeRequests++;
                            // 只有当第一次请求时才显示遮罩层
                            if (activeRequests == 1) {
                                if(opt.type.toLowerCase() != "get"&&!opt.unmask){
                                    $.MaskUtil.mask($.i18n.prop("i18n-save-loading"));
                                }else{
                                    $.MaskUtil.mask("");
                                }
                            }
                        }
                    }
                    if (sessionStorage.getItem("xystyle") == "p2p" && opt.type.toLowerCase() != "get") {
                        if(opt.url.indexOf("/System/DeviceCustomFunction")!==-1){
                            xhr.setRequestHeader("content-type", "text/plain");
                        }else{
                            xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
                        }
                    }
                    fn.beforeSend(xhr);
                }
            },
            success: function(data, textStatus) {
                if (sessionStorage.getItem("xystyle") == "p2p") {
                    if (opt.dataType == "json" || opt.dataType == "text" || opt.dataType == "html" || opt.dataType == "script") {
                        // console.log("本地资源不做处理直接返回");
                        fn.success(data, textStatus);
                    } else {
                        if (data[0].error == 0) {
                            // console.log("p2p资源解析base64之后再做返回");
                            var devicemessage;
                            if(opt.url.indexOf("/System/DeviceConfigFile?FileType=9")!==-1){
                                devicemessage = Base64.decode(data[0].attach.response);
                            } else {
                                if (config.isDownLoad) {
                                    devicemessage = data[0].attach.response;
                                } else {
                                    devicemessage = xmlStr2XmlObj(Base64.decode(data[0].attach.response));
                                }
                            }
                            var xhr = {};
                            xhr.responseXML = devicemessage;
                            if (opt.type.toLowerCase() == "put") {
                                fn.success(xhr, textStatus);
                            } else {
                                fn.success(devicemessage, textStatus);
                            }

                        } else {
                            if (config.isDownLoad) {
                                $.optionBootoast($.i18n.prop('i18n-download-failed'), "danger");
                                $.MaskUtil.unmask();
                                config.isDownLoad = false;
                            }
                            if(data[0].error == 3001){
                                $.optionBootoast($.i18n.prop('i18n-userpasswordincorrect'), "danger")
                            }
                            if(data[0].error == 401){
                                $.optionBootoast($.i18n.prop('i18n-userpasswordincorrect'), "danger")
                            }
                        }
                    }

                } else {
                    // console.log("p6s不做处理直接返回");
                    fn.success(data, textStatus);
                }

            },
            // 统一的完成处理
            complete: function(XMLHttpRequest, textStatus) {
                // $.MaskUtil.unmask();
                // 如果是超时完成
                // if (textStatus === 'timeout') {
                //     bootoast({
                //         message: $.i18n.prop('i18n-savefail'),
                //         type: 'danger',
                //         position: 'bottom-center',
                //         icon: undefined,
                //         timeout: true,
                //         animationDuration: 3000,
                //         dismissable: true
                //     })
                // }

                // 减少请求计数器，只有当所有请求都完成时才移除遮罩层
                if ((sessionStorage.getItem("xystyle") == "p2p" || sessionStorage.getItem("xystyle") == "p6s")) {
                    if(opt && opt.type&&!opt.isloading) {
                        activeRequests--;
                        // 确保计数器不会小于0
                        if (activeRequests < 0) activeRequests = 0;
                        // 只有当所有请求都完成时才移除遮罩层
                        if (activeRequests === 0) {
                            $.MaskUtil.unmask();
                        }
                    }
                }

                // 调用用户自定义的complete处理
                fn.complete(XMLHttpRequest, textStatus);
            }
        });
        // _ajax(_opt);
        var def = _ajax.call($, _opt);

        return def;
    };
})(jQuery);
