package com.offcn.TestUnti;

import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.ContentType;
import io.restassured.http.Cookies;
import io.restassured.http.Headers;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.offcn.process.BasicsGM;
import com.offcn.process.XYZB;
import com.offcn.system.system;

import static io.restassured.http.ContentType.JSON;


public class RequestDataUtils {
	
	public static void main(String[] args) {
		String s="/user/validator/code?phone=13910960649&sendImageCode=CJ6J";
		
	}
	//发送请求前的准备
	private RestAssured getRMEnv(system tem) {
		RestAssured	ra = new RestAssured();
			ra.config = RestAssuredConfig.newConfig().sslConfig(
					SSLConfig.sslConfig().allowAllHostnames());
//			System.out.println(""+tem.getRM_URI()+"");
			ra.baseURI = tem.getRM_URI();
			
//			System.out.println(tem.getRM_port());
			if (tem.getRM_port()!=null && tem.getRM_port().length()>1){
				ra.port = Integer.valueOf(tem.getRM_port());
			}
			
//			System.out.println(tem.getRM_basePath());
			if (tem.getRM_basePath()!=null && tem.getRM_basePath().length()>1){
				ra.basePath = tem.getRM_basePath();
			}
//			RestAssured.config = RestAssured.config().encoderConfig(EncoderConfig.encoderConfig().encodeContentTypeAs("x-www-form-urlencoded", ContentType.ANY).defaultContentCharset("utf-8"));
		return ra;
	}
	
	//不带token的post请求
		public static Response Post_headers(HashMap<String, Object> data, String serviceURL,String zgl_clienttype) {
				// 设置参数格式
			String Parameter = (String) data.get("parameter");

			String system = MapUtil.getValue("system", data);
			com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));

			Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);

			int state = 0;
			Response re = null;
			RequestDataUtils rdu = new RequestDataUtils();
			while (state < 5) {
				try {
					state++;
					re = rdu.getRMEnv(tem).given()
							.header("zgl-systemtype", "Windows")
							.header("zgl-clienttype", zgl_clienttype)
							.contentType(JSON).body("{"+Parameter+"}").when()
							.post(serviceURL).thenReturn();
//						System.out.println(re.getStatusCode()+"............................");
//						System.out.println(re.asString());
					JsonPath jp = re.body().jsonPath();
					if ("500".equals(jp.getString("status"))) {
						Log.logError("请求返回500," + state + "次。");
						Thread.sleep(1000);
					} else {
						return re;
					}
				} catch (Exception e) {
					e.printStackTrace();
					Log.logError("请求超时," + state + "次。");
				}
			}
			return re;
		}
	
	//不带token的post请求
	public static Response Post_NOToken(HashMap<String, Object> data, String serviceURL) {
			// 设置参数格式
		String Parameter = (String) data.get("parameter");

		String system = MapUtil.getValue("system", data);
		com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));

		Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);

		int state = 0;
		Response re = null;
		RequestDataUtils rdu = new RequestDataUtils();
		while (state < 5) {
			try {
				state++;
				if("/web/member".equals(serviceURL)){
//					Cookie cookie1 = Cookie.Builder("username", "John").setComment("comment 1").build();
//					Cookie cookie2 = Cookie.Builder("token", 1234).setComment("comment 2").build();
//					Cookies cookies = new Cookies(cookie1, cookie2);
					System.out.println(XYZB.laravel_session);
					System.out.println(XYZB.XSRF_token);
					re = rdu.getRMEnv(tem).given()
//							.header("laravel_session", XYZB.laravel_session)
//							.header("XSRF-TOKEN", XYZB.XSRF_token)
							.cookie("laravel_session", XYZB.laravel_session)
							.cookie("XSRF-TOKEN", XYZB.XSRF_token)
							.contentType(JSON).body("{"+Parameter+"}").when()
							.post(serviceURL).thenReturn();
//					System.out.println(re.getStatusCode()+"............................");
//					System.out.println(re.asString());
//					Headers headers=re.getHeaders();
//					System.out.println(headers.toString());
//							System.out.println(re.getSessionId());
							
//					JsonPath jp = re.body().jsonPath();
					if (!"200".equals(re.getStatusCode()+"")) {
						Log.logError("请求返回:" +re.getStatusCode()+",第"+ state + "次。");
						Thread.sleep(1000);
					} else {
						return re;
					}
				}else{
					re = rdu.getRMEnv(tem).given()
//							.header("laravel_session", XYZB.laravel_session)
							.cookie("laravel_session", XYZB.laravel_session)
							.contentType(JSON).body("{"+Parameter+"}").when()
							.post(serviceURL).thenReturn();
//					System.out.println(re.getStatusCode()+"............................");
//					System.out.println(re.asString());
					JsonPath jp = re.body().jsonPath();
					if ("500".equals(jp.getString("status"))) {
						Log.logError("请求返回500," + state + "次。");
						Thread.sleep(1000);
					} else {
						return re;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.logError("请求超时," + state + "次。");
			}
		}
		return re;
	}
	
	//不带token的post请求
		@SuppressWarnings("static-access")
		public static Response Post_NOtokenNOcookie(HashMap<String, Object> data, String serviceURL) {
				// 设置参数格式
			String Parameter = (String) data.get("parameter");

			String system = MapUtil.getValue("system", data);
			com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));

			Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);

			int state = 0;
			Response re = null;
			RequestDataUtils rdu = new RequestDataUtils();
			while (state < 5) {
				try {
					state++;
					re = rdu.getRMEnv(tem).given()
							.contentType(JSON).body("{"+Parameter+"}").when()
							.post(serviceURL).thenReturn();
					if (!"200".equals(re.getStatusCode()+"")) {
						Log.logError("请求返回," + re.getStatusCode() + "次。");
						Thread.sleep(1000);
					} else {
						return re;
					}
				
				} catch (Exception e) {
					e.printStackTrace();
					Log.logError("请求超时," + state + "次。");
				}
			}
			return re;
		}
	
	//需要添加token的post，json请求
	@SuppressWarnings("static-access")
	public static Response Post_token(HashMap<String, Object> data, String serviceURL, String token) {
		// 设置参数格式
		String Parameter = (String) data.get("parameter");

		String system = MapUtil.getValue("system", data);
		com.offcn.system.system tem = (com.offcn.system.system) (BasicsGM.map.get(system));

		Log.logInfo(data.get("Description").toString() + "," + data.get("TCNO").toString() + ",Parameter=" + Parameter);

		int state = 0;
		Response re = null;
		RequestDataUtils rdu = new RequestDataUtils();
		while (state < 5) {
			try {
				state++;
//				re = rdu.getRMEnv(tem).given().cookie("laravel_session", XYZB.laravel_session).when().get("http://live.offcncloud.com/web/admin").thenReturn();
				re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+ token)
						.contentType(JSON).body("{"+Parameter+"}").when()
						.post(serviceURL).thenReturn();
//				System.out.println(MapUtil.showMap_String(re.getCookies()));
				if (!"200".equals(re.getStatusCode()+"")) {
					Log.logError("请求返回:" +re.getStatusCode()+",第"+ state + "次。");
					Thread.sleep(1000);
				} else {
					return re;
				}
			} catch (Exception e) {
				Log.logError("请求超时," + state + "次。");
			}
		}
		return re;
	}
	
	//发送get请求返回整个响应结果
    @SuppressWarnings("static-access")
    public static Response Get_Noparameter(HashMap<String, Object> data,
                                          String serviceURL,String token) {
        //设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);

        int state=0;
        Response re=null;
        RequestDataUtils rdu=new RequestDataUtils();
        while(state<3){
            try {
                state++;
                 
                if(parameter != null && !"".equals(parameter)) {
					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+ token).get(serviceURL + "/" + parameter).andReturn();
				}else{
					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+ token).get(serviceURL).andReturn();
				}
                if(!"200".equals(re.statusCode()+"")){
                    Log.logError("请求返回"+re.statusCode()+"次。");
                }else{
                    return re;
                }
            } catch (Exception e) {
                Log.logError("请求超时,"+state+"次。");
            }
        }
        return re;
    }
	
	
	//发送get请求返回整个响应结果
    @SuppressWarnings("static-access")
    public static Response Get_token(HashMap<String, Object> data,
                                          String serviceURL,String token) {
        //设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);

        int state=0;
        Response re=null;
        RequestDataUtils rdu=new RequestDataUtils();
        while(state<3){
            try {
                state++;
                 
                if(parameter != null && !"".equals(parameter)) {
					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+ token).get(serviceURL + "?" + parameter).andReturn();
				}else {
					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+ token).get(serviceURL).andReturn();
				}
                if(!"200".equals(re.statusCode()+"")){
                    Log.logError("请求返回"+re.statusCode()+"次。");
                }else{
                    return re;
                }
            } catch (Exception e) {
                Log.logError("请求超时,"+state+"次。");
            }
        }
        return re;
    }
	
  //get错误token请求
    @SuppressWarnings("static-access")
    public static Response Get_Errtoken(HashMap<String, Object> data,
                                          String serviceURL,String token) {
        //设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);

        int state=0;
        Response re=null;
        RequestDataUtils rdu=new RequestDataUtils();
        while(state<5){
            try {
                state++;
                 
                if(parameter != null && !"".equals(parameter)) {
					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+  token+"1").get(serviceURL + "/" + parameter).andReturn();
				}else {
					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+  token+"1").get(serviceURL).andReturn();
				}
                if("500".equals(re.statusCode()+"")){
                    Log.logError("请求返回500,"+state+"次。");
                }else{
                    return re;
                }
            } catch (Exception e) {
                Log.logError("请求超时,"+state+"次。");
            }
        }
        return re;
    }
  	
  //get超长token请求
    @SuppressWarnings("static-access")
    public static Response Get_Longtoken(HashMap<String, Object> data,
                                          String serviceURL,String token) {
        //设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);

        int state=0;
        Response re=null;
        RequestDataUtils rdu=new RequestDataUtils();
        while(state<5){
            try {
                state++;
                 
                if(parameter != null && !"".equals(parameter)) {
					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+  token+token+token+token+token).get(serviceURL + "/" + parameter).andReturn();
				}else {
					re = rdu.getRMEnv(tem).given().header("Authorization", "Bearer "+ token+token+token+token+token).get(serviceURL).andReturn();
				}
                if("500".equals(re.statusCode()+"")){
                    Log.logError("请求返回500,"+state+"次。");
                }else{
                    return re;
                }
            } catch (Exception e) {
                Log.logError("请求超时,"+state+"次。");
            }
        }
        return re;
    }
    
  //get无token请求
    @SuppressWarnings("static-access")
    public static Response Get_Notoken(HashMap<String, Object> data,
                                          String serviceURL) {
        //设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);

        int state=0;
        Response re=null;
        RequestDataUtils rdu=new RequestDataUtils();
        while(state<5){
            try {
                state++;
				re = rdu.getRMEnv(tem).given().cookie("laravel_session",XYZB.laravel_session).get(serviceURL).andReturn();
                
//				System.out.println(re.asString());
				if(!"200".equals(re.statusCode()+"")){
                    Log.logError("请求返回,"+re.statusCode()+"。");
                }else{
                    return re;
                }
            } catch (Exception e) {
                Log.logError("请求超时,"+state+"次。");
            }
        }
        return re;
    }
    
  //get无token请求
    @SuppressWarnings("static-access")
    public static Response Get_Notoken_NoCookie(HashMap<String, Object> data,
                                          String serviceURL) {
        //设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);

        int state=0;
        Response re=null;
        RequestDataUtils rdu=new RequestDataUtils();
        while(state<5){
            try {
                state++;
				re = rdu.getRMEnv(tem).given().get(serviceURL).andReturn();
                
//				System.out.println(re.asString());
				if(!"200".equals(re.statusCode()+"")){
                    Log.logError("请求返回,"+re.statusCode()+"。");
                }else{
                    return re;
                }
            } catch (Exception e) {
                Log.logError("请求超时,"+state+"次。");
            }
        }
        return re;
    }
    
    @SuppressWarnings("static-access")
    public static Response Get_cookie(HashMap<String, Object> data,
                                          String serviceURL) {
        //设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);

        int state=0;
        Response re=null;
        RequestDataUtils rdu=new RequestDataUtils();
        while(state<5){
            try {
                state++;
				re = rdu.getRMEnv(tem).given()
						.cookie("laravel_session",XYZB.laravel_session)
						.cookie("XSRF-TOKEN", XYZB.XSRF_token)
						.get(serviceURL).andReturn();
                if(!"200".equals(re.statusCode()+"")){
                    Log.logError("请求返回,"+re.statusCode()+"。");
                }else{
                    return re;
                }
            } catch (Exception e) {
                Log.logError("请求超时,"+state+"次。");
            }
        }
        return re;
    }
    
    
  //带token的pout请求
  	@SuppressWarnings("deprecation")
	public static Response Put_Token(HashMap<String, Object> data,String token, String serviceURL,Map<String, Object>  jsonAsMap) {

  	//设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);
		// 设置参数格式
		int state = 0;
		Response re = null;
		RequestDataUtils rdu = new RequestDataUtils();
		while (state < 5) {
			try {
				state++;
				re = rdu.getRMEnv(tem).given().config(RestAssured.config()
						.encoderConfig(EncoderConfig.encoderConfig()
								.encodeContentTypeAs("x-www-form-urlencoded", ContentType.ANY)
								.defaultContentCharset("utf-8")))
						.header("Authorization","Bearer "+ token)
								.formParameters(jsonAsMap).
//						.formParam("start_time", "2018-08-31 22:19:42")
//							.formParam("end_time", "2018-08-31 23:00:00")
//							.formParam("room_name", "呜呜呜呜22s11")
//							.formParam("office_type", "国家公务员")
//							.formParam("province", "北京")
//							.formParam("city", "市辖区")
//							.formParam("area", "东城区").
						when().put(serviceURL).thenReturn();
				JsonPath jp = re.body().jsonPath();
				if ("500".equals(jp.getString("status"))) {
					Log.logError("请求返回500," + state + "次。");
					Thread.sleep(1000);
				} else {
					return re;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.logError("请求超时," + state + "次。");
			}
		}
		return re;
	}
    
  //带token的del请求
  	public static Response Del_Token(HashMap<String, Object> data,String token, String serviceURL) {
  	//设置参数格式
        String parameter= MapUtil.getParameter(data);

        String system= MapUtil.getValue("system", data);
        com.offcn.system.system tem=(com.offcn.system.system)(BasicsGM.map.get(system));


		parameter=parameter.substring(1, parameter.length()-1);
        Log.logInfo(data.get("Description").toString()+","+data.get("TCNO").toString()+",Parameter="+parameter);
  			// 设置参数格式
  			Log.logInfo("serviceURL=" + serviceURL + ",Parameter=" + token);
  			int state = 0;
  			Response re = null;
  			RequestDataUtils rdu = new RequestDataUtils();
  			while (state < 5) {
  				try {
  					state++;
  					re = rdu.getRMEnv(tem).given().header("Authorization","Bearer "+ token).
  							when().delete(serviceURL).thenReturn();
  					JsonPath jp = re.body().jsonPath();
  					if ("500".equals(jp.getString("status"))) {
  						Log.logError("请求返回500," + state + "次。");
  						Thread.sleep(1000);
  					} else {
  						return re;
  					}
  				} catch (Exception e) {
  					Log.logError("请求超时," + state + "次。");
  				}
  			}
  			return re;
  		}
    
}
