package com.offcn.process;

import io.restassured.response.Response;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MYSQLConnection;
import com.offcn.TestUnti.XMLread;
import com.offcn.system.sql;


public abstract class BasicsGM {
//	//数据提取

//	public static List<String> rulesEngine_ids = new ArrayList<String>();//决策引擎customer表 id
//	old
	public static boolean isClearMysql =false;
	//new
	public static Connection conn = null;
	public static Statement stmt = null;
	public static ResultSet rs=null;
	public static Map<String,Object> map=new XMLread().getSystem();// 读取XML配置文件

	public static HashMap<String,String> PublicParameter = new HashMap<String,String>();//静态公共参数
	public static HashMap<String,String> DynamicParameter = new HashMap<String,String>();//动态公共参数
	public static  Map<String,Connection> ConnectionsMap=new HashMap<String, Connection>();
	public static  Map<String,Statement> StatementsMap=new HashMap<String, Statement>();
	public static HashMap<Class<?>,Object> Delsql = new HashMap<Class<?>,Object>();//数据库信息源
	public static Set<String> Delsqlset = new HashSet<String>();//数据库信息源

	public static void setDelSystemSql(Class<?> c,Object object){
		String SystemName=c.getSuperclass().getSimpleName();
		int count=Delsqlset.size();
		Delsqlset.add(SystemName);
		if(Delsqlset.size()>count){
			Delsql.put(c, object);
		}
	}

//	
//	public static boolean isProduct =  false;
//	
	//建立数据库连接池Connection对象集合
	//建立数据库连接池Connection对象集合
		public  Map<String,Connection> getConnections(String[] arr){
			XMLread xml=new XMLread();
			Map<String,Object> map=(Map<String, Object>) xml.getDatabaseSql();
			for(int i=0;i<arr.length;i++){
				String a=arr[i];
				sql sys=(sql) map.get(a);
				if(ConnectionsMap.get(arr[i])==null){
					Connection Connection2=MYSQLConnection.coontSql(sys.getSqlurl(), sys.getSqlname(), sys.getSqlpwd());
					ConnectionsMap.put(arr[i], Connection2);
				}
			}
			return ConnectionsMap;
		}


	
		//建立数据库连接池Statements对象集合
		public  Map<String,Statement> getStatements(Map<String,Connection> Map){
			Set<String> keySet = Map.keySet();
			//有了Set集合。就可以获取其迭代器。
			Iterator<String> it = keySet.iterator();
			while(it.hasNext()){
				String key = it.next();
				//有了键可以通过map集合的get方法获取其对应的值。
				Connection value  = Map.get(key);
//				System.out.println("key:"+key+",value:"+value);
				Statement statement=MYSQLConnection.stmtSql(value);
				StatementsMap.put(key, statement);
			}
			return StatementsMap;
		}

	//断开数据库连接
		public void CloseMysql(){
			try {
				if(rs!=null){
					rs.close();
				}
			} catch (Exception e2) {
				Log.logError("关闭结果集失败");
			}
			try { 
				Set<String> keySet = ConnectionsMap.keySet();
				//有了Set集合。就可以获取其迭代器。
				Iterator<String> it = keySet.iterator();
				while(it.hasNext()){
					String key = it.next();
					//有了键可以通过map集合的get方法获取其对应的值。
					Log.logInfo("断开连接:"+key);
					if(StatementsMap.get(key)!=null){
						StatementsMap.get(key).close();
					}
					if (ConnectionsMap.get(key) != null){
						ConnectionsMap.get(key).close();
					}
				}
			} catch (SQLException e) {
				Log.logError("断开连接失败");
				e.printStackTrace();
			}
		}

		//查询表名tableName的条件是condition的结果集
		public ResultSet sqlFromDB_template(String sql) throws Exception {
			ResultSet rs = stmt.executeQuery(sql);
			return rs;

		}
		
		//查询表名tableName的条件是condition的结果集
		public ResultSet sqlFromDB_package(String sql) throws Exception {
			ResultSet rs = stmt.executeQuery(sql);
			return rs;

		}
		
		//清除数据库的方法
		//清除数据库的方法
		public void cleanMysqlData(Class<?> c,Object obj){
			try {
				Class<?> printClass =  c;
				Method printMethod;
				printMethod = printClass.getMethod("cleanMysqlData");
				printMethod.invoke(obj);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		};

		

	//更改huimai.bestbuy_order表，条件是id=orderId，值该为orderStatus
	public static Integer updateOrderStatus(String fromName,String setCondition, String whereCondition) {
		Integer result=null;
		String sql =null;
		try {
			sql = " update  "+fromName+"  set  "+setCondition+"  where  " + whereCondition;
			result = stmt.executeUpdate(sql);//
			if (result == -1) {
				Log.logInfo("update failed! "+sql);
			}else{
				Log.logInfo("update  OK! " + sql);
			}
		} catch (SQLException e) {
			Log.logError("update failed! "+sql);
		}
		return result;
	}
	
	//查询表名tableName的条件是condition的结果集
	public ResultSet selectFromDB(String tableName, String condition) throws Exception {
		String sql;
		ResultSet rs = null;
		sql = " select  *  from  " + tableName + "  where  " + condition;
//		System.out.println(sql);
		rs = stmt.executeQuery(sql);
		return rs;

	}
	
	//查询表名tableName的条件是condition的结果集
		public ResultSet sqlFromDB(String sql) throws Exception {
			ResultSet rs = stmt.executeQuery(sql);
			return rs;

		}
		
	//查询表名tableName的条件是condition的结果集,返回数量
	public ResultSet selectCountFromDB(String tableName, String condition) throws Exception {
		String sql;
		ResultSet rs = null;
		sql = " select  count(*)  from  " + tableName + "  where  " + condition;
		Log.logInfo(sql);
		rs = stmt.executeQuery(sql);
		return rs;

	}
	
	//具体的删除动作，tableName=表名，key列，value值使用的like删除
	public void deleteFromDB(String tableName, String key, String value) throws Exception {
		String sql = "delete from " + tableName + " where " + key + " like '" + value + "'";
		Log.logInfo("sql==="+sql);
		int result = stmt.executeUpdate(sql);
		Log.logInfo("result==="+result);
		if (result == -1) {
			Log.logError("Clean failed!");
		}

	}
	
	public static String splitData(String str, String strStart, String strEnd) {
    	String tempStr;
    	tempStr = str.substring(str.indexOf(strStart) + 1, str.indexOf(strEnd,1));
    	return tempStr;
    	}

	//判断字符串是否是空或者是“”
	public boolean StringIsNull(String str){
		if(str==null || "".equals(str)){
			return false;
		}else{
			return true;
		}
	}
	
	//获取errcode或code，或者msg或errmsg，返回去作为用例输出结果
	public String getCode( Response re){
		try {
			String code=JSONObject.fromObject(re.body().asString()).getString("code");
			if(StringIsNull(code)){
				return code;
			}
		} catch (Exception e) {
		}
		
		try {
			String status=JSONObject.fromObject(re.body().asString()).getString("status");
			if(StringIsNull(status)){
				return status;
			}
		} catch (Exception e) {
		}
		
		try {
			String retcode=JSONObject.fromObject(re.body().asString()).getString("retcode");
			if(StringIsNull(retcode)){
				return retcode;
			}
		} catch (Exception e) {
		}
		
		
		try {
			String errcode=JSONObject.fromObject(re.body().asString()).getString("errcode");
			if(StringIsNull(errcode)){
				return errcode;
			}
		} catch (Exception e) {
		}
		return null;
	}
	//获取errcode或code，或者msg或errmsg，返回去作为用例输出结果
	public String getMsg( Response re){
		try {
			String msg=JSONObject.fromObject(re.body().asString()).getString("msg");
			if(StringIsNull(msg)){
				return msg;
			}
		} catch (Exception e) {
		}
		
		try {
			String message=JSONObject.fromObject(re.body().asString()).getString("message");
			if(StringIsNull(message)){
				return message;
			}
		} catch (Exception e) {
		}
		
		try {
			String errmsg=JSONObject.fromObject(re.body().asString()).getString("errmsg");
			if(StringIsNull(errmsg)){
				return errmsg;
			}
		} catch (Exception e) {
		}
		
		return null;
	}

	
	//setDynamicParameter动态代理
		@SuppressWarnings("unchecked")
		public HashMap<String, Object> setDynamicParameter(Class<?> c,Object object,HashMap<String, Object> data) {
			try {
				Class<?> printClass =  c;
				Method printMethod;
				printMethod = printClass.getMethod("setDynamicParameter",HashMap.class);
				return (HashMap<String, Object>) printMethod.invoke(object,data);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			return null;
		}

		//setPublicParameter静态变量动态代理
		@SuppressWarnings("unchecked")
		public HashMap<String, Object> setPublicParameter(Class<?> c,Object object,HashMap<String, Object> data) {
			try {
				Class<?> printClass =  c;
				Method printMethod;
				printMethod = printClass.getMethod("setPublicParameter",HashMap.class);
				return (HashMap<String, Object>) printMethod.invoke(object,data);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			return null;
		}

	
}
