import Message from "../message";
import {Alert} from "../modal";
import Modal from "../modal";
import MathUtil from "../../util/MathUtil";
import StringUtil from "../../util/StringUtil";
import baseTool from "../../util/baseTool";
import Loading from '../loading';
import {getUID, sendLog, needSendLog} from '../../util/sendLog';
const sendHttp = (($)=>{
    const DefaultConfig = {
        method: "post",
        dataType: "json",
        noVenderId: true,
        contentType:"application/x-www-form-urlencoded; charset=UTF-8", 
        timeout: 60000,
        xhrFields:{
            withCredentials:true
        },
        headers:{},
        checkLoginUrl:"//zxdesigner-sdk.jd.com/isLogin.html",   
        basePath:"",
        isErrorCallback:true,
        clearErrorTip:false,
        showLoading:false,
        jsonp:null,             
        jsonpCallback:null,     
        timeLog:true,       
        slowTime:300,       
        errorHandler:(data, clearErrorTip)=>{
            if(data){
                if(data.hasOwnProperty("code")){
                    let errorMsg = data.msg || data.message;
                    let msgLevel = data.msgLevel || 0;
                    if(errorMsg){
                        console.log(errorMsg);
                    }
                    if(data.code >= 400 && data.code < 500){
                        errorMsg = "当前网络异常，请刷新页面";
                        msgLevel = 1;
                    }
                    if(data.code == 401 || data.code == 402){
                    }
                    else if(errorMsg){
                        if(msgLevel == 0 || msgLevel == 1){
                            Message.error(errorMsg, clearErrorTip);
                        }
                        else if(msgLevel == 2){
                            new Alert({
                                title:"错误提示",
                                label:"知道了",
                                iconClass:"cd-error",
                                content:errorMsg
                            });
                        }
                    }
                }
            }
        }
    }
    function getTimer(){
        return (new Date()).getTime();
    }
    
    function checkLogin(url, callback){
        let param = {
            dataType: "jsonp",
            timeout: 5000,
            xhrFields:{
                withCredentials:true
            },
            url: url,
            success:(data, textStatus, jqXHR)=>{
                if(data && data.code == 200){
                    if(callback){
                        callback(1);
                    }
                }
                else{
                    if(callback){
                        callback(0);
                    }
                }
            },
            error:(jqXHR, textStatus, errorThrown)=>{
                if(callback){
                    callback(-1);
                }
            }
        };
        return $.ajax(param);
    }
    
    function processParam(logFlag, param, _uid) {
        let venderId = '';
        if(window.page_data && window.page_data.hasOwnProperty('venderId')){
            venderId = window.page_data.venderId;
        }
        if(!venderId){
            venderId = StringUtil.getQueryString('venderId');
        }
        if(venderId || logFlag){
            if(param.data == null){
                param.data = {};
            }
            if(StringUtil.isString(param.data)){
                let temp = null;
                try{
                    temp = JSON.parse(param.data);
                }
                catch (e) {
                    console.log(e);
                }
                if(temp){
                    if(venderId){
                        temp['_vender_id'] = venderId;
                    }
                    if(logFlag){
                        temp['_uid_'] = _uid;
                    }
                    param.data = JSON.stringify(temp);
                }
            }
            else{
                if(venderId){
                    param.data['_vender_id'] = venderId;
                }
                if(logFlag){
                    param.data['_uid_'] = _uid;
                }
            }
        }
    }
    
    function errorAlert(data) {
        if(data && window._nologinAlert == null){
            let msg = data.msg || data.message || '系统检测到您暂未登录或不具备该操作权限，请重新登陆。';
            window._nologinAlert = new Alert({
                zIndex:baseTool.getTopIndex(),
                title:"登录提示",
                label:"确 定",
                iconClass:"cd-warning",
                content:msg,
                onClose:(flag)=>{
                    window._nologinAlert = null;
                    if(flag == Modal.CloseType.TYPE_OK){
                        let url = `//passport.jd.com/new/login.aspx?ReturnUrl=` + encodeURIComponent(window.location.href);
                        window.location.href = url;
                    }
                }
            });
        }
    }
    
    function preErrorHandler(status, data, config, jqXHR) {
        if(data && config){
            if(data.hasOwnProperty("code") && (data.code == 401 || data.code == 402)){
                errorAlert(data);
            }
            else if(config.errorHandler){
                if(status == 'success'){
                    config.errorHandler(data, config.clearErrorTip);
                }
                else{
                    if ((jqXHR.getResponseHeader('TEMPLATE_OUTDATE') == 'false') || jqXHR.getResponseHeader('needUpdate') == 1) {
                    }
                    else{
                        config.errorHandler(data, config.clearErrorTip);
                    }
                }
            }
        }
    }
    
    function sendHttp(options, callback) {
        if (!options) {
            throw Error('sendHttp options is null');
        }
        let config = $.extend(true, {}, DefaultConfig, options);
        let url = config.url || "";
        if(config.timeLog){
            config.__startTime = getTimer();
        }
        let _url = config.basePath + url;
        let _uid = getUID();
        let logFlag = needSendLog(_url);
        let param = {
            method: config.method || DefaultConfig.method,
            dataType: config.dataType || DefaultConfig.dataType,
            contentType: config.contentType || DefaultConfig.contentType,
            headers: config.headers,
            timeout:config.timeout,
            url: _url,
            data: config.data,
            xhrFields:config.xhrFields
        };
        if(config.jsonp){
            param.jsonp = config.jsonp;
        }
        if(config.jsonpCallback){
            param.jsonpCallback = config.jsonpCallback;
        }
        if (!config.noVenderId) {
            processParam(logFlag, param, _uid);
        }
        param.success = (data, textStatus, jqXHR)=>{
            if(config.loading){
                config.loading.dispose();
                config.loading = null;
            }
            if(config.timeLog){
                let endTime = getTimer();
                let costTime = endTime - config.__startTime;
                if(costTime >= config.slowTime){
                    console.warn("sendHttp success costTime:" + costTime + "ms,_url:" + _url + ",param:"+JSON.stringify(config.data));
                }
            }
            if(data){
                if(data.hasOwnProperty("code")){
                    const { code } = data;
                    const responseSuccessFlag = code >= 200 && code < 300 || code == 0;
                    if(!data.hasOwnProperty("success")){
                        data.success = responseSuccessFlag;
                    }
                    if(!data.hasOwnProperty("result")){
                        data.result = responseSuccessFlag;
                    }
                }
                if(data.hasOwnProperty('success') && data.success == false || data.hasOwnProperty('succ') && data.succ ==false || data.hasOwnProperty('result') && data.result == false){
                    if(logFlag){
                        sendLog(_uid, 'SUCCESS', {url:_url, data:data});
                    }
                    preErrorHandler('success', data, config, jqXHR);
                }
                if(callback){
                    callback({success:true, originUrl:_url, msg:textStatus, data:data});
                }
            }
        };
        param.error = (jqXHR, textStatus, errorThrown)=>{
            if(config.loading){
                config.loading.dispose();
                config.loading = null;
            }
            if(logFlag){
                sendLog(_uid, 'ERROR', {url: _url, jqXHR:jqXHR, textStatus:textStatus, errorThrown:errorThrown});
            }
            if(config.timeLog){
                let endTime = getTimer();
                let costTime = endTime - config.__startTime;
                console.warn("sendHttp error! costTime:" + costTime + "ms,_url:" + _url + ",param:"+JSON.stringify(options.data));
            }
            let data = {code:-100, success:false, msgLevel:1, result:false, msg:"当前网络异常，请刷新页面"};
            preErrorHandler('error', data, config, jqXHR);
            if(config.isErrorCallback){
                if(callback){
                    callback({success:false, originUrl:_url, msg:textStatus, data:data});
                }
            }
            if((jqXHR.status==0 && textStatus == "error" && errorThrown == "") ||
                (jqXHR.status==200 && textStatus == "parsererror")
            ){
                if(window._nologinAlert ==null){
                    checkLogin(config.checkLoginUrl, (flag)=>{
                        if(flag ==0){
                            data.code = 401;
                            data.msg = '系统检测到您暂未登录，请先登录再进行此操作。';
                            errorAlert(data);
                        }
                    });
                }
            }
        };
        if(config.showLoading){
            config.loading = new Loading({
                zIndex:baseTool.getLoadingIndex(),
                text:config.loadingText,
            });
            config.loading.show();
        }
        return $.ajax(param);
    }
    return sendHttp;
})($);
export default sendHttp;