(function(){
	angular.module("app")
	.factory("HttpService",["$http","$q","UtilService",httpService]);

	function httpService($http,$q,UtilService){
		var service = {};
		service.loginTimeout = function(data) {
        if(data!=null && data.code && data.code == -1002){
        	service.logOutCookie();
        }
    };
    service.noLogin = function(url){
    	if(angular.isUndefined(url) || url.indexOf('login')==-1){
    		var loginuserId = UtilService.getUser().id;
    		if(UtilService.isNullStr(loginuserId)){
    			service.logOutCookie();
    		}
    	}
    };
    service.logOutCookie = function(){
    	UtilService.setUser({});
      window.localStorage.setItem("ryioUauth","");
    	UtilService.setCookie("ryioToken","");
    	UtilService.setCookie("ryioIsSuper","");
    	window.location.href="/login.html";
    };
		service.getInfo = function(url,params,noLogin){
			if(!noLogin){
				service.noLogin(url);
			}

			var defered = $q.defer();

			var condition = "";
            for(var k in params){
                condition += "&" + k +"=" + params[k];
            }
            if(url.indexOf("?")==-1){
            	url += "?r=" + Math.random();
            }else{
            	url += "&r=" + Math.random();
            }
            url += condition;

			var hp = $http.get("/api/"+url)
			.success(function(data){
				service.loginTimeout(data);
				if(data.code && data.code!=200){
					defered.reject(data);
				}
				else{
					defered.resolve(data.content || data);
				}
			})
			.error(function(data){
				service.loginTimeout(data);
				defered.reject(data);
			});
			return defered.promise;
		}

		service.getInfoByUrl = function(url){
			service.noLogin();

			var defered = $q.defer();
			var hp = $http.get(url)
			.success(function(data){
				service.loginTimeout(data);
				defered.resolve(data.content || data);
			})
			.error(function(data){
				service.loginTimeout(data);
				defered.reject(data);
			});
			return defered.promise;
		}

		service.getReportData = function(report,param){
			service.noLogin();
			var defered = $q.defer();

			var params = UtilService.cloneJSON(param);
			var appid = params.appid;
			delete params.appid;

			var condition = "?r=" + Math.random();
            for(var k in params){
                condition += "&" + k +"=" + params[k];
            }
			var hp = $http.get("/api/report/"+appid+"/"+report+condition)
			.success(function(data){
				service.loginTimeout(data);
				if(data.code && data.code!=200){
					defered.reject(data);
				}
				else{
					defered.resolve(data.content || data);
				}
			})
			.error(function(data){
				service.loginTimeout(data);
				defered.reject(data);
			});
			return defered.promise;
		}

		service.postInfo = function(url,params,noLogin){
			if(!noLogin){
				service.noLogin(url);
			}
			var defered = $q.defer();
			if(url.indexOf("?")==-1){
            	url += "?r=" + Math.random();
            }else{
            	url += "&r=" + Math.random();
            }
			var hp = $http.post("/api/"+url,params)
			.success(function(data,status){
				service.loginTimeout(data);
				data.status = status;
				if(data.code && data.code==-5000){
					defered.resolve(data);
				}
				else if(data.code && data.code==-6001){
					defered.resolve(data);
				}
				else{
					defered.resolve(data.content || data);
				}

			})
			.error(function(data){
				service.loginTimeout(data);
				defered.reject(data);
			});
			return defered.promise;
		}

		service.postInfoByUrl = function(url,params){
			service.noLogin();

			var defered = $q.defer();
			if(url.indexOf("?")==-1){
      	url += "?r=" + Math.random();
      }
			else{
      	url += "&r=" + Math.random();
      }
			var hp = $http.post(url,params)
			.success(function(data){
				defered.resolve(data.content || data);
			})
			.error(function(data){
				service.loginTimeout(data);
				defered.reject(data);
			});
			return defered.promise;
		}

		service.putInfo = function(url,params){
			service.noLogin(url);
			var defered = $q.defer();
			if(url.indexOf("?")==-1){
            	url += "?r=" + Math.random();
            }else{
            	url += "&r=" + Math.random();
            }

			var hp = $http.put("/api/"+url,params)
			.success(function(data,status){
				service.loginTimeout(data);
				data.status = status;
				if(data.code && data.code < 0){
					defered.reject(data);
				}else{
					defered.resolve(data.content || data);
				}
			})
			.error(function(data){
				service.loginTimeout(data);
				defered.reject(data);
			});
			return defered.promise;
		}

		service.deleteInfo = function(url){
			service.noLogin();
			var defered = $q.defer();
			if(url.indexOf("?")==-1){
            	url += "?r=" + Math.random();
            }else{
            	url += "&r=" + Math.random();
            }

			var hp = $http.delete("/api/"+url)
			.success(function(data,status){
				service.loginTimeout(data);
				data.status = status;
				defered.resolve(data.content || data);
			})
			.error(function(data){
				service.loginTimeout(data);
				defered.reject(data);
			});
			return defered.promise;
		}

		//文件下载
		service.downFile = function(url,params){
			var defered = $q.defer();
			if(url.indexOf("api")==-1){
				url = "/api/" + url;
			}
			$http({
                method: 'GET',
                url: url,
                params: params,
                responseType: 'arraybuffer'
            }).success(function (data, status, headers) {
            	if(status == 204){//没有文件
            		defered.resolve({code:-1});
            		return false;
            	}
            	else{
            		defered.resolve({code:1});
            	}
                headers = headers();

                var filename = headers['filename'];
                var contentType = headers['content-type'];
                var linkElement = document.createElement('a');
                try {
                    var blob = new Blob([data], { type: contentType });
                    var url = window.URL.createObjectURL(blob);

                    linkElement.setAttribute('href', url);
                    linkElement.setAttribute("download", decodeURIComponent(filename));

                    var clickEvent = new MouseEvent("click", {
                        "view": window,
                        "bubbles": true,
                        "cancelable": false
                    });
                    linkElement.dispatchEvent(clickEvent);
                } catch (ex) {
                    // console.log(ex);
                }
            }).error(function (data) {

            });
            return defered.promise;
		}
		return service;
	}
})();
