package com.gx.obe.management.thread;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

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

import com.gx.obe.business.entity.EvaluationFactorItem;
import com.gx.obe.business.entity.SupplierEvaluationFactor;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.components.core.enumeration.EvaluationFactorEnum;
import com.gx.obe.util.utils.BigDecimalUtils;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.UuidUtils;
import com.gx.obe.util.utils.XmlUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.evaluation.EvaluationFactor;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.EvaluationFactorItemService;
import com.gx.obe.web.service.SupplierEvaluationFactorService;
import com.gx.obe.web.service.SupplierService;
import com.gx.utils.ParsingSupplierResponseXmlUtils;

/**
 * @Description: 自动解析并导入招标或投标文件下的指标xml
 * @author guoyr
 */
public class SupplierEvaluationFactorXmlResolverThread implements Runnable {
	
	private SupplierService supplierService = new SupplierService();
	private SupplierEvaluationFactorService supplierEvaluationFactorService ;
	private EvaluationFactorItemService evaluationFactorItemService ;
	private Thread thread;
	private TenderProjectEntity tenderProjectEntity;
	private CallBack callBack;
	private Logger LOG = Logger.getLogger(SupplierEvaluationFactorXmlResolverThread.class);
	private int sorNo = 1;
	{
		LogUtils.logClass(SupplierEvaluationFactorXmlResolverThread.class);
	}
	
	/**
	 * 无参构造方法
	 */
	public SupplierEvaluationFactorXmlResolverThread(){}
	
	/** 有参构造方法
	 * @param tenderProjectEntity 项目信息
	 * @param callBack 回调函数
	 */
	public SupplierEvaluationFactorXmlResolverThread(TenderProjectEntity tenderProjectEntity, CallBack callBack){
		this.tenderProjectEntity = tenderProjectEntity;
		this.callBack = callBack;
		supplierEvaluationFactorService = new SupplierEvaluationFactorService();
		evaluationFactorItemService = new EvaluationFactorItemService();
	}
	
	/**
	 * @Description: 开启线程
	 * @author guoyr
	 */
	public void start(){
		thread = new Thread(this);
		thread.start();
	}
	
	/**
	 * @Description: 停止线程
	 * @author guoyr
	 */
	public void stop(){
		thread = null;
	}
	
	public void run() {
		if (null != callBack) {
			analyFactorRespsonseXMl();
		}
	}
	
	/**
	 * @Description: 导入本地评审指标（招标文件或投标文件中的指标）
	 * @author guoyr
	 */
	private void analyLocalEvalFactor(List<SupplierEvaluationFactor> supplierEvaluationFactorList, Supplier supplier, Document factorDoc, List<EvaluationFactorItem> evaluationFactorItemList){
		callBack.callBackString("正在解析" + supplier.getSupplierName() + "评标响应，请稍后......");
//		boolean isImport = false;
		// 获得评审指标Document对象
		
		List<SupplierEvaluationFactor> factorList = null;
		final StringBuilder msg = new StringBuilder();
		try {
			factorList = ParsingSupplierResponseXmlUtils.parsingEvaluationFactorXML(factorDoc, tenderProjectEntity);
		} catch (Exception e) {
			LOG.error("解析评标响应指标文件失败", e);
			msg.append("解析【"  + supplier.getSupplierName() + "】评标响应指标文件失败！");
			callBack.callBackString("解析评标响应文件失败！");
		}
		if(null != factorList && factorList.size() > 0){
			for(SupplierEvaluationFactor supplierEvaluationFactor : factorList){
				supplierEvaluationFactor.setSupplierId(supplier.getId());
				List<EvaluationFactorItem> itemList = supplierEvaluationFactor.getEvaluationFactorItemList();
				for(EvaluationFactorItem item : itemList){
					item.setSupplierId(supplier.getId());
					item.setFactorCode(supplierEvaluationFactor.getFactorCode());
					item.setTenderId(supplierEvaluationFactor.getTenderId());
					evaluationFactorItemList.add(item);
				}
			}
			supplierEvaluationFactorList.addAll(factorList);
		}
		callBack.callBackString("解析" + supplier.getSupplierName() + "评标响应成功！共有" + factorList.size() + "个相应节点！");
	}
	
	/**
	 * @Description: 递归循环遍历子节点
	 * @author guoyr
	 * @param childElementList
	 * @param parentFactor
	 * @param factorType
	 * @return 
	 */
	@SuppressWarnings("unchecked")
	public List<EvaluationFactor> setChildList(List<Element> childElementList, EvaluationFactor parentFactor, String factorType){
		if(null == childElementList || childElementList.size() == 0){
			return null;
		}
		List<EvaluationFactor> factorList = new ArrayList<EvaluationFactor>();
		for(Element element : childElementList){
			EvaluationFactor evaluationFactor = resolverEvaluationFactorFromElement(UuidUtils.getUUID(), parentFactor, element, factorType);
			if(null != evaluationFactor){
				factorList.add(evaluationFactor);
				List<Element> childrenElementList = element.element("childFactorList").elements();
				List<EvaluationFactor> childFactorList = setChildList(childrenElementList, evaluationFactor, factorType);
				if(null != parentFactor && null != evaluationFactor){
					parentFactor.addChild(evaluationFactor); 
					evaluationFactor.setSortNo(parentFactor.getChildFactorList().size());
				}else{
					evaluationFactor.setSortNo(sorNo++);
				}
				if(null != childFactorList && childFactorList.size() > 0){
					factorList.addAll(childFactorList);
				}
				if(null != factorType && factorType.equals(EvaluationFactorEnum.AUDIT_COMPLIANCE)){
					// 符合性指标
				}else {
					// 打分指标和价格指标
					
					if(null != evaluationFactor.getChildFactorList() && evaluationFactor.getChildFactorList().size() > 0){
						if(null == evaluationFactor.getFactorScore() || evaluationFactor.getFactorScore().compareTo(BigDecimal.ZERO) == 0){
							BigDecimal totalScore = BigDecimal.ZERO;
							for(EvaluationFactor childEvaluationFactor : evaluationFactor.getChildFactorList()){
								totalScore = BigDecimalUtils.add(totalScore, childEvaluationFactor.getFactorScore());
							}
							evaluationFactor.setFactorScore(totalScore);
						}
					}
					if(null == evaluationFactor.getFactorMaxScore() || evaluationFactor.getFactorMaxScore().compareTo(BigDecimal.ZERO) == 0){
						evaluationFactor.setFactorMaxScore(evaluationFactor.getFactorScore());
					}
				}
				
			}
		}
		return factorList;
	}
	
	/**
	 * @Description: 解析xml保存指标信息
	 * @author guoyr
	 * @param id
	 * @param parentEvaluationFactor
	 * @param element
	 * @param factorType
	 * @return 
	 */
	private EvaluationFactor resolverEvaluationFactorFromElement(String id, EvaluationFactor parentEvaluationFactor, Element element, String factorType){
		EvaluationFactor evaluationFactor = new EvaluationFactor();
		evaluationFactor.setId(id);
		if(null != parentEvaluationFactor ){
			evaluationFactor.setParentId(parentEvaluationFactor.getId());			
		}
		evaluationFactor.setAuditType(factorType);
		evaluationFactor.setTenderId(tenderProjectEntity.getId());
		evaluationFactor.setFactorName(element.element("name").getTextTrim());
		String factorCode = element.element("code").getTextTrim();
		if (null != factorCode && factorCode.length() > 0) {
			evaluationFactor.setFactorCode(factorCode);
		} else {
			String sourceId = element.element("id").getTextTrim();
			if(null != sourceId && sourceId.length() > 0){
				evaluationFactor.setFactorCode(sourceId);
			}else {
				evaluationFactor.setFactorCode(id);
			}
		}
		
		if(null != factorType && factorType.equals(EvaluationFactorEnum.AUDIT_COMPLIANCE)){
			// 符合性指标
		}else {
			Element scoreElement = element.element("score");
			String scoreValue = "0";
			if(null != scoreElement){
				scoreValue = scoreElement.getTextTrim();
			}
			String evalBidType = element.elementTextTrim("evalBidType");
			evaluationFactor.setEvalBidType(evalBidType);
			evaluationFactor.setFactorScore(ObjectUtils.getObjBigDecimal(scoreValue));
			evaluationFactor.setFactorMinScore(ObjectUtils.getObjBigDecimal(element.elementTextTrim("minScore")));
			evaluationFactor.setFactorMaxScore(ObjectUtils.getObjBigDecimal(element.elementTextTrim("maxScore")));
			if(null == evaluationFactor.getFactorMinScore()){
				evaluationFactor.setFactorMinScore(BigDecimal.ZERO);
			}
			if(null == evaluationFactor.getFactorMaxScore()){
				evaluationFactor.setFactorMaxScore(evaluationFactor.getFactorScore());
			}
			if(null != element.elementTextTrim("weight")){
				evaluationFactor.setFactorMaxScore(ObjectUtils.getObjBigDecimal(element.elementTextTrim("weight")));
			}
		}
		evaluationFactor.setMemo(element.elementTextTrim(("memo")));
		return evaluationFactor;
	}
	/**
	 * @Description: 获得评审指标Document对象
	 * @author guoyr
	 * @return
	 */
	private void analyFactorRespsonseXMl(){
		// 获得招标文件的指标Document
		// 未找到招标文件的指标，则获得投标文件的指标。
		// 获得投标人集合
		supplierEvaluationFactorService.deleteByTenderId(tenderProjectEntity.getId());
		evaluationFactorItemService.deleteByTenderId( tenderProjectEntity.getId());
		List<Supplier> supplierList = supplierService.getSupplierOpenBidList(tenderProjectEntity.getId());
		List<SupplierEvaluationFactor> supplierEvaluationFactorList = new ArrayList<SupplierEvaluationFactor>();
		List<EvaluationFactorItem> evaluationFactorItemList = new ArrayList<EvaluationFactorItem>();
		if(null != supplierList && supplierList.size() > 0){
			// 遍历投标人信息
			for(Supplier supplier : supplierList){
				// 获得投标人投标文件下的指标路径
				String supplierFactorXmlPath = FileConstants.getBidFilePath(tenderProjectEntity.getId(), supplier.getId()) + FileConstants.PSZB_XML;
				// 获得投标文件的指标Document
				Document factorDoc = XmlUtils.getXmlDocument(supplierFactorXmlPath);
				if(null != factorDoc){
					analyLocalEvalFactor(supplierEvaluationFactorList, supplier, factorDoc, evaluationFactorItemList);
				}
			}
		}
		callBack.callBackString("正在批量保存解析结果，请稍后。。。");
		evaluationFactorItemService.batchSave(evaluationFactorItemList);
		int result = supplierEvaluationFactorService.batchSave(supplierEvaluationFactorList);
		if(result == supplierEvaluationFactorList.size() ){
			callBack.callBackString("批量保存解析结果成功！");
		}else{
			callBack.callBackString("批量保存解析结果失败！");
		}
		callBack.after();
	}

}
