package com.offcn.api.nwn.service;

import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.json.simple.JSONArray;

import com.offcn.TestUnti.HttpRequest;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.api.nwn.ifUpdatePackage;
import com.offcn.api.nwn.md5.nwngetsign;
import com.offcn.interfaces.API;
import com.offcn.process.NWN;
import com.offcn.process.TK;
import com.offcn.TestUnti.ListUtil;

/**
 * 添加学员信息
 * 
 * @author liyy
 * 
 */
public class addStudent extends NWN implements API {

	public String parameter;// 参数集合

	public String package_id;// 母板ID

	public String phone;//
	public String sso_id;//
	public String user_info;//

	@Override
	public void initialize(HashMap<String, Object> data) {
		// try {
		// Thread.sleep(20000);
		// } catch (InterruptedException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	@Override
	public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
		// 获取parameter对应的内容
		parameter = MapUtil.getValue("parameter", data);
		
		timestamp = MapUtil.getParameter_get(parameter, "timestamp").trim();
		user_info = MapUtil.getParameter_get(parameter, "user_info").trim();
		
		if ((!user_info.equals("")) && user_info.contains("package_id")) {
			package_id=ListUtil.getListValue(n_package_idList, 0);
			parameter = parameter.replace("\"package_id\":package_id", "\"package_id\":"
					+ package_id);
		}
		if ((!user_info.equals("")) && user_info.contains("sso_id")) {
			sso_id= "1" + new Random().nextInt(9000000);
			parameter = parameter.replace("\"sso_id\":sso_id", "\"sso_id\":"
					+ sso_id);
		}
		if ((!user_info.equals("")) && user_info.contains("phone")) {
			phone = "1351" + (new Random().nextInt(9000000) + 1000000);
			parameter = parameter.replace("\"phone\":phone", "\"phone\":"
					+ phone);
		}
		if ((!user_info.equals("")) && user_info.contains("phone1")) {
			phone = "1331" + (new Random().nextInt(9000000) + 1000000);
			parameter = parameter.replace("\"phone\":phone1", "\"phone\":"
					+ phone);
		}
		if ((!user_info.equals("")) && user_info.contains("phone2")) {
			phone = "1321" + (new Random().nextInt(9000000) + 1000000);
			parameter = parameter.replace("\"phone\":phone2", "\"phone\":"
					+ phone);
		}

		if ((!timestamp.equals("")) && timestamp.equals("timestamp")) {
			Long timeString = System.currentTimeMillis();
			timestamp = timeString.toString().substring(0, 10);
			parameter = parameter.replace("timestamp=timestamp", "timestamp="
					+ timestamp);
		}

		data.put("parameter", parameter);
		return data;
	}

	@Override
	public Response SendRequest(HashMap<String, Object> data, String Url,
			String Request) {
		System.out.println("url ===" + Url);
		System.out.println("parameter ===" + parameter);
		Response re = HttpRequest.sendGet("http://beta.alitest.eoffcn.com"
				+ Url, parameter);

		/*
		 * System.out.println(re.getStatusCode());
		 * System.out.println(re.asString());
		 */
		// http://beta.alitest.eoffcn.com/template/addStuden/sign/0e74b43cefd12b43705d22cfdd744efd
		// user_info=[{"package_id":391634,"username":"aaa","phone":15652333337,"sso_id":1}]&timestamp=1548837998&appid=jiaowu
		/*
		 * Response re =HttpRequest.sendGet(
		 * "http://beta.alitest.eoffcn.com/template/addStuden/sign/5d114486999208096dace001ae4bc45a"
		 * ,
		 * "user_info=[{\"package_id\":391634,\"username\":\"aaa\",\"phone\":15656333337,\"sso_id\":1}]&timestamp=1548828632&appid=jiaowu"
		 * );
		 */
		// Response re =
		// HttpRequest.sendGet("http://beta.alitest.eoffcn.com/template/addStudent/sign/2e90e16d93702c6d900577322063463c",
		// "user_info=[{\"package_id\":391634,\"username\":\"aaa\",\"phone\":15652333337,\"sso_id\":1}]&timestamp=1548840818&appid=jiaowu");

		return re;

	}

	@Override
	public String handleOutput(Response re, HashMap<String, Object> data) {
		JsonPath jp = new JsonPath(re.asString());
		System.out.println("jp====" + jp);
		boolean result = true;
		String failReason = "";

		String json = re.asString();
		System.out.println("response=========="
				+ StringUtils.decodeUnicode(json));
		json = StringUtils.decodeUnicode(json);
		if ((data.get("statusCode") != null)
				&& (!data.get("statusCode").toString()
						.equals(String.valueOf(re.getStatusCode())))) {
			result = result && false;
			failReason = failReason + "statusCode is expected "
					+ data.get("statusCode").toString() + " but actually "
					+ String.valueOf(re.getStatusCode()) + ". ";
		}

		if (json.length() != 0) {

			if (!json.contains(data.get("msg").toString())) {
				result = result && false;
				failReason = failReason + "msg is expected "
						+ data.get("msg").toString() + " but actually "
						+ jp.getString("message") + ".";
			}

			if (data.get("custom") != null && json != null) {
				// 如果自定义结果包含多个希望结果，也就是有逗号，那么就切割，包含比较。
				if (data.get("custom").toString().contains(",")) {
					String[] strCustomStrings = data.get("custom").toString()
							.split(",");
					System.out.println(strCustomStrings.length);
					for (int i = 0; i < strCustomStrings.length; i++) {
						if (!json.contains(strCustomStrings[i])) {
							result = result && false;
							failReason = failReason + "custom is expected "
									+ data.get("custom").toString()
									+ " but actually " + strCustomStrings[i]
									+ ".";
							break;
						}
					}
				} else {// 如果只有一个希望结果，就直接包含比较。
					if (!json.contains(data.get("custom").toString())) {
						result = result && false;
						failReason = failReason + "custom is expected "
								+ data.get("custom").toString()
								+ " but actually "
								+ data.get("custom").toString() + ".";
					}
				}
			}

	if("0".equals(jp.getString("retcode"))){
				
				//是否验证数据库
			
		
				if (!isProduct) {
					
					try {
						String sql="SELECT count(*) as num FROM  n_user where phone = " + phone;
						//SELECT  id FROM  n_template ORDER BY id DESC LIMIT 1
						ResultSet rs_bankcard = this.sqlFromDB(sql);
						rs_bankcard.last();
						System.out.println("after addstudent============"+ rs_bankcard.getString("num"));
						
						if("成功0条,失败1条".equals(jp.getString("message"))||Integer.parseInt(rs_bankcard.getString("num")) == Integer.parseInt("1") )
						{
															
								Log.logInfo("template_id info in DB is correct;");
							
						}else {
							result = result && false;
							failReason = failReason + "addstudent info in DB is wrong;";
						}
						
						
					} catch (Exception e) {
						result = result && false;
						failReason = failReason + "cannot verify template_id info in DB;";
						e.printStackTrace();
					}
				}
			

			}
		}
		if (result)
			return "Pass";
		else
			return "Fail:" + failReason;
	}

}
