package com.gx.obe.management.webservice;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.swt.core.CallBack;

import com.alibaba.fastjson.JSONObject;
import com.gx.obe.WebserviceConstants;
import com.gx.obe.business.http.HttpResponse;
import com.gx.obe.business.http.HttpUrl;
import com.gx.obe.business.http.HttpUtils;
import com.gx.obe.common.widget.thread.MyRunnable;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.Chain;
import com.gx.obe.web.entity.tender.TenderProjectEntity;

import hyperledger.FosunBlockChain;

/**
 * @Description: 交易溯源查询
 * @author wangxaing
 */
public class QueryTxSourceThread extends MyRunnable {
	
	private CallBack callBack;
	private Logger LOG = Logger.getLogger(QueryTxSourceThread.class);
	private TenderProjectEntity tenderProject;
	private String blockChainUrl;
	private Chain chain;
	private Map<String,String>  hashMap =  new HashMap<String, String>();
	
	public QueryTxSourceThread(TenderProjectEntity tenderProject, Chain chain,CallBack callBack) {
		this.tenderProject = tenderProject;
		this.chain = chain;
		this.callBack = callBack;
	}
	
	public void run() {
		blockChainUrl = PropertiesUtils.getWebserviceProperty(WebserviceConstants.BLOCK_CHAIN_URL, "");
		boolean queryFlag = getBlockChainInfo();
		if (null != callBack && queryFlag) {
			callBack.callBack(true, hashMap);
		} else {
			callBack.callBack(false, null);
		}
	}
	
	private boolean getBlockChainInfo() {
		if(blockChainUrl.length() == 0){
			LOG.error("未获取到区块链地址！");
			return false;
		}
		
		String params = getParams().toJSONString();
		boolean flag = false;
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("Content-Type" , "application/json");
//		map.put("connection" , "keep-alive");
//		String sendPost = null;
//		try {
//			sendPost = HttpUtils.post(blockChainUrl, params, "POST", "UTF-8",map);
//			flag = resolveXml(tenderProject, sendPost);
//		} catch (Exception e) {
//			LOG.error("", e);
//		}finally{
//			if(!flag){
//				LOG.error("交易溯源查询失败:"+blockChainUrl + "  params :"+params +"返回的结果为：" + sendPost);
//			}
//		}
		
		HttpUrl httpUrl = new HttpUrl(blockChainUrl);
		httpUrl.setRequestProperty("Content-Type" , "application/json");
		httpUrl.setRequestProperty("connection" , "keep-alive");
		HttpResponse httpResponse = HttpUtils.doPost(httpUrl, params);
		flag = resolveXml(httpResponse);
		if(!flag) {
			LOG.error("交易溯源查询失败：" + httpUrl.getUrl() + httpUrl.getUrl() + "\r\n参数：" + params + "\r\n返回："+httpResponse.getContent());
		}
		return flag;
	}
	
	/**
	 * @param sign 
	 * @Description: 交易溯源查询Json字符串
	 * @return
	 */
	private JSONObject getParams() {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", "F103");
		String jsonStr = getJsonObject().toJSONString();
		jsonObject.put("param", jsonStr);
		String sign = null;
		try {
			sign = FosunBlockChain.FB901(jsonObject.get("code").toString(), jsonStr);
		} catch (NoSuchAlgorithmException e) {
			LOG.error("结构化数据签名错误"+ jsonStr , e);
		} catch (IOException e) {
			e.printStackTrace();
		} 
		jsonObject.put("sign", sign);
		
		return jsonObject;
	}
	
	/**
	 * @param b 
	 * @Description: 交易溯源参数Json字符串
	 * @return
	 */
	private JSONObject getJsonObject() {
		JSONObject jsonMap = new JSONObject();
		jsonMap.put("funcName", "FB807");
		jsonMap.put("enquirerCodeType", "00");
		jsonMap.put("enquirerCode", "00000000000000000000");
		jsonMap.put("enquirerOperator", "enquirerOperator");
		jsonMap.put("enquirerOperatorRole", "enquirerOperatorRole");
		jsonMap.put("txHash", chain.getTxHashAddress());
		
		return jsonMap;
	}
	
	
	
	/**
	 * @Description: 是否成功判断
	 * @param tenderProject2
	 * @param sendPost
	 * @return
	 */
	private boolean resolveXml(HttpResponse httpResponse) {
		if(!httpResponse.getStatus()){
			return false;
		}
		/**
		 * 
		 * {"result":true,"msg":"{\"blockHash\":\"0x5bd66c327c43c5839951ded96dbf4b2e6240fc209665f196643c78be1f631b25\",\"blockNumber\":\"0x7976\",\"nonce\":\"6967366681482551\",\"returnCode\":\"S0000\",\"returnMessage\":\"FosunTxhash Success!\",\"timestamp\":\"1566891940060671960\"}"}
		 * */
		try {
			boolean resultObject = ObjectUtils.getObjBoolean(httpResponse.getParam("result"));
			if(resultObject){
				String msg = (String)httpResponse.getParam("msg");
				JSONObject msgRoot = JSONObject.parseObject(msg);
				if(null != msgRoot){
					String blockHash = (String)msgRoot.get("blockHash");	
					String blockNumber = (String)msgRoot.get("blockNumber");	
					String nonce = (String)msgRoot.get("nonce");	
					String timestamp = (String)msgRoot.get("timestamp");	
					
					hashMap.put("blockHash", blockHash);
					hashMap.put("blockNumber", blockNumber);
					hashMap.put("nonce", nonce);
					hashMap.put("timestamp", timestamp);
				}
				
				return resultObject;
			}else{
				LOG.error("交易溯源查询失败："+httpResponse.getContent());
				return false;
			}
		} catch (Exception e) {
		}
		return false;
	}
}
