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

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.gx.obe.business.vo.PriceEvaluationFactor;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.evaluation.step.inter.IPriceShowTable;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.NumberFormatUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.EvaluationFactorResult;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
import com.gx.obe.web.entity.evaluation.EvaluationFactor;
import com.gx.obe.web.entity.evaluation.EvaluationStep;
import com.gx.obe.web.entity.expert.Expert;
import com.gx.obe.web.entity.expert.ExpertEvaluationResult;
import com.gx.obe.web.entity.price.BidPrice;
import com.gx.obe.web.entity.price.BidPriceResult;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.BidPriceResultService;
import com.gx.obe.web.service.BidPriceService;
import com.gx.obe.web.service.evaluation.EvaluationFactorResultService;
import com.gx.obe.web.service.evaluation.EvaluationFactorService;
import com.gx.obe.web.service.expert.ExpertEvaluationResultService;
import com.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.model.CommonKtableCModel;
import de.kupzog.ktable.renderers.CellAlignmentRender;
import de.kupzog.ktable.renderers.CellContentRender;

public class ShowPriceResultWithOutPriceComposite extends Composite implements IPriceShowTable{

	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private Expert CURRENT_EXPERT;
	private EvaluationFactorService evaluationFactorService = new EvaluationFactorService();
	private EvaluationFactorResultService evaluationFactorResultService = new EvaluationFactorResultService();
	private ExpertEvaluationResultService expertEvaluationResultService;
	private BidPriceService bidPriceService ;
	private BidPriceResultService bidPriceResultService ;
	private Composite composite;
	private List<EvaluationFactor> evaluationFactorList = new ArrayList<EvaluationFactor>();
	private List<PriceEvaluationFactor> priceEvaluationFactorList;//价格得分评审项列表
	private List<Supplier> supplierList;//供应商列表
	private KTable priceEvaluactionResult;//价格评审结果展示表格
	private CommonKtableCModel commKTableModel;
	private String supplierName;
	private Map<String, BidPriceResult> supplierBidPriceResultMap;//供应商价格评审结果数据集
	private Map<String, Map<String, EvaluationFactorResult>> supplierEvaluationFactorResultMap;//供应商价格评审项评审结果数据集
	private Map<String, ExpertEvaluationResult> expertEvaluationResultMap;// 记录专家对供应商的评审汇总结果
	private boolean hasBidPriceTotal = false;
	private int scoreRound = 2;//评审结果有效小数点位数
	private boolean hasFactorWeight = false;

	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public ShowPriceResultWithOutPriceComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		
		composite = new Composite(this, SWT.NONE);
		composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		composite.setLayout(new FillLayout(SWT.HORIZONTAL));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		expertEvaluationResultService = new ExpertEvaluationResultService();
	}

	@Override
	protected void checkSubclass() {
	}
	/**
	 * @Description: 表格数据加载
	 * @author guoyr
	 */
	public void refreshTable(TenderProjectEntity tenderProjectEntity, TenderProjectRuleEntity tenderProjectRuleEntity, EvaluationStep evaluationStep, Expert curExpert, List<Supplier> supplierList, List<EvaluationFactor> evaluationFactorList, boolean hasFactorWeight){
		this.tenderProjectEntity = tenderProjectEntity;
		this.tenderProjectRuleEntity = tenderProjectRuleEntity;
		this.evaluationStep = evaluationStep;
		this.CURRENT_EXPERT = curExpert;
		this.supplierList = supplierList;
		supplierName = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType());
		scoreRound = tenderProjectRuleEntity.getScoreRoundIntVal();
		hasBidPriceTotal = evaluationFactorService.hasTotalBidPriceFactor(tenderProjectEntity.getId(), null);//是否含有总报价
		this.evaluationFactorList = evaluationFactorList;
		this.hasFactorWeight = hasFactorWeight;
		drawTable();
	}
	/**
	 * @Description: 初始化价格评审各项指标评审结果
	 * @author guoyr 
	 */
	private void initEvaluationResult(){
		if(null == bidPriceResultService){
			bidPriceResultService = new BidPriceResultService();
		}
		if(null == evaluationFactorList)evaluationFactorList = new ArrayList<EvaluationFactor>();
		
		priceEvaluationFactorList = new ArrayList<PriceEvaluationFactor>();
		// 供应商每个指标的评审结果集合
		supplierEvaluationFactorResultMap = new HashMap<String, Map<String, EvaluationFactorResult>>();
		
		// 专家对供应商的评审汇总结果集合
		expertEvaluationResultMap = new HashMap<String, ExpertEvaluationResult>();
		
		// 评审当前评标专家所有的评标结果
		
		List<EvaluationFactorResult> expertEvaluateFactorResultList = evaluationFactorResultService.getExpertEvaluationFactorResult(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId(), null);
		
		List<ExpertEvaluationResult> queryExpertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
		
		for(Supplier supplier : supplierList){
			ExpertEvaluationResult expertEvaluationResult = null;
			if(null != queryExpertEvaluationResultList && queryExpertEvaluationResultList.size() > 0){
				for(ExpertEvaluationResult queryExpertEvaluationResult : queryExpertEvaluationResultList){
					if(ObjectUtils.equals(queryExpertEvaluationResult.getSupplierId(), supplier.getId())){
						expertEvaluationResult = queryExpertEvaluationResult;
					}
				}
			}
			Map<String, EvaluationFactorResult> evaluationFactorResultMap = new HashMap<String, EvaluationFactorResult>();
			for(EvaluationFactor evaluationFactor : evaluationFactorList){
				EvaluationFactorResult evaluationFactorResult = null;
				if(null != expertEvaluateFactorResultList && expertEvaluateFactorResultList.size() > 0){
					for(EvaluationFactorResult factorResult : expertEvaluateFactorResultList){
						if(ObjectUtils.equals(supplier.getId(), factorResult.getSupplierId()) && ObjectUtils.equals(evaluationFactor.getId(), factorResult.getFactorId())){
							evaluationFactorResult = factorResult;
							break;
						}
					}
				}
				evaluationFactorResultMap.put(evaluationFactor.getId(), evaluationFactorResult);
			}
			expertEvaluationResultMap.put(supplier.getId(), expertEvaluationResult);
			supplierEvaluationFactorResultMap.put(supplier.getId(), evaluationFactorResultMap);
		}
		//获取报价分项列表
		List<BidPrice> bidPriceList = null;
		if(!hasBidPriceTotal){
			if(null == bidPriceService){
				bidPriceService = new BidPriceService();
			}
			bidPriceList = bidPriceService.getTenderBidPriceList(tenderProjectEntity.getId());
		}
		
		supplierBidPriceResultMap = new HashMap<String, BidPriceResult>();
		for(EvaluationFactor evaluationFactor : evaluationFactorList){
			BidPrice factorBidPrice = null;
			PriceEvaluationFactor priceEvaluationFactorFinalScore = new PriceEvaluationFactor(evaluationFactor);
			if(null != bidPriceList && bidPriceList.size() > 0){
				for(BidPrice bidPrice : bidPriceList){
					if(null != evaluationFactor.getBidPriceCode() && evaluationFactor.getBidPriceCode().equals(bidPrice.getBidPriceCode()) ){//&& null != evaluationFactor.getComputerParams()){
						factorBidPrice = bidPrice;
						break;
					}
				}
			}
			if(null != factorBidPrice){
				List<BidPriceResult> bidPriceResultList = bidPriceResultService.getBidPriceResultList(tenderProjectEntity.getId(), factorBidPrice.getId());
				List<BigDecimal> evalPriceList = new ArrayList<BigDecimal>();
				if(null != bidPriceResultList && bidPriceResultList.size() > 0){
					for(Supplier supplier : supplierList){
						for(BidPriceResult bidPriceResult : bidPriceResultList){
							if(null != bidPriceResult.getSupplierId() && supplier.getId().equals(bidPriceResult.getSupplierId())){
								supplierBidPriceResultMap.put(bidPriceResult.getSupplierId()+"_"+bidPriceResult.getBidPriceId(), bidPriceResult);
								if(null != bidPriceResult.getEvaluationPrice()){
									evalPriceList.add(bidPriceResult.getEvaluationPrice());
								}
							}
						}
					}
				}
				priceEvaluationFactorList.add(priceEvaluationFactorFinalScore);
				if(null != evaluationFactor.getFactorWeight()){
					// 添加价格得分列
					priceEvaluationFactorList.add(priceEvaluationFactorFinalScore.clone(PriceEvaluationFactor.PRICE_FINAL_SCORE));
				}
			}else if(null != evaluationFactor.getBidPriceCode() && evaluationFactor.getBidPriceCode().equals(BidPrice.BID_PRICE_TOTAL_CODE)){
				if(null != evaluationFactor.getComputerParams()){
					List<BigDecimal> evalPriceList = new ArrayList<BigDecimal>();
					for(Supplier supplier : supplierList){
						SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
						if(null != supplierOpeningResult && null != supplierOpeningResult.getEvaluationPrice()){
							evalPriceList.add(supplierOpeningResult.getEvaluationPrice());
						}
					}
				}
				priceEvaluationFactorList.add(priceEvaluationFactorFinalScore);
				if(null != evaluationFactor.getFactorWeight()){
					// 添加价格得分列
					priceEvaluationFactorList.add(priceEvaluationFactorFinalScore.clone(PriceEvaluationFactor.PRICE_FINAL_SCORE));
				}
			}else {
				priceEvaluationFactorList.add(priceEvaluationFactorFinalScore);
				if(null != evaluationFactor.getFactorWeight()){
					// 添加价格得分列
					priceEvaluationFactorList.add(priceEvaluationFactorFinalScore.clone(PriceEvaluationFactor.PRICE_FINAL_SCORE));
				}
			}
		}
	}
	
	/**
	 * @Description:绘制价格评审结果表格
	 * @author guoyr 
	 */
	private void drawTable(){
		initEvaluationResult();
		if(null != priceEvaluactionResult && !priceEvaluactionResult.isDisposed()){
			priceEvaluactionResult.dispose();
		}
		priceEvaluactionResult = new KTable(composite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.FILL_WITH_LASTCOL | SWTX.EDIT_ON_KEY);
		
		boolean hasFinalSumScore = false;// 标记是否存在最终得分
		boolean hasSumScore = false;// 标记是否存在得分汇总
		if(evaluationFactorList.size() > 1){
			hasFinalSumScore = true;
			commKTableModel = new CommonKtableCModel(priceEvaluactionResult, 2, 1, supplierList.size() , priceEvaluationFactorList.size() +(hasFactorWeight ? 3 : 2));//合理性得分，总分，最终得分。排名
			if(hasFactorWeight){
				hasSumScore = true;
			}
		}else {
			commKTableModel = new CommonKtableCModel(priceEvaluactionResult, 1, 1, supplierList.size() , priceEvaluationFactorList.size() + 1);
		}
		commKTableModel.addRowSpan(0, 0, commKTableModel.getFixedRowCount());
		
		commKTableModel.setColumnMinWidth(0, 100);
		commKTableModel.setRowHeight(0, 40);
		
		final Map<String, String> tableTitleMap = new HashMap<String, String>();
		
		// 排名列
		final int sortCol = commKTableModel.getColCount() -1;
		commKTableModel.addRowSpan(0, sortCol, commKTableModel.getFixedRowCount());
		commKTableModel.setColumnWidth(sortCol, 40);
		commKTableModel.setColumnMaxWidth(sortCol, 80);
		tableTitleMap.put("0_"+ sortCol, Messages.SortNo);
		// 最终得分列
		final int finalScoreSumCol= hasFinalSumScore?commKTableModel.getColCount() -2:-1;
		if(finalScoreSumCol > 0){
			commKTableModel.setColumnWidth(finalScoreSumCol, 40);
			commKTableModel.setColumnMaxWidth(finalScoreSumCol, 80);
			commKTableModel.addRowSpan(0, finalScoreSumCol, commKTableModel.getFixedRowCount());
			if(hasFactorWeight){
				tableTitleMap.put("0_"+ finalScoreSumCol, Messages.FinalScore);
			}else {
				tableTitleMap.put("0_"+ finalScoreSumCol, Messages.TotalScore);
			}
		}
		// 得分汇总列
		int index = 3;
		final int scoreSumCol = hasSumScore?commKTableModel.getColCount() -3 : -1;
		if(scoreSumCol > 0){
			index ++;
			commKTableModel.addRowSpan(0, scoreSumCol, commKTableModel.getFixedRowCount());
			commKTableModel.setColumnWidth(scoreSumCol, 40);
			commKTableModel.setColumnMaxWidth(scoreSumCol, 80);
			tableTitleMap.put("0_"+ scoreSumCol, Messages.TotalScore);
		}
		
		tableTitleMap.put("0_0", MessageFormat.format(Messages.Supplier, Messages.Name));
		commKTableModel.addRowSpan(0, 0, commKTableModel.getFixedRowCount());
		commKTableModel.setColumnWidth(0, 200);
		commKTableModel.setColumnMaxWidth(0, 280);
		int col = commKTableModel.getFixedColumnCount();
		int margerColCount = 0;
		String preFactorId = null;
		
		for(PriceEvaluationFactor priceEvaluationFactor : priceEvaluationFactorList){
			EvaluationFactor evaluationFactor = priceEvaluationFactor.getEvaluationFactor();
			if(commKTableModel.getFixedRowCount() > 1){
				if(null == preFactorId){
					preFactorId = evaluationFactor.getId();
				}
				tableTitleMap.put("0_"+col, evaluationFactor.getFactorName() + "(" + evaluationFactor.getFactorScore() + "分)" );
				if(null != preFactorId && !evaluationFactor.getId().equals(preFactorId)){
					commKTableModel.addColSpan(0, col - margerColCount, margerColCount);
					margerColCount = 0;
					preFactorId = evaluationFactor.getId();
				}
				margerColCount ++;
			}
			if(priceEvaluationFactor.getFactorType() == PriceEvaluationFactor.PRICE_SCORE){
				tableTitleMap.put((commKTableModel.getFixedRowCount() -1)+"_"+col, Messages.PriceScore);
			}
			else if(priceEvaluationFactor.getFactorType() == PriceEvaluationFactor.PRICE_FINAL_SCORE){
				if(null != evaluationFactor.getFactorFinalWeight()){
					tableTitleMap.put((commKTableModel.getFixedRowCount() -1)+"_"+col, Messages.WeightScore +"\r\n(" + NumberFormat.getInstance().format(evaluationFactor.getFactorFinalWeight())+"%)");
				}else {
					tableTitleMap.put((commKTableModel.getFixedRowCount() -1)+"_"+col, Messages.PriceScore);
					// 如果存在多个指标（多表头），且当前指标是分值录入的指标，且没有权重，则合并行
					if(margerColCount == 1 && commKTableModel.getFixedRowCount() > 1){
						commKTableModel.addRowSpan(0, col, commKTableModel.getFixedRowCount());
					}
				}
			}
			commKTableModel.setColumnWidth(col, 80);
			col ++;
		}
		if(margerColCount > 0){
			commKTableModel.addColSpan(0, col - margerColCount, margerColCount);
		}
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender(){
			public Object receiveContent(int row, int col) {
				if (row < commKTableModel.getHeadRow()) {
					if (null != tableTitleMap.get(row + "_" + col)) {
						return tableTitleMap.get(row + "_" + col);
					} else {
						return "";
					}
				} else {
					Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
					if (col < commKTableModel.getFixedColumnCount()) {
						return supplier.getSupplierName();
					} else if (col < commKTableModel.getFixedColumnCount() + priceEvaluationFactorList.size()) {

						PriceEvaluationFactor priceEvaluationFactor = priceEvaluationFactorList.get(col - commKTableModel.getFixedColumnCount());
						EvaluationFactor evaluationFactor = priceEvaluationFactor.getEvaluationFactor();
						if (priceEvaluationFactor.getFactorType() == PriceEvaluationFactor.BID_EVAL_PRICE_TOTAL) {
							SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
							if (null != supplierOpeningResult && null != supplierOpeningResult.getEvaluationPrice()) {
								return supplierOpeningResult.getFormatEvaluatoinPriceByUnit(tenderProjectRuleEntity.getEvalPriceUnit());
							}
						} else {
							EvaluationFactorResult evalFactorResult = supplierEvaluationFactorResultMap.get(supplier.getId()).get(evaluationFactor.getId());
							if(null != evalFactorResult){
								
								if (priceEvaluationFactor.getFactorType() == PriceEvaluationFactor.PRICE_SCORE) {
									if (null != evalFactorResult.getEvaluationScore()) {
										return NumberFormatUtils.format(evalFactorResult.getEvaluationScore(), scoreRound);
									}
								} else if (priceEvaluationFactor.getFactorType() == PriceEvaluationFactor.PRICE_FINAL_SCORE) {
									if (null != evalFactorResult.getEvaluationFinalScore()) {
										return NumberFormatUtils.format(evalFactorResult.getEvaluationFinalScore(), scoreRound);
									}
								}
							}
						}
					} else {
						// 供应商的汇总
						ExpertEvaluationResult expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
						if (null != expertEvaluationResult) {
							if (col == scoreSumCol) {
								if (null != expertEvaluationResult.getEvaluationScore()) {
									return NumberFormatUtils.format(expertEvaluationResult.getEvaluationScore(),scoreRound);
								}
							} else if (col == finalScoreSumCol) {
								if (null != expertEvaluationResult.getEvaluationFinalScore()) {
									return NumberFormatUtils.format(expertEvaluationResult.getEvaluationFinalScore(), scoreRound);
								}
							} else if (col == sortCol) {
								if (expertEvaluationResult.getSortNoIntValue() > 0) {
									return expertEvaluationResult.getSortNoIntValue();
								}
							}
						}
					}
				}
				return "";
		}};
		commKTableModel.setCellContentRender(contentRender);
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender(){
			public int receiveCellAlignment(int row, int col) {
				if(row < commKTableModel.getFixedRowCount()){
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				}else {
					if(col < commKTableModel.getFixedColumnCount()){
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					}else if(col < commKTableModel.getFixedColumnCount() + priceEvaluationFactorList.size()){
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
					}
				}
				return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
		priceEvaluactionResult.setModel(commKTableModel);
	}
}
