package weaver.hrm.pm.action;

import com.alibaba.fastjson.JSONObject ;
import weaver.conn.RecordSet ;
import weaver.general.Util ;
import weaver.general.BaseBean ;
import weaver.general.MD5 ;
import org.apache.http.client.methods.HttpRequestBase ;
import org.apache.commons.collections.MapUtils ;
import java.io.IOException ;
import org.apache.http.client.methods.HttpPost ;
import org.apache.http.entity.StringEntity ;
import org.apache.http.Consts ;
import org.apache.http.impl.client.CloseableHttpClient ;
import org.apache.http.client.methods.CloseableHttpResponse ;
import org.apache.http.HttpEntity ;
import org.apache.http.util.EntityUtils ;
import org.apache.http.StatusLine ;
import javax.net.ssl.SSLContext ;
import org.apache.http.conn.socket.ConnectionSocketFactory ;
import org.apache.http.config.Registry ;
import org.apache.http.config.RegistryBuilder ;
import org.apache.http.conn.socket.PlainConnectionSocketFactory ;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory ;
import org.apache.http.conn.ssl.NoopHostnameVerifier ;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager ;
import org.apache.http.impl.client.HttpClients ;
import java.security.NoSuchAlgorithmException ;
import java.security.KeyManagementException ;
import javax.net.ssl.X509TrustManager ;
import java.security.cert.CertificateException ;
import weaver.interfaces.workflow.action.Action;
import javax.net.ssl.TrustManager ;
import org.apache.commons.lang3.StringUtils ;
import java.util.* ;
import com.alibaba.fastjson.JSON ;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

/**
 * @description:人员入职
 * @author:xuxy
 * @createTime: 2024/10/28
 * @version: 1.0
 */
public class SyndeliUserRzAction implements Action {

	@Override
	public String execute(RequestInfo requestInfo) {
		BaseBean bb = new BaseBean();
		BaseBean log = new BaseBean();
		String path = "/v2.0/employee";
		String url = "http://v2-api.delicloud.com" + path;
		//获取主表数据
		Map mainInfo = getMainInfo(requestInfo);
		log.writeLog("入职流程主表信息：mainInfo:{}",mainInfo);
		//此处获取主表字段信息
		String sfzh = Util.null2String(mainInfo.get("sfzh"));//id
		log.writeLog("-UpdateHrmOrgInfo-主表数据是：" + sfzh);
		try {

			String key = bb.getPropValue("deliCloud", "key");
			String secret = bb.getPropValue("deliCloud", "secret");
			log.writeLog("key:" + key + "</br>");
			log.writeLog("secret:" + secret + "</br>");

			if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(secret)) {
				String sjc = String.valueOf(Calendar.getInstance().getTimeInMillis());
				String appSig = getAppSigData(path, key, secret, sjc);

				log.writeLog("sjc:" + sjc + "</br>");
				log.writeLog("appSig:" + appSig + "</br>");

				Map<String, String> heads = new HashMap<String, String>();
				heads.put("App-Key", key);
				heads.put("App-Timestamp", sjc);
				heads.put("App-Sig", appSig);
				heads.put("Api-Module", "CHECKIN");
				heads.put("Api-Cmd", "checkin_query");

				Map<String, String> userMap = getUserData(sfzh);
				String workcode = Util.null2String(userMap.get("workcode"));
				String lastname = Util.null2String(userMap.get("lastname"));
				String mobile = Util.null2String(userMap.get("mobile"));
				String deptcode = Util.null2String(userMap.get("departmentcode"));
				String deptname = Util.null2String(userMap.get("departmentname"));
				String deptid = Util.null2String(userMap.get("departmentid"));
				String subcompanyid1 = Util.null2String(userMap.get("subcompanyid1"));

				log.writeLog("workcode:" + workcode + "</br>");
				log.writeLog("lastname:" + lastname + "</br>");
				log.writeLog("mobile:" + mobile + "</br>");

				log.writeLog("deptcode:" + deptcode + "</br>");
				log.writeLog("deptname:" + deptname + "</br>");
				log.writeLog("deptid:" + deptid + "</br>");
				log.writeLog("subcompanyid1:" + subcompanyid1 + "</br>");

				int errorcount = 0;
				log.writeLog("key:" + key + "</br>");
				log.writeLog("secret:" + secret + "</br>");
				int errorcount1 = updateSubcompanyData2(subcompanyid1, key, secret);
				errorcount = errorcount + errorcount1;
				log.writeLog("errorcount1:" + errorcount1 + "</br>");

				int errorcount2 = updateDeptData(deptid, key, secret);
				errorcount = errorcount + errorcount2;
				log.writeLog("errorcount2:" + errorcount2 + "</br>");

				if (errorcount == 0) {

					Map<String, Object> dataMap = new HashMap<String, Object>();
					dataMap.put("employee_ext_id", workcode);
					dataMap.put("name", lastname);
					dataMap.put("mobile", mobile);
					dataMap.put("employee_num", workcode);

					List<Map<String, Object>> department_infolist = new ArrayList<Map<String, Object>>();
					Map<String, Object> department_infos = new HashMap<String, Object>();
					department_infos.put("ext_id", deptcode);
					department_infos.put("title", deptname);
					department_infolist.add(department_infos);
					dataMap.put("department_infos", department_infolist);

					log.writeLog("employee-headers:" + JSONObject.toJSONString(heads) + "</br>");
					log.writeLog("employee-body:" + JSONObject.toJSONString(dataMap) + "</br>");

					String back = doPostJsonRequest(url, heads, JSON.toJSONString(dataMap));
					bb.writeLog("response:" + back);
					log.writeLog("employee-response:" + back + "</br>");
					JSONObject backObj = JSONObject.parseObject(back);
					String code = backObj.getString("code");
					String data = backObj.getString("data");
					log.writeLog("employee-code:" + code + "</br>");
					if (!"0".equals(code)) {
						errorcount++;
					}
				}
			}
			return SUCCESS;
		} catch (Exception e) {
			bb.writeLog("数据异常!");
			bb.writeLog(e.getMessage());
		}
		return FAILURE_AND_CONTINUE;
	}


	public List<Map<String,String>> getSubcompanyListByParentid(String supsubcomid){
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> map = null;
		RecordSet rs = new RecordSet();

		String sql =" with tem_table(id,subcompanyname,supsubcomid,subcompanycode,curlevel) as (\n" +
				"   select id,subcompanyname,supsubcomid,subcompanycode,1 as level \n" +
				"          from HrmSubCompany where id = " + supsubcomid +
				"   union all\n" +
				"   select a.id,a.subcompanyname,a.supsubcomid,a.subcompanycode,b.curlevel+1\n" +
				"   from HrmSubCompany a \n" +
				//"   inner join tem_table  b on (a.id = b.supsubcomid)\n" +
				"   inner join tem_table  b on (a.supsubcomid = b.id)\n" +
				" )\n" +
				" select l.*,k.subcompanycode as supsubcompanycode from tem_table l " +
				" left join HrmSubCompany k on l.supsubcomid = k.id " ;

		rs.executeQuery(sql);
		while (rs.next()){
			String subcompanycode = rs.getString("subcompanycode");
			String subcompanyname = rs.getString("subcompanyname");
			String sup_subcomid = rs.getString("supsubcomid");
			String supsubcompanycode = rs.getString("supsubcompanycode");

			map = new HashMap<String,String>();
			map.put("subcompanycode",subcompanycode);
			map.put("subcompanyname",subcompanyname);
			map.put("supsubcomid",sup_subcomid);
			map.put("supsubcompanycode",supsubcompanycode);
			list.add(map);
		}

		if(list !=null && list.size() > 0){
			Collections.reverse(list);
		}

		return list;
	}


	public List<Map<String,String>> getDeptListByParentid(String supsubcomid){
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> map = null;
		RecordSet rs = new RecordSet();

		String sql =" with tem_table(id,departmentname,supdepid,departmentcode,subcompanyid1,curlevel) as(\n" +
				"   select id,departmentname,supdepid,departmentcode,subcompanyid1,1 as level \n" +
				"        from HrmDepartment where id =" + supsubcomid +
				"   union all\n" +
				"   select a.id,a.departmentname,a.supdepid,a.departmentcode,a.subcompanyid1,b.curlevel+1                          \n" +
				"        from HrmDepartment  a \n" +
				"   inner join tem_table b on (a.id = b.supdepid) \n" +
				" )\n" +
				" select p.*,k.departmentcode as supdeptcode,h.subcompanycode from tem_table p\n" +
				" left join HrmDepartment k on p.supdepid = k.id " +
				" left join hrmsubcompany h on h.id = p.subcompanyid1 " ;

		rs.executeQuery(sql);
		while (rs.next()){
			String departmentcode = rs.getString("departmentcode");
			String subcompanycode = rs.getString("subcompanycode");
			String departmentname = rs.getString("departmentname");
			String sup_depid = rs.getString("supdepid");
			String supdeptcode = rs.getString("supdeptcode");
			if(StringUtils.isBlank(supdeptcode)){
				supdeptcode = subcompanycode;
			}
			map = new HashMap<String,String>();
			map.put("departmentcode",departmentcode);
			map.put("departmentname",departmentname);
			map.put("supdepid",sup_depid);
			map.put("supdeptcode",supdeptcode);
			list.add(map);
		}

		if(list !=null && list.size() > 0){
			Collections.reverse(list);
		}

		return list;
	}

	/***
	 *
	 * @param path
	 * @param key
	 * @param sercet
	 * @param sjc
	 * @return
	 */
	public String getAppSigData(String path,String key,String sercet,String sjc){

		String appSig = "";
		BaseBean bb = new BaseBean();
		try{
			MD5 md5 = new MD5();
			String all = path + sjc + key + sercet;
			String sig = md5.getMD5ofStr(all);
			bb.writeLog("sig:" + sig);
			Scanner sc = new Scanner(md5.getMD5ofStr(all));
			String str = sc.next();
			char[] arrays = str.toCharArray();

			for (int i = 0; i < arrays.length; i++) {
				char c1 = arrays[i];
				if (c1 >= 65 && c1 <= 90) {
					char c2 = toLowerCase(c1);//如果输入是大写  ,则调用toLowerCase方法
					appSig = appSig + c2;
				} else {
					appSig = appSig + c1;
				}
			}
			bb.writeLog("appSig:" + appSig);
		}catch (Exception e){

		}
		return appSig;
	}


	/***
	 *
	 * @param c1
	 * @return
	 */
	public static char toLowerCase(char c1){
		int a = (int) c1;//将接收到的小写字符c1转换成int类型的数据给a
		int b =a+32;     //a+32得出大写写对应小写的ascll数值
		char bb = (char)b;//最后将b转换成char类型字符给bb
		return bb;        //返回bb；就是返回字母小写的字符

	}


	private static void prepareHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
		if (!MapUtils.isEmpty(headers)) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httpRequest.addHeader(entry.getKey(), entry.getValue());
			}
		}
	}


	public static String doPostJsonRequest(String url, Map<String, String> headers, String jsonStr) throws IOException {
		HttpPost httpost = new HttpPost(url);
		BaseBean bb = new BaseBean();
		bb.writeLog("doPostJsonRequest:"+url);
		prepareHeaders(httpost, headers);
		StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpost.setEntity(entity);
		bb.writeLog("doPostJsonRequest:"+jsonStr);
		return sendRequest(httpost);
	}


	private static String sendRequest(HttpRequestBase httpRequest) throws IOException {
		String result = null;
		BaseBean bb = new BaseBean();
		bb.writeLog("sendRequest3333");
		CloseableHttpClient httpclient = creteClient();
		bb.writeLog("sendRequest44444");
		try (CloseableHttpResponse resp = httpclient.execute(httpRequest)) {
			bb.writeLog("sendRequest-response:" + resp + "</br>");
			HttpEntity entity = resp.getEntity();
			bb.writeLog("sendRequest-entity:" + entity + "</br>");
			result = (entity == null ? null : EntityUtils.toString((HttpEntity) entity, Consts.UTF_8));
			bb.writeLog("sendRequest-result:" + result + "</br>");
			StatusLine statusLine = resp.getStatusLine();
			if (statusLine.getStatusCode() >= 300) {
				EntityUtils.consume((HttpEntity) entity);
//                String errorMsg = Strings.lenientFormat("Http status abnormal-status code is %s, response is %s", resp.getStatusLine().getStatusCode(), result);
			}
		}
		return result;
	}


	public static CloseableHttpClient creteClient() {
		//采用绕过验证的方式处理https请求
		BaseBean bb = new BaseBean();
		try {
			SSLContext sslcontext = createIgnoreVerifySSL();
			// 设置协议http和https对应的处理socket链接工厂的对象
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
					.register("http", PlainConnectionSocketFactory.INSTANCE)
					.register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE))
					.build();
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
			HttpClients.custom().setConnectionManager(connManager);

			//创建自定义的httpclient对象
			CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
			return client;
		} catch (Exception e) {
			bb.writeLog("CloseableHttpClient:"+e);
			return null;
		}

	}


	/**
	 * 绕过验证
	 *
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext sc = SSLContext.getInstance("SSLv3");

		// 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
		X509TrustManager trustManager = new X509TrustManager() {
			@Override
			public void checkClientTrusted(
					java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(
					java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}

			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};

		sc.init(null, new TrustManager[]{trustManager}, null);
		return sc;
	}


	public Map<String,String> getUserData(String sfzh){

		Map<String,String> userMap = new HashMap<String,String>();
		String workcode = "";
		String departmentid = "";
		String subcompanyid1 = "";
		String departmentcode = "";
		String lastname = "";
		String mobile = "";
		String departmentname = "";

		RecordSet rs = new RecordSet();


		try{
			if(StringUtils.isNotBlank(sfzh)){
				String sql =  "select t.workcode,t.departmentid,t.subcompanyid1,t.lastname,t.mobile,k.departmentcode,k.departmentname " +
						" from hrmresource t inner join hrmdepartment k on k.id = t.departmentid" +
						" where t.certificatenum = ? and t.status in (0,1,2,3) ";

				rs.executeQuery(sql,new Object[]{sfzh});
				if(rs.next()){
					workcode = Util.null2String(rs.getString("workcode"));
					departmentid = Util.null2String(rs.getString("departmentid"));
					subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
					departmentcode = Util.null2String(rs.getString("departmentcode"));
					lastname = Util.null2String(rs.getString("lastname"));
					mobile = Util.null2String(rs.getString("mobile"));

					departmentname = Util.null2String(rs.getString("departmentname"));
				}
			}
		}catch (Exception e){

		}

		userMap.put("workcode",workcode);
		userMap.put("lastname",lastname);
		userMap.put("mobile",mobile);
		userMap.put("departmentcode",departmentcode);
		userMap.put("departmentname",departmentname);
		userMap.put("departmentid",departmentid);
		userMap.put("subcompanyid1",subcompanyid1);

		return userMap;
	}


	public int updateSubcompanyData2(String subcompanyid1,String key,String secret){
		BaseBean bb = new BaseBean();
		bb.writeLog("updateSubcompanyData2:start" +"</br>");
		bb.writeLog("updateSubcompanyData2:subcompanyid1" +subcompanyid1+"</br>");
		bb.writeLog("updateSubcompanyData2:key" +key+"</br>");
		bb.writeLog("updateSubcompanyData2:secret" +secret+"</br>");
		String path = "/v2.0/department";
		String url = "http://v2-api.delicloud.com"+path;

		String sjc = String.valueOf(Calendar.getInstance().getTimeInMillis());
		String appSig = getAppSigData(path,key,secret,sjc);


		Map<String, String> heads = new HashMap<String, String>();
		heads.put("App-Key", key);
		heads.put("App-Timestamp", sjc);
		heads.put("App-Sig", appSig);
		heads.put("Api-Module", "CHECKIN");
		heads.put("Api-Cmd", "checkin_query");

		int errorcount = 0;
		List<Map<String,String>> childSubcompanyList = getSubcompanyListByParentid(subcompanyid1);
		bb.writeLog("updateSubcompanyData2:childSubcompanyList" +childSubcompanyList+"</br>");
		for(int k=0;k<childSubcompanyList.size();k++) {
			Map<String, String> childSubcompanyMap = childSubcompanyList.get(k);
			String subcompanycode = childSubcompanyMap.get("subcompanycode");
			String subcompanyname = childSubcompanyMap.get("subcompanyname");
			String supsubcompanycode = childSubcompanyMap.get("supsubcompanycode");
			bb.writeLog("updateSubcompanyData2:supsubcompanycode" +supsubcompanycode+"</br>");
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("department_ext_id", subcompanycode);
			dataMap.put("name", subcompanyname);
			dataMap.put("p_ext_id", supsubcompanycode);
			bb.writeLog("updateSubcompanyData2:dataMap" +dataMap+"</br>");
			String back = null;
			try {
				String jsonString = JSON.toJSONString(dataMap);
				bb.writeLog("updateSubcompanyData:jsonString" + jsonString + "</br>");
				back = doPostJsonRequest(url, heads, jsonString);
				bb.writeLog("updateSubcompanyData:back" + back + "</br>");
			} catch (IOException e) {
				bb.writeLog("updateSubcompanyData2:IOException" +e.getMessage()+"</br>");
				throw new RuntimeException(e);
			}
			JSONObject backObj = JSONObject.parseObject(back);
			bb.writeLog("updateSubcompanyData:backObj" + backObj + "</br>");
			String code = backObj.getString("code");
			String data = backObj.getString("data");
			if (!"0".equals(code)) {
				errorcount++;
			}
		}
		bb.writeLog("updateSubcompanyData:" + errorcount + "</br>");
		bb.writeLog("updateSubcompanyData2:end" +"</br>");
		return errorcount;
	}


	public int updateDeptData(String deptid,String key,String secret){
		BaseBean bb = new BaseBean();
		bb.writeLog("updateDeptData:start" +"</br>");
		bb.writeLog("updateDeptData:deptid" +deptid+"</br>");
		bb.writeLog("updateDeptData:key" +key+"</br>");
		bb.writeLog("updateDeptData:secret" +secret+"</br>");
		String path = "/v2.0/department";
		String url = "http://v2-api.delicloud.com"+path;

		String sjc = String.valueOf(Calendar.getInstance().getTimeInMillis());
		String appSig = getAppSigData(path,key,secret,sjc);


		Map<String, String> heads = new HashMap<String, String>();
		heads.put("App-Key", key);
		heads.put("App-Timestamp", sjc);
		heads.put("App-Sig", appSig);
		heads.put("Api-Module", "CHECKIN");
		heads.put("Api-Cmd", "checkin_query");

		int errorcount = 0;
		List<Map<String,String>> childDepartmentList = getDeptListByParentid(deptid);
		for(int k=0;k<childDepartmentList.size();k++){
			Map<String,String> childDepartmentMap = childDepartmentList.get(k);
			String departmentcode = childDepartmentMap.get("departmentcode");
			String departmentname = childDepartmentMap.get("departmentname");
			String supdeptcode = childDepartmentMap.get("supdeptcode");

			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("department_ext_id", departmentcode);
			dataMap.put("name", departmentname);
			dataMap.put("p_ext_id", supdeptcode);

			String back = null;
			try {
				back = doPostJsonRequest(url, heads, JSON.toJSONString(dataMap));
			} catch (IOException e) {
				bb.writeLog("updateDeptData:IOException" +e.getMessage()+"</br>");
				throw new RuntimeException(e);
			}
			JSONObject backObj = JSONObject.parseObject(back);
			String code = backObj.getString("code");
			String data = backObj.getString("data");
			if (!"0".equals(code)) {
				errorcount++;
			}
		}
		bb.writeLog("updateDeptData:" + errorcount + "</br>");
		bb.writeLog("updateDeptData:end" +"</br>");
		return errorcount;
	}
	/**
	 * 根据requestInfo获取主表数据
	 * */
	public static Map getMainInfo(RequestInfo requestInfo){
		Map map = new HashMap();
		Property[] property = requestInfo.getMainTableInfo().getProperty();
		for (int i = 0; i < property.length; i++) {
			map.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue()));
		}
		return map;
	}


}
