package com.gx.obe.evaluation.step.thread;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

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.listener.ProgressMessageListener;
import com.gx.obe.common.widget.thread.MyRunnable;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.UuidUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierBidBond;
import com.gx.obe.web.entity.TransactionServer;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.SupplierBidBondService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.TenderProjectService;
import com.gx.utils.ActionLogUtils;

import common.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/** 
 * @Description: 获得投标保证金
 * @author wangx 
 */
public class DownLoadSupplierBidBondThread extends MyRunnable{

	private Thread thread;
	private TenderProjectEntity tenderProject;
	private TenderProjectService tenderProjectService = new TenderProjectService();
	private SupplierBidBondService supplierBidBondService = new SupplierBidBondService();
	private SupplierService supplierService = new SupplierService();
	private Logger LOG = Logger.getLogger(DownLoadSupplierBidBondThread.class);
	private ProgressMessageListener messageListener;
	private ThreadPoolExecutor threadPool;
	
	public DownLoadSupplierBidBondThread(TenderProjectEntity tenderProject, ProgressMessageListener messageListener){
		this.tenderProject = tenderProject;
		this.messageListener = messageListener;
	}
	
	public void start(){
		thread = new Thread(this);
		thread.setName(tenderProject.getTenderName()+"获取投标保证金");
		thread.start();
	}
	
	public void join(){
		if(null != thread){
			try {
				thread.join();
			} catch (InterruptedException e) {
			}
		}
	}
	public void stop(){
		thread = null;
		if(null != threadPool){
			threadPool.shutdownNow();
		}
	}
	
	public void run() {
		long start = Calendar.getInstance().getTimeInMillis();
		final TransactionServer transactionServer = HttpUtils.getTransactionServer(tenderProject.getTransactionServerId());
		if(null == transactionServer) {
			if(null != messageListener)
			messageListener.finish(true);
			return;
		}
		List<Future<Boolean>> allTenderPackFutureList = new ArrayList<Future<Boolean>>();
		final String method = PropertiesUtils.getWebserviceProperty(WebserviceConstants.GET_PROJECT_SUPPLIER_METHOD, "");
		if(null == tenderProject.getParentId() && CommonEnum.YES.equals(tenderProject.getIsPack())){
			
			List<TenderProjectEntity> tenderPackList = tenderProjectService.getSubPackageList(tenderProject.getId());
			if(null != tenderPackList){
				int poolSize = tenderPackList.size() > 5 ? 5 :tenderPackList.size();
				threadPool = new ThreadPoolExecutor(poolSize, poolSize, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadPoolExecutor.CallerRunsPolicy());
				for(final TenderProjectEntity tenderPack : tenderPackList){
					allTenderPackFutureList.add(threadPool.submit(new Callable<Boolean>() {
						public Boolean call(){
							boolean flag = false;
							if(null != thread){
								HttpUrl httpUrl = HttpUtils.getProjectHttpUrl(tenderPack, tenderProject, transactionServer, method);
								if(null != httpUrl){
									HttpResponse httpResponse = HttpUtils.doPost(httpUrl);
									flag = resolveXml(tenderPack, httpResponse);
									ActionLogUtils.addServerLog(tenderPack.getId(), "获取投标保证金 ", httpUrl, flag);
								}
							}
							return flag;
						}
					}));
				}
				threadPool.shutdown();
			}
		}else {
			threadPool = new ThreadPoolExecutor(1, 1, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadPoolExecutor.CallerRunsPolicy());
			allTenderPackFutureList.add(threadPool.submit(new Callable<Boolean>() {
				
				public Boolean call() throws Exception {
					boolean flag = false;
					HttpUrl httpUrl = HttpUtils.getProjectHttpUrl(tenderProject, null, transactionServer, method);
					
					if(null != httpUrl){
						HttpResponse httpResponse = HttpUtils.doPost(httpUrl);
						flag = resolveXml(tenderProject, httpResponse);
						ActionLogUtils.addServerLog(tenderProject.getId(), "获取投标保证金 ", httpUrl, flag);
					}else {
						messageListener.message(Messages.LoginDialog_connectionFail, -1);
					}
					return flag;
				}
			}));
			threadPool.shutdown();
		}	
		boolean synFlag = true;
		for(Future<Boolean> future : allTenderPackFutureList){
			if(null == thread){
				break;
			}
			try {
				if(!future.get()){
					synFlag = false;
				}
			} catch (InterruptedException e) {
				LOG.error("", e);
			} catch (ExecutionException e) {
				LOG.error("", e);
			}
		}
		if(null != thread && null != messageListener){
			long useTime = Calendar.getInstance().getTimeInMillis() - start;
			if(useTime < 2000){
				try {
					Thread.sleep(2000- useTime);
				} catch (InterruptedException e) {
				}
			}
			
			if(synFlag) {
				messageListener.message("获取保证金结束！", 1);
			}else {
				messageListener.message("获取保证金失败！", -1);
			}
			messageListener.finish(synFlag);
		}
	}
	
	/**
	 * @Description: 解析返回的xml
	 * @author guoyr
	 * @param xmlStr
	 * @return
	 */
	private boolean resolveXml(TenderProjectEntity tenderProjectEntity, HttpResponse httpResponse){
		if(!httpResponse.getStatus())return false;
	        JSONArray supplierBidList = httpResponse.getDataJSONArray("supplierBidList");
	        if (null == supplierBidList) {
	        	messageListener.message(tenderProjectEntity.getTenderNo() + tenderProjectEntity.getTenderName() + "未获取到投标保证金信息！", -1);
	            return false;
	        }
	        
	        List<Supplier> supplierList = supplierService.getAllSupplierList(tenderProjectEntity.getId());
	        Map<String,Supplier>  supplierMap = new HashMap<String,Supplier>();
	        if(null != supplierList && supplierList.size() > 0) {
	        	for(Supplier supplier : supplierList) {
	        		supplierMap.put(supplier.getOrgId(), supplier);
	        	}
	        }
	        List<SupplierBidBond> supplierBidBondList = new ArrayList<SupplierBidBond>();
	        Map<String,SupplierBidBond>  supplierBondMap = new HashMap<String,SupplierBidBond>();
	        List<SupplierBidBond>  oldSupplierBidBondList = supplierBidBondService.getSupplierBondByTenderId(tenderProjectEntity.getId());
	        if(null != oldSupplierBidBondList && oldSupplierBidBondList.size() > 0) {
	        	for(SupplierBidBond supplierBidBond : oldSupplierBidBondList) {
	        		supplierBondMap.put(supplierBidBond.getSupplierId().concat(supplierBidBond.getRenderTime().toString()), supplierBidBond);
	        	}
	        }
	        
	        for (Object object : supplierBidList.toArray()) {
	        	JSONObject supplierBid = (JSONObject) object;
	        	String mainId = ObjectUtils.getObjString(supplierBid.get("mainId"));
	        	if(null != mainId) {
	        		Supplier supplier = supplierMap.get(mainId);
	        		if(null != supplier) {
	        			SupplierBidBond  supplierBidBond = null;
	        			String inDate = (String)supplierBid.get("indate");
						String inTime = (String)supplierBid.get("intime");
						String dateString = (null != inDate ? inDate : "").concat("-").concat(null != inTime ? inTime : "")  ;
						
						Date date=null;
						if(null != dateString && dateString.length() > 0){
							SimpleDateFormat formatter=new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
						    try {
								date=formatter.parse(dateString);
							} catch (ParseException e) {
							}
						    if(null != date) {
						    	supplierBidBond = supplierBondMap.get(supplier.getId().concat(date.toString()));
						    }
						}
						if(null == supplierBidBond && null != date) {
							supplierBidBond = new SupplierBidBond();
							supplierBidBond.setId(UuidUtils.getUUID());
							supplierBidBond.setRenderTime(date);//保证金缴纳时间
							supplierBidBond.setTenderId(tenderProjectEntity.getId());
							supplierBidBond.setSupplierId(supplier.getId());
							String bidBond = (String)supplierBid.get("inamount");
							if (null == bidBond || bidBond.length() == 0) {
								supplierBidBond.setAmount(null);
							} else {
								supplierBidBond.setAmount(ObjectUtils.getObjBigDecimal(bidBond));
							}
							String isBasicAccount = (String)supplierBid.get("isBasicAccount");
							if(null != isBasicAccount && isBasicAccount.length() == 1){
								supplierBidBond.setBidCashDeposiPpayType(isBasicAccount);//是否基本户汇出
							}
							supplierBidBondList.add(supplierBidBond);
						}
	        		}
	        	}
	        }
	        
		if(CollectionUtils.isNotNull(supplierBidBondList)){
			if (supplierBidBondService.batchSaveSupplierBidBond(supplierBidBondList)) {
				return true;
			}else {
				messageListener.message(tenderProjectEntity.getTenderNo() + tenderProjectEntity.getTenderName() + "保存投标保证金信息完成", -1);
			}
		}
		return false;
	}
	
}
