package com.gx.obe.management.webservice;

import hyperledger.HttpUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.eclipse.swt.core.CallBack;

import com.gx.obe.common.widget.thread.MyRunnable;
import com.gx.obe.util.utils.AuthTokenUtil;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.expert.Expert;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.expert.ExpertService;
/**
 * @Description: 上传公信区块链
 * @author wangxaing
 */
public class UploadGxThread extends MyRunnable {

	private CallBack callBack;
	private ExpertService expertService;
	private SupplierService supplierService = new SupplierService();
	private Logger LOG = Logger.getLogger(UploadGxThread.class);
	
	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectRuleEntity tenderProjectRuleEntity;

	public UploadGxThread(TenderProjectEntity tenderProjectEntity, CallBack callBack) {
		this.tenderProjectEntity = tenderProjectEntity;
		this.callBack = callBack;
		expertService = new ExpertService();
	}

	public void run() {
//		boolean upLoadFlag = uploadGx();
		boolean upLoadFlag = true;

		if (null != callBack && upLoadFlag) {
			callBack.callBackBoolean(true);
		} else {
			callBack.callBackBoolean(false);
		}
	}

	private boolean uploadGx() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		JSONObject json = new JSONObject();
		json.element("requesttime", sdf.format(new Date()));
		String token = "";
//		Properties configProperties = PropertiesUtils.getProperties("config.properties");
//		String AppKey = ObjectUtils.getObjString(configProperties.getProperty(ConfigConstants.APPKEY));
//		String AppSecret = ObjectUtils.getObjString(configProperties.getProperty(ConfigConstants.APPSECRET));
		try {
			token = AuthTokenUtil.createToken("国家平台提供", "国家平台提供", 60, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//拼接XML
		String xmlString  = getXmlToString();
		
		json.element("token", token);
		json.element("content", xmlString);
		json.element("instance_id", UUID.randomUUID().toString());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssss");
		String dateStr = dateFormat.format(new Date());
		json.element("requesttime", dateStr);
		String joStr = json.toString();

		String getWebserviceXml ="";
		try {
//			String gxIp = ObjectUtils.getObjString(configProperties.getProperty(ConfigConstants.GXQUL_IP));
			
			getWebserviceXml = HttpUtils.sendPost("http://ip:port/EPDataExService/rest/dataex/datatransfer", joStr);
		} catch (Exception e) {
			LOG.error("上传公信区块链返回的xml结果为：" + getWebserviceXml, e);
		}
		return resolveXml(tenderProjectEntity, getWebserviceXml);
	}


	/** 生成xml信息
	 * @return
	 */
	private String getXmlToString() {
		Document document = DocumentHelper.createDocument();
		Element rootElement = document.addElement("ROOT");
		addHeadData(rootElement);
		addDesContextData(rootElement);
		addDesBinarys(rootElement);
		addSingAtures(rootElement);
		return document.asXML();
	}	
	
	private void addHeadData(Element rootElement) {
		Element headDataElement = rootElement.addElement("HEADDATA");
		headDataElement.addElement("FROMPLATFORMCODE").setText("wujtTPFrame");
		Element toPlatFormCodeElement = headDataElement.addElement("TOPLATFORMCODE");
		Element dataNoElement = headDataElement.addElement("DATA_NO");
		Element dataEnElement = headDataElement.addElement("DATA_EN");
		Element dataCnElement = headDataElement.addElement("DATA_CN");
		Element dataTypeElement = headDataElement.addElement("DATA_TYPE");
		Element dataKeyElement = headDataElement.addElement("DATA_KEY");
		Element timeStampElement = headDataElement.addElement("TIMESTAMP");
		Element versionElement = headDataElement.addElement("VERSION");
		
	}
	
	private void addDesContextData(Element rootElement) {
		Element desContextElement = rootElement.addElement("DESCONTEXT");
		desContextElement.addElement("TRADEPLATF_PROJECTCODE").setText("");
		desContextElement.addElement("PROJECT_CODE").setText("");
		desContextElement.addElement("PROJECT_ID").setText("");
		desContextElement.addElement("PROJECT_NAME").setText("");
		desContextElement.addElement("REGION_CODE").setText("");
		desContextElement.addElement("PROJECT_ADDRESS").setText("");
		desContextElement.addElement("RELATE_CODE").setText("");
		desContextElement.addElement("INVEST_PROJECT_CODE").setText("");
		desContextElement.addElement("INDUSTRIES_TYPE").setText("");
		desContextElement.addElement("ADDRESS").setText("");
		desContextElement.addElement("LEGAL_PERSON").setText("");
		desContextElement.addElement("LEGAL_PERSON_ADDRESS").setText("");
		desContextElement.addElement("JIANSHEUNITORGNUM").setText("");
		desContextElement.addElement("TENDERERCATEGORY").setText("");
		desContextElement.addElement("TENDERERROLE").setText("");
		desContextElement.addElement("WEITUODANWEI").setText("");
		desContextElement.addElement("WEITUODATE").setText("");
		desContextElement.addElement("LIANXIUSER").setText("");
		desContextElement.addElement("LIANXIMOBILE").setText("");
		desContextElement.addElement("LIANXITEL").setText("");
		desContextElement.addElement("TOUZIGUSUAN").setText("");
		desContextElement.addElement("INVESTMENTAMOUNT").setText("");
		desContextElement.addElement("CURRENCYCODE").setText("");
		desContextElement.addElement("PRICEUNIT").setText("");
		desContextElement.addElement("FUND_SOURCE").setText("");
		desContextElement.addElement("INVESTRESOURCE").setText("");
		desContextElement.addElement("CONTRIBUTION_SCALE").setText("");
		desContextElement.addElement("PROJECT_SCALE").setText("");
		desContextElement.addElement("CONTACTOR").setText("");
		desContextElement.addElement("ISLIXIANG").setText("");
		desContextElement.addElement("NOTLIXIANG").setText("");
		desContextElement.addElement("APPROVAL_NAME").setText("");
		desContextElement.addElement("APPROVAL_NUMBER").setText("");
		desContextElement.addElement("APPROVAL_AUTHORITY").setText("");
		desContextElement.addElement("CREATE_TIME").setText("");
		desContextElement.addElement("EXAMINERNAME").setText("");
		desContextElement.addElement("EXAMINERCODETYPE").setText("");
		desContextElement.addElement("EXAMINERCODE").setText("");
		desContextElement.addElement("VERIFYTIME").setText("");
		desContextElement.addElement("BATCH_NO").setText("");
		desContextElement.addElement("VERSION").setText("");
		desContextElement.addElement("ATTACHMENTCODE").setText("");
		desContextElement.addElement("XIAQUNAME").setText("");
		desContextElement.addElement("PLATFORM_CODE_REGION").setText("");
		desContextElement.addElement("PLATFORM_CODE").setText("");
		desContextElement.addElement("PUB_SERVICE_PLAT_CODE").setText("");
		desContextElement.addElement("TRADE_PLAT").setText("");
		desContextElement.addElement("PUB_SERVICE_PLAT").setText("");
		desContextElement.addElement("DATA_TIMESTAMP").setText("");
		 
		Element supplierListElement = desContextElement.addElement("SUPPLIERLIST");
		List<Supplier> supplierList = supplierService.getSupplierList(tenderProjectEntity.getId());
		if(null != supplierList && supplierList.size() > 0){
			for(Supplier supplier :supplierList){
				Element supplierElement = supplierListElement.addElement("SUPPLIER");
				supplierElement.addElement("BID_CODE_TYPE").setText("");
				supplierElement.addElement("BID_CODE").setText("");
				supplierElement.addElement("BID_NEME").setText("");
				supplierElement.addElement("BID_QUOTE").setText("");
				supplierElement.addElement("DECRYPTION_TIME").setText("");
				supplierElement.addElement("BID_FINAL_SCORE").setText("");
				supplierElement.addElement("BID_FINAL_RANKING").setText("");
				supplierElement.addElement("WIN_CANDIDATE").setText("");
			}
		}
		
		Element expertListElement = desContextElement.addElement("EXPERTLIST");
		List<Expert> expertList = expertService.getExpertList(tenderProjectEntity.getId(), null);
		if(null != expertList && expertList.size() > 0){
			for(Expert expert :expertList){
				Element expertElement = expertListElement.addElement("EXPERT");
				expertElement.addElement("EXPERT_NAME").setText("");
				expertElement.addElement("EXPERT_CODE").setText("");
				expertElement.addElement("EXPERT_SIGN_TIME").setText("");
			}
		}
	}
	
	private void addDesBinarys(Element rootElement) {
		Element desBinarysElement = rootElement.addElement("DESBINARYS");
		List<File> attachmentFileList = new ArrayList<File>();
		if(null != attachmentFileList && attachmentFileList.size() > 0){
			for(File file : attachmentFileList){
				Element desBinaryElement = 	desBinarysElement.addElement("DESBINARY");
				desBinaryElement.addElement("ATTACHMENT_SET_CODE").setText("");
				desBinaryElement.addElement("ATTACHMENT_COUNT").setText("");
				desBinaryElement.addElement("ATTACHMENT_CODE").setText("");
				desBinaryElement.addElement("ATTACHMENT_NAME").setText("");
				desBinaryElement.addElement("ATTACHMENT_TYPE").setText("");
				desBinaryElement.addElement("MD5").setText("");
				desBinaryElement.addElement("ATTACHMENT_FILE_NAME").setText("");
				desBinaryElement.addElement("URL").setText("");
			}
		}
	}
	
	private void addSingAtures(Element rootElement) {
		
	}


	/**
	 * @param tenderProjectEntity
	 * @param xmlStr
	 * @return
	 */
	private boolean resolveXml(TenderProjectEntity tenderProjectEntity, String xmlStr) {
		if (null == xmlStr || "".equals(xmlStr)) {
			LOG.error("服务器无响应内容!");
			return false;
		}
		try {
			JSONObject root = JSONObject.fromObject(xmlStr);
			JSONObject headerObject = (JSONObject) root.get("DataBody");
			if (null != headerObject && headerObject.get("Status").equals(true)) {
				return true;
			} else {
				LOG.error("上传公信区块链接口服务器返回内容：" + xmlStr);
				return false;
			}
		} catch (Exception e) {
		}
		return false;
	}
	
}
