(function($) {
    var publish_version = false;
    var agentName = "wlyyAgentForDoc";
    var server, userAgent, loginUrl, imserver, socketUrl, imgServer;

    var IMEI = localStorage.getItem('WLYY_IMEI') || uuid(16, 16)
    localStorage.setItem('WLYY_IMEI', IMEI)
    $.support.cors = true;
    if(publish_version) { // 生产环境配置
        server = "http://172.19.103.88:9092/wlyy/"
        imserver = "http://172.19.103.88:3000/api/v2";
        socketUrl = "http://172.19.103.88:3000";
        loginUrl = "login.html";
        imgServer = "";
    } else { // 测试环境配置
        server = "http://172.19.103.88:9092/wlyy/"
        // server = "http://192.168.131.127:8060/"; //逸祥
        // server = "http://192.168.131.24:8080/"; //仕杰
        imserver = "http://172.19.103.88:3000/api/v2";
        socketUrl = "http://172.19.103.88:3000";
        loginUrl = "login.html";
        imgServer = "http://172.19.103.54/";
    }

    userAgent = localStorage.getItem(agentName)

    //hard code userAgent for test start
    //全科
    // userAgent = {"id":4800,"uid":"zbqD201703150222","imei":"864394010176834","token":"9b23e4ec0bcd3b9fa72a52f91544a4e9","platform":4,"hospital":"3502050100"}
    //健管
    // userAgent = {"id":4821,"uid":"zbqD201703150228","imei":"864394010176834","token":"73f5ace5c7d4cdb811f743902fd705d9","platform":4,"hospital":"3502050100"}; 
    // userAgent = JSON.stringify(userAgent);
    //hard code userAgent for test end

    if(userAgent) {
        try {
            userAgent = JSON.parse(userAgent)
        } catch(e) {
            toastr && toastr.warning("登录失效，请重新登录")
            toLoginPage()
        }
    } else {
        toLoginPage()
    }
	
	var isRelogined = sessionStorage.getItem('wlyy_relogin')
	if(isRelogined && top !== window && location.href.indexOf("login.html") < 0) {
		sessionStorage.removeItem('wlyy_relogin')
		top.location.reload(true)
	}

    function httpGet(url, options) {
        //发送ajax请求
        return new Promise(function(resolve, reject) {
            $.ajax(server + url,
                $.extend({}, {
                    type: 'GET',
                    dataType: 'JSON',
                    beforeSend: function(request) {
                        var agent = userAgent || {
                            imei: localStorage.getItem('WLYY_IMEI'),
                            platform: 4
                        }
                        request.setRequestHeader("userAgent", JSON.stringify(agent));
                    },
                    error: function(res) {
                        reject(res)
                    },
                    success: function(res) {
                        failCodeHandle(res)
                        resolve(res)
                    }
                }, options));
        })
    }

    function httpPost(url, options) {
        //发送ajax请求
        return new Promise(function(resolve, reject) {
            $.ajax(server + url,
                $.extend({}, {
                    type: 'POST',
                    dataType: 'JSON',
                    beforeSend: function(request) {
                        var agent = userAgent || {
                            imei: localStorage.getItem('WLYY_IMEI')
                        }
                        request.setRequestHeader("userAgent", JSON.stringify(agent));
                    },
                    error: function(res) {
                        reject(res)
                    },
                    success: function(res) {
                        failCodeHandle(res)
                        resolve(res)
                    }
                }, options));
        })
    }

    function imHttpGet(url, options) {
        //发送ajax请求
        return new Promise(function(resolve, reject) {
            $.ajax(imserver + url,
                $.extend({}, {
                    type: 'GET',
                    dataType: 'JSON',
                    beforeSend: function(request) {
                        request.setRequestHeader("userAgent", JSON.stringify(userAgent));
                    },
                    error: function(res) {
                        reject(res)
                    },
                    success: function(res) {
                        failCodeHandle(res)
                        resolve(res)
                    }
                }, options));
        })
    }

    function imHttpPost(url, options) {
        //发送ajax请求
        return new Promise(function(resolve, reject) {
            $.ajax(imserver + url,
                $.extend({}, {
                    type: 'POST',
                    dataType: 'JSON',
                    beforeSend: function(request) {
                        request.setRequestHeader("userAgent", JSON.stringify(userAgent));
                    },
                    error: function(res) {
                        reject(res)
                    },
                    success: function(res) {
                        failCodeHandle(res)
                        resolve(res)
                    }
                }, options));
        })
    }

    function toLoginPage() {
        if(location.href.indexOf('login.html') > -1) {
            return;
        }
        setTimeout(function() {
        	sessionStorage.setItem("wlyy_relogin",1)
            top.location.replace(loginUrl + '?redirect_url=' + encodeURIComponent(location.href))
        }, 2000)
    }

    function failCodeHandle(res) {
        var tip = "";
        if(res.status == 999) {
            tip = "此账号已在别处登录，请重新登录";
        } else if(res.status == 998) {
            tip = "登录超时，请重新登录";
        } else if(res.status == 997) {
            tip = "此账号未登录，请先登录"
        }
        if(tip) {
            toastr && toastr.warning(tip)
            toLoginPage()
        }
    }

    function uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;

        if(len) {
            // Compact form  
            for(i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            // rfc4122, version 4 form  
            var r;

            // rfc4122 requires these characters  
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as  
            // per rfc4122, sec. 4.1.5  
            for(i = 0; i < 36; i++) {
                if(!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    }

    APIService = {
        agentName: agentName,
        server: server,
        imserver: imserver,
        socketUrl: socketUrl,
        userAgent: userAgent,
        httpGet: httpGet,
        httpPost: httpPost,
        imHttpGet: imHttpGet,
        imHttpPost: imHttpPost,
        getDoctorInfo: function() {
            return httpGet('doctor/baseinfo');
        },
        getTeamInfo: function(doctor) {
            return httpGet('/doctor/admin-teams/team/' + doctor + '/teams');
        }
    }

    window.APIService = APIService;
})(jQuery)