package com.palmnest.application.core.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.OAuthConstants;
import com.palmnest.dao.estateserve.NeigouOrderDao;

public class SpaceHomeUtil {

	private static Logger LOG = Logger.getLogger(SpaceHomeUtil.class);

	@Autowired
	private static NeigouOrderDao neigouOrderDao;

	/**
	 * 创建用户登录使用的login_token
	 * 第三方用户唯一标识 （必填）
	 * 第三方用户所在公司唯一标识（非必填）
	 *
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	/*public static void SynchCompany(Map<String,Object> mapObs) throws UnsupportedEncodingException {//NeigouOAuth2Details oauthDetails,String accessToken,String user_company_id,String user_id


		LOG.info("NeigouOAuthUtils--CreateLoginToken======");

		//LOG.info("NeigouOAuthUtils--CreateLoginToken user_id======"+user_id);

		//LOG.info("NeigouOAuthUtils--CreateLoginToken 使用 accessToken======"+accessToken);

		//platform_id:100000021
		//encrypt_key:e10adc3949ba59abbe56e057f20f883e

		String platform_id="100000021";
		String encrypt_key="e10adc3949ba59abbe56e057f20f883e";

		//创建公司 url
		//HttpPost post = new HttpPost(oauthDetails.getCreatelogintoken_url());
		HttpPost post = new HttpPost("https://testgateway.superxz.com/api/v1/company/import");
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/createLoginToken");


		List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();


		JSONObject jsonData=new JSONObject();
		//jsonData.put("platform_id", platform_id);
		parametersBody.add(new BasicNameValuePair("platform_id",platform_id));


		Long datatimeStr=new Date().getTime();
		datatimeStr=Long.valueOf("1516159601298");
		//jsonData.put("timestamp", datatimeStr.toString());//公司Id		
		parametersBody.add(new BasicNameValuePair("timestamp",datatimeStr.toString()));

		List jsonList=new ArrayList();
		Map jsonMap=new HashMap();

		jsonMap.put("Id", "11");//公司Id
		jsonMap.put("Name", "测试公司11");//公司名称		
		jsonMap.put("Phone", "13066855666");		
		jsonMap.put("ContactName", "联系人11");//联系人	

		jsonList.add(jsonMap);

		jsonMap=new HashMap();

		jsonMap.put("Id", "12");//公司Id
		jsonMap.put("Name", "测试公司12");//公司名称		
		jsonMap.put("Phone", "13066855888");		
		jsonMap.put("ContactName", "联系人12");//联系人	
		jsonList.add(jsonMap);

		jsonList.add(mapObs);

		String companyJsonData=JSONObject.toJSONString(jsonList);
		System.out.println("同步公司信息==="+companyJsonData);


		//jsonData.put("data", companyJsonData);
		parametersBody.add(new BasicNameValuePair("data",URLEncoder.encode(companyJsonData,"UTF-8")));
		String signature=Encrypt(datatimeStr+companyJsonData+encrypt_key,"SHA-256");

		//String ss=Encrypt("1516159601298张三e10adc3949ba59abbe56e057f20f883e","");
		//System.out.println(ss);

		签名方法：
		例如: sha256(timestamp + data + encrpty_ke
		y)
		注意要小写。
		其中 timestamp 需要和请求中的 timestamp 保持一
		致; data 为请求中的 data 参数（不需要 urlencode）; se
		cretKey 是由行政超人将平台 ID 一起发放的;
		加密的数据是 utf-8 格式的
		//jsonData.put("signature", signature);
		parametersBody.add(new BasicNameValuePair("signature",signature));


		LOG.info("NeigouOAuthUtils--CreateLoginToken BasicNameValuePair data======"+jsonData.toJSONString());
		//parametersBody.add(new BasicNameValuePair("data", jsonData.toJSONString()));	


		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String createCompanyResult = null;
		try {
			post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
			System.out.println(parametersBody);

			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == OAuthConstants.HTTP_UNAUTHORIZED) {
				LOG.info("Authorization server expects Basic authentication");
				LOG.info("Retry with client credentials");
				post.releaseConnection();
				response = client.execute(post);
				code = response.getStatusLine().getStatusCode();
				if (code == 401 || code == 403) {
					LOG.info("Could not authenticate using client credentials.");
					//throw new RuntimeException("Could not retrieve access token for client: "+ oauthDetails.getClientId());

				}

			}
			Map map = NeigouOAuthUtils.handleResponse(response);
			System.out.println("同步公司返回信息==="+map);
			//createCompanyResult = (String)map.get("Result");

			//JSONObject tokenJsonData=(JSONObject)map.get("Data");
			//createCompanyResult=(String)tokenJsonData.get("login_token");


			JSONObject tokenJsonData=JSONObject.parseObject((String)map.get("Data"));
			if(tokenJsonData.containsKey("login_token")){
				createCompanyResult=(String) tokenJsonData.get("login_token");
			}


			//String ss=EntityUtils.toString(response.getEntity());
			//LOG.info(ss);

		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		}

	}*/
	public static String SynchCompany(Map<String, Object> mapObs) throws UnsupportedEncodingException {//NeigouOAuth2Details oauthDetails,String accessToken,String user_company_id,String user_id


		StringBuffer returnStr = new StringBuffer();

		LOG.info("SpaceHomeUtil--SynchCompany======");

		//LOG.info("NeigouOAuthUtils--CreateLoginToken user_id======"+user_id);

		//LOG.info("NeigouOAuthUtils--CreateLoginToken 使用 accessToken======"+accessToken);

		//platform_id:100000021
		//encrypt_key:e10adc3949ba59abbe56e057f20f883e

		String encrypt_key = PropertiesKit.readPropertiesValue("spacehome_encrypt_key", "oauth2Client.properties");
		String platform_id = PropertiesKit.readPropertiesValue("spacehome_platform_id", "oauth2Client.properties");
		String spacehome_synchcompany_url = PropertiesKit.readPropertiesValue("spacehome_synchcompany_url", "oauth2Client.properties");

		LOG.info("SpaceHomeUtil--encrypt_key======" + encrypt_key);
		LOG.info("SpaceHomeUtil--platform_id======" + platform_id);
		LOG.info("SpaceHomeUtil--spacehome_synchcompany_url======" + spacehome_synchcompany_url);

		//String platform_id="200000021";
		//String encrypt_key="jinvk23osrnaculb77wvh48tgekgydcr";

		//创建公司 url
		HttpPost post = new HttpPost(spacehome_synchcompany_url);
		//HttpPost post = new HttpPost(oauthDetails.getCreatelogintoken_url());
		//HttpPost post = new HttpPost("https://gateway.superxz.com/api/v1/company/import");
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/createLoginToken");


		List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();


		//JSONObject jsonData=new JSONObject();
		//jsonData.put("platform_id", platform_id);
		parametersBody.add(new BasicNameValuePair("platform_id", platform_id));


		Long datatimeStr = new Date().getTime();
		//datatimeStr=Long.valueOf("1516159601298");
		//jsonData.put("timestamp", datatimeStr.toString());//公司Id		
		parametersBody.add(new BasicNameValuePair("timestamp", datatimeStr.toString()));

		List jsonList = new ArrayList();
		/*Map jsonMap=new HashMap();

		jsonMap.put("Id", "56");//公司Id
		jsonMap.put("Name", "前海超级前台");//公司名称	

		jsonMap.put("ContactUserId", "4173");//公司Id		
		jsonMap.put("Phone", "13066855666");		
		jsonMap.put("ContactName", "青章银");//联系人	

		jsonList.add(jsonMap);*/

		/*jsonMap=new HashMap();

		jsonMap.put("Id", "12");//公司Id
		jsonMap.put("Name", "测试公司12");//公司名称		
		jsonMap.put("Phone", "13066855888");		
		jsonMap.put("ContactName", "联系人12");//联系人	
		jsonList.add(jsonMap);*/

		jsonList.add(mapObs);

		String companyJsonData = JSONObject.toJSONString(jsonList);
		System.out.println("同步公司信息===" + companyJsonData);
		LOG.info("SpaceHomeUtil--spacehome_synchcompany_url======" + companyJsonData);


		returnStr.append("同步公司信息===" + companyJsonData).append("\n");

		//jsonData.put("data", companyJsonData);
		parametersBody.add(new BasicNameValuePair("data", URLEncoder.encode(companyJsonData, "UTF-8")));
		String signature = Encrypt(datatimeStr + companyJsonData + encrypt_key, "SHA-256");

		//String ss=Encrypt("1516159601298张三e10adc3949ba59abbe56e057f20f883e","");
		//System.out.println(ss);

		/*签名方法：
		例如: sha256(timestamp + data + encrpty_ke
		y)
		注意要小写。
		其中 timestamp 需要和请求中的 timestamp 保持一
		致; data 为请求中的 data 参数（不需要 urlencode）; se
		cretKey 是由行政超人将平台 ID 一起发放的;
		加密的数据是 utf-8 格式的*/
		//jsonData.put("signature", signature);
		parametersBody.add(new BasicNameValuePair("signature", signature));
		LOG.info("SpaceHomeUtil--signature======" + signature);


		//LOG.info("SpaceHomeUtil--jsonData.toJSONString()======"+jsonData.toJSONString());
		//parametersBody.add(new BasicNameValuePair("data", jsonData.toJSONString()));	


		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String createCompanyResult = null;
		try {
			post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
			System.out.println(parametersBody);
			returnStr.append("parametersBody===" + parametersBody).append("\n");

			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == OAuthConstants.HTTP_UNAUTHORIZED) {
				LOG.info("Authorization server expects Basic authentication");
				LOG.info("Retry with client credentials");
				post.releaseConnection();
				response = client.execute(post);
				code = response.getStatusLine().getStatusCode();
				if (code == 401 || code == 403) {
					LOG.info("Could not authenticate using client credentials.");
					//throw new RuntimeException("Could not retrieve access token for client: "+ oauthDetails.getClientId());

				}

			}
			Map map = NeigouOAuthUtils.handleResponse(response);
			System.out.println("同步公司返回信息===" + map);
			LOG.info("SpaceHomeUtil--同步公司返回信息=========" + map);
			returnStr.append("同步公司返回信息=========" + map).append("\n");


		} catch (ClientProtocolException e) {
			LOG.error(LogExceptionStackUtil.LogExceptionStack(e));
			returnStr.append("erroe==========" + LogExceptionStackUtil.LogExceptionStack(e)).append("\n");
		} catch (IOException e) {
			LOG.error(LogExceptionStackUtil.LogExceptionStack(e));
			returnStr.append("erroe==========" + LogExceptionStackUtil.LogExceptionStack(e)).append("\n");
		}

		return returnStr.toString();

	}

	/**
	 * 创建用户登录使用的login_token
	 * 第三方用户唯一标识 （必填）
	 * 第三方用户所在公司唯一标识（非必填）
	 *
	 * @throws UnsupportedEncodingException
	 */
	/*	public static String SynchUser(List<Map<String,Object>> listObs) throws UnsupportedEncodingException {//NeigouOAuth2Details oauthDetails,String accessToken,String user_company_id,String user_id

		LOG.info("NeigouOAuthUtils--CreateLoginToken======");

		//LOG.info("NeigouOAuthUtils--CreateLoginToken user_id======"+user_id);

		//LOG.info("NeigouOAuthUtils--CreateLoginToken 使用 accessToken======"+accessToken);

		//platform_id:100000021
		//encrypt_key:e10adc3949ba59abbe56e057f20f883e

		String platform_id="100000021";
		String encrypt_key="e10adc3949ba59abbe56e057f20f883e";

		//创建公司 url
		//HttpPost post = new HttpPost(oauthDetails.getCreatelogintoken_url());
		HttpPost post = new HttpPost("https://testgateway.superxz.com/api/v1/manager/import");
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/createLoginToken");


		List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();


		JSONObject jsonData=new JSONObject();
		//jsonData.put("platform_id", platform_id);
		parametersBody.add(new BasicNameValuePair("platform_id",platform_id));


		Long datatimeStr=new Date().getTime();
		//jsonData.put("timestamp", datatimeStr.toString());//公司Id		
		parametersBody.add(new BasicNameValuePair("timestamp",datatimeStr.toString()));

		List jsonList=new ArrayList();
		Map jsonMap=new HashMap();

		jsonMap.put("Id", "user5");//公司Id
		jsonMap.put("Name", "user4");//公司名称		
		jsonMap.put("Phone", "13066855666");		
		jsonMap.put("CompanyId", "4");//联系人	

		jsonList.add(jsonMap);

		jsonMap=new HashMap();

		jsonMap.put("Id", "user6");//公司Id
		jsonMap.put("Name", "user6");//公司名称		
		jsonMap.put("Phone", "13066855666");		
		jsonMap.put("CompanyId", "4");//联系人	

		jsonList.add(jsonMap);

        for (int i = 0; i < listObs.size(); i++) {
        	Map<String,Object> mapOb= listObs.get(i);
        	if(i==0){
        		continue;
        	}

        	Map jsonMap=new HashMap();
        	jsonMap.put("Id", mapOb.get("ContactUserId"));//子管理员id
    		jsonMap.put("Name", mapOb.get("ContactName"));//子管理员name		
    		jsonMap.put("Phone", mapOb.get("Phone"));		
    		jsonMap.put("CompanyId", mapOb.get("Id"));//公司id	

    		jsonList.add(jsonMap);

		}


		String companyJsonData=JSONObject.toJSONString(jsonList);
		System.out.println("子管理员同步信息==="+companyJsonData);

		//jsonData.put("data", companyJsonData);
		parametersBody.add(new BasicNameValuePair("data",companyJsonData));
		String signature=Encrypt(datatimeStr+companyJsonData+encrypt_key,"SHA-256");

		签名方法：
		例如: sha256(timestamp + data + encrpty_ke
		y)
		注意要小写。
		其中 timestamp 需要和请求中的 timestamp 保持一
		致; data 为请求中的 data 参数（不需要 urlencode）; se
		cretKey 是由行政超人将平台 ID 一起发放的;
		加密的数据是 utf-8 格式的
		//jsonData.put("signature", signature);
		parametersBody.add(new BasicNameValuePair("signature",signature));


		LOG.info("NeigouOAuthUtils--CreateLoginToken BasicNameValuePair data======"+jsonData.toJSONString());
		//parametersBody.add(new BasicNameValuePair("data", jsonData.toJSONString()));	


		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String createCompanyResult = null;
		try {
			post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
			System.out.println(parametersBody);

			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == OAuthConstants.HTTP_UNAUTHORIZED) {
				LOG.info("Authorization server expects Basic authentication");
				LOG.info("Retry with client credentials");
				post.releaseConnection();
				response = client.execute(post);
				code = response.getStatusLine().getStatusCode();
				if (code == 401 || code == 403) {
					LOG.info("Could not authenticate using client credentials.");
					//throw new RuntimeException("Could not retrieve access token for client: "+ oauthDetails.getClientId());

				}

			}
			Map map = NeigouOAuthUtils.handleResponse(response);
			System.out.println("子管理员同步返加信息==="+map);
			//createCompanyResult = (String)map.get("Result");

			//JSONObject tokenJsonData=(JSONObject)map.get("Data");
			//createCompanyResult=(String)tokenJsonData.get("login_token");


			JSONObject tokenJsonData=JSONObject.parseObject((String)map.get("Data"));
			if(tokenJsonData.containsKey("login_token")){
				createCompanyResult=(String) tokenJsonData.get("login_token");
			}
			System.out.println(tokenJsonData);

			//String ss=EntityUtils.toString(response.getEntity());
			//LOG.info(ss);

		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		}

		return createCompanyResult;
	}*/

	/*public static String SynchUser(List<Map<String,Object>> listObs) throws UnsupportedEncodingException {

		LOG.info("NeigouOAuthUtils--CreateLoginToken======");

		//LOG.info("NeigouOAuthUtils--CreateLoginToken user_id======"+user_id);

		//LOG.info("NeigouOAuthUtils--CreateLoginToken 使用 accessToken======"+accessToken);

		//platform_id:100000021
		//encrypt_key:e10adc3949ba59abbe56e057f20f883e

		String platform_id="200000021";
		String encrypt_key="jinvk23osrnaculb77wvh48tgekgydcr";

		//创建公司 url
		//HttpPost post = new HttpPost(oauthDetails.getCreatelogintoken_url());
		HttpPost post = new HttpPost("https://gateway.superxz.com/api/v1/manager/import");
		//HttpPost post = new HttpPost("http://openapi.test.neigou.com/ChannelInterop/V1/Standard/User/createLoginToken");


		List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();


		JSONObject jsonData=new JSONObject();
		//jsonData.put("platform_id", platform_id);
		parametersBody.add(new BasicNameValuePair("platform_id",platform_id));


		Long datatimeStr=new Date().getTime();
		//jsonData.put("timestamp", datatimeStr.toString());//公司Id		
		parametersBody.add(new BasicNameValuePair("timestamp",datatimeStr.toString()));

		List jsonList=new ArrayList();	
		Map jsonMap=new HashMap();

		jsonMap.put("Id", "2890");//公司Id
		jsonMap.put("Name", "舒谦");//公司名称		
		jsonMap.put("Phone", "13902220969");		
		jsonMap.put("CompanyId", "56");//联系人	
		jsonList.add(jsonMap);

		jsonMap=new HashMap();
		jsonMap.put("Id", "4403");//公司Id
		jsonMap.put("Name", "陈文礼");//公司名称		
		jsonMap.put("Phone", "13922202307");		
		jsonMap.put("CompanyId", "56");//联系人
		jsonList.add(jsonMap);

		jsonMap=new HashMap();	
		jsonMap.put("Id", "4417");//公司Id
		jsonMap.put("Name", "南山彩娇");//公司名称		
		jsonMap.put("Phone", "15019433985");		
		jsonMap.put("CompanyId", "56");//联系人	


		jsonMap=new HashMap();	
		jsonMap.put("Id", "4236");//公司Id
		jsonMap.put("Name", "青章银");//公司名称		
		jsonMap.put("Phone", "18589021134");		
		jsonMap.put("CompanyId", "56");//联系人
		jsonList.add(jsonMap);

		jsonMap=new HashMap();	
	jsonMap.put("Id", "4233");//公司Id
	jsonMap.put("Name", "卢少珊");//公司名称		
	jsonMap.put("Phone", "13590475230");		
	jsonMap.put("CompanyId", "56");//联系人
	jsonList.add(jsonMap);


		jsonMap=new HashMap();	
	jsonMap.put("Id", "4097");//公司Id
	jsonMap.put("Name", "姚经纬");//公司名称		
	jsonMap.put("Phone", "18810741383");		
	jsonMap.put("CompanyId", "56");//联系人
	jsonList.add(jsonMap);

		    for (int i = 0; i < listObs.size(); i++) {
    	Map<String,Object> mapOb= listObs.get(i);
    	if(i==0){
    		continue;
    	}

    	Map jsonMap=new HashMap();
    	jsonMap.put("Id", mapOb.get("ContactUserId"));//子管理员id
		jsonMap.put("Name", mapOb.get("ContactName"));//子管理员name		
		jsonMap.put("Phone", mapOb.get("Phone"));		
		jsonMap.put("CompanyId", mapOb.get("Id"));//公司id	

		jsonList.add(jsonMap);

	}


		String companyJsonData=JSONObject.toJSONString(jsonList);
		System.out.println("子管理员同步信息==="+companyJsonData);

		//jsonData.put("data", companyJsonData);
		parametersBody.add(new BasicNameValuePair("data",companyJsonData));
		String signature=Encrypt(datatimeStr+companyJsonData+encrypt_key,"SHA-256");

		签名方法：
	例如: sha256(timestamp + data + encrpty_ke
	y)
	注意要小写。
	其中 timestamp 需要和请求中的 timestamp 保持一
	致; data 为请求中的 data 参数（不需要 urlencode）; se
	cretKey 是由行政超人将平台 ID 一起发放的;
	加密的数据是 utf-8 格式的
		//jsonData.put("signature", signature);
		parametersBody.add(new BasicNameValuePair("signature",signature));


		LOG.info("NeigouOAuthUtils--CreateLoginToken BasicNameValuePair data======"+jsonData.toJSONString());
		//parametersBody.add(new BasicNameValuePair("data", jsonData.toJSONString()));	


		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String createCompanyResult = null;
		try {
			post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
			System.out.println(parametersBody);

			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == OAuthConstants.HTTP_UNAUTHORIZED) {
				LOG.info("Authorization server expects Basic authentication");
				LOG.info("Retry with client credentials");
				post.releaseConnection();
				response = client.execute(post);
				code = response.getStatusLine().getStatusCode();
				if (code == 401 || code == 403) {
					LOG.info("Could not authenticate using client credentials.");
					//throw new RuntimeException("Could not retrieve access token for client: "+ oauthDetails.getClientId());

				}

			}
			Map map = NeigouOAuthUtils.handleResponse(response);
			System.out.println("子管理员同步返加信息==="+map);
			//createCompanyResult = (String)map.get("Result");

			//JSONObject tokenJsonData=(JSONObject)map.get("Data");
			//createCompanyResult=(String)tokenJsonData.get("login_token");


			JSONObject tokenJsonData=JSONObject.parseObject((String)map.get("Data"));
			if(tokenJsonData.containsKey("login_token")){
			createCompanyResult=(String) tokenJsonData.get("login_token");
		}
			System.out.println(tokenJsonData);

			//String ss=EntityUtils.toString(response.getEntity());
			//LOG.info(ss);

		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		}

		return createCompanyResult;
	}*/

	//同步子管理员
	public static String SynchUser(List<Map<String, Object>> listObs) throws UnsupportedEncodingException {//NeigouOAuth2Details oauthDetails,String accessToken,String user_company_id,String user_id


		StringBuffer returnStr = new StringBuffer();

		LOG.info("SpaceHomeUtil--SynchUser======");

		//LOG.info("NeigouOAuthUtils--CreateLoginToken user_id======"+user_id);

		//LOG.info("NeigouOAuthUtils--CreateLoginToken 使用 accessToken======"+accessToken);

		//platform_id:100000021
		//encrypt_key:e10adc3949ba59abbe56e057f20f883e

		String encrypt_key = PropertiesKit.readPropertiesValue("spacehome_encrypt_key", "oauth2Client.properties");
		String platform_id = PropertiesKit.readPropertiesValue("spacehome_platform_id", "oauth2Client.properties");
		String spacehome_synchuser_url = PropertiesKit.readPropertiesValue("spacehome_synchuser_url", "oauth2Client.properties");

		LOG.info("SpaceHomeUtil--encrypt_key======" + encrypt_key);
		LOG.info("SpaceHomeUtil--platform_id======" + platform_id);
		LOG.info("SpaceHomeUtil--spacehome_synchuser_url======" + spacehome_synchuser_url);

		//String platform_id="200000021";
		//String encrypt_key="jinvk23osrnaculb77wvh48tgekgydcr";

		//创建公司 url
		HttpPost post = new HttpPost(spacehome_synchuser_url);


		List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();


		parametersBody.add(new BasicNameValuePair("platform_id", platform_id));


		Long datatimeStr = new Date().getTime();
		parametersBody.add(new BasicNameValuePair("timestamp", datatimeStr.toString()));

		List jsonList = new ArrayList();

		//jsonList.add(mapObs);

		for (int i = 0; i < listObs.size(); i++) {

			Map<String, Object> mapOb = listObs.get(i);
			Map jsonMap = new HashMap();
			jsonMap.put("Id", mapOb.get("ContactUserId"));//子管理员id
			jsonMap.put("Name", mapOb.get("ContactName"));//子管理员name		
			jsonMap.put("Phone", mapOb.get("Phone"));
			jsonMap.put("CompanyId", mapOb.get("Id"));//公司id	

			jsonList.add(jsonMap);

		}

		String companyJsonData = JSONObject.toJSONString(jsonList);
		System.out.println("同步子管理员信息===" + companyJsonData);
		LOG.info("SpaceHomeUtil--spacehome_synchcompany_url======" + companyJsonData);


		returnStr.append("同步子管理员信息===" + companyJsonData).append("\n");

		//jsonData.put("data", companyJsonData);
		parametersBody.add(new BasicNameValuePair("data", URLEncoder.encode(companyJsonData, "UTF-8")));
		String signature = Encrypt(datatimeStr + companyJsonData + encrypt_key, "SHA-256");

		//String ss=Encrypt("1516159601298张三e10adc3949ba59abbe56e057f20f883e","");
		//System.out.println(ss);

		/*签名方法：
		例如: sha256(timestamp + data + encrpty_ke
		y)
		注意要小写。
		其中 timestamp 需要和请求中的 timestamp 保持一
		致; data 为请求中的 data 参数（不需要 urlencode）; se
		cretKey 是由行政超人将平台 ID 一起发放的;
		加密的数据是 utf-8 格式的*/
		//jsonData.put("signature", signature);
		parametersBody.add(new BasicNameValuePair("signature", signature));
		LOG.info("SpaceHomeUtil--signature======" + signature);

		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		String createCompanyResult = null;
		try {
			post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
			System.out.println(parametersBody);
			returnStr.append("parametersBody===" + parametersBody).append("\n");

			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == OAuthConstants.HTTP_UNAUTHORIZED) {
				LOG.info("Authorization server expects Basic authentication");
				LOG.info("Retry with client credentials");
				post.releaseConnection();
				response = client.execute(post);
				code = response.getStatusLine().getStatusCode();
				if (code == 401 || code == 403) {
					LOG.info("Could not authenticate using client credentials.");

				}

			}
			Map map = NeigouOAuthUtils.handleResponse(response);
			System.out.println("同步子管理员返回信息===" + map);
			LOG.info("SpaceHomeUtil--同步子管理员返回信息=========" + map);
			returnStr.append("同步子管理员返回信息=========" + map).append("\n");


		} catch (ClientProtocolException e) {
			LOG.error(LogExceptionStackUtil.LogExceptionStack(e));
			returnStr.append("erroe==========" + LogExceptionStackUtil.LogExceptionStack(e)).append("\n");
		} catch (IOException e) {
			LOG.error(LogExceptionStackUtil.LogExceptionStack(e));
			returnStr.append("erroe==========" + LogExceptionStackUtil.LogExceptionStack(e)).append("\n");
		}

		return returnStr.toString();

	}

	/**
	 * 对字符串加密,加密算法使用MD5,SHA-1,SHA-256,默认使用SHA-256
	 *
	 * @param strSrc  要加密的字符串
	 * @param encName 加密类型
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String Encrypt(String strSrc, String encName) throws UnsupportedEncodingException {
		MessageDigest md = null;
		String strDes = null;


		//String xmString = new String(strSrc.toString().getBytes("UTF-8"));  
		//String xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");  

		byte[] bt = strSrc.getBytes("utf-8");
		System.out.println(bt);
		//byte[] bt = xmlUTF8.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "SHA-256";
			}
			md = MessageDigest.getInstance(encName);
			md.reset();
			md.update(bt);
			//strDes = bytes2Hex(md.digest()); // to HexString //请求会变
			strDes = byteToHex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
		return strDes;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

		//SynchCompany(null);
		SynchUser(null);

		//List<Map<String,Object>> listObs=neigouOrderDao.getCompanyAndSuperUser("成都中航国际交流中心项目部");
		//System.out.println(listObs);

		//String ss=Encrypt("1516159601298张三e10adc3949ba59abbe56e057f20f883e","");
		//System.out.println(ss);

		/*链接类似这种 具体的一会提供  https://www.superxz.com/login?platform_id=100000021&sso_code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
		sso_code  内容是  时间戳|用户ID 如  1516171192|12345   通过刚才给的那个java文件加密  加密key和同步数据那个key一样
		我们这边的流程是  通过 platform_id 查到 对应的盐值  然后解密sso_code  获取到时间和用户id  然后进行有效期验证和登录*/

		//String platform_id="100000021";
		/*String encrypt_key="jinvk23osrnaculb77wvh48tgekgydcr";

		String userId="4173";
		Long datatimeStr=new Date().getTime();
		//datatimeStr=Long.valueOf("123456789");
		String sso_codeData=datatimeStr+"|"+userId;
		System.out.println(sso_codeData);
		String sso_code=Java_AES_Cipher.encrypt(encrypt_key,sso_codeData);
		System.out.println(sso_code);*/

		//String desso_code=Java_AES_Cipher.decrypt(encrypt_key,sso_codeData);
		//System.out.println(desso_code);
	}

}
