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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.entity.ExpertEvaluationStep;
import com.gx.obe.business.enumeration.SupplierEnum;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.components.core.enumeration.ExpertEnum;
import com.gx.obe.evaluation.step.composite.business.BusinessEvalResultComposite;
import com.gx.obe.evaluation.step.dialog.ApplyReEvaluationDialog;
import com.gx.obe.evaluation.step.entity.BusinessEvalResult;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.LogUtils;
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.EvaluationStep;
import com.gx.obe.web.entity.expert.Expert;
import com.gx.obe.web.entity.expert.ExpertEvaluationResult;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.SupplierOpeningResultService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.evaluation.EvaluationFactorResultService;
import com.gx.obe.web.service.expert.ExpertEvaluationResultService;
import com.gx.obe.web.service.expert.ExpertEvaluationStepService;
import com.gx.obe.web.service.expert.ExpertService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 商务评审结果界面
 * @author chenxw
 */
public class BusinessEvaluationResultComposite extends Composite {
	
	private final SupplierService supplierService = new SupplierService();
	private final ExpertService expertService = new ExpertService();
	private final ExpertEvaluationStepService expertEvaluationStepService = new ExpertEvaluationStepService();
	private final SupplierOpeningResultService supplierOpeningResultService = new SupplierOpeningResultService();
	private final EvaluationFactorResultService evaluationFactorResultService = new EvaluationFactorResultService();
	private final ExpertEvaluationResultService expertEvaluationResultService = new ExpertEvaluationResultService();
	
	private Label messageLabel;
	private ELink applyReEvaluation_link;
	private BusinessEvalResultComposite businessEvalResultComposite;
	
	private TenderProjectEntity tenderProject;
	private EvaluationStep evaluationStep;
	private TenderProjectRuleEntity projectRule;
	
	private List<Supplier> supplierList;
	
	{
		LogUtils.logClass(BusinessEvaluationResultComposite.class);
	}
	
	/**
	 * @author chenxw
	 * @param parent
	 * @param style
	 */
	public BusinessEvaluationResultComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.marginHeight = 1;
		gridLayout.marginWidth = 1;
		setLayout(gridLayout);
		
		Composite composite_1 = new Composite(this, SWT.NONE);
		GridLayout gl_composite_1 = new GridLayout(2, false);
		composite_1.setLayout(gl_composite_1);
		composite_1.setBackgroundMode(SWT.INHERIT_FORCE);
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		messageLabel = new Label(composite_1, SWT.WRAP);
		messageLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		messageLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		messageLabel.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		
		applyReEvaluation_link = new ELink(composite_1, SWT.NONE);
		applyReEvaluation_link.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				applyReEvaluationAction();
			}
		});
		applyReEvaluation_link.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		applyReEvaluation_link.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/hand.png"));
		
		Composite composite = new Composite(this, SWT.NONE);
		composite.setBackground(ColorConstants.BORDER_LINE_COLOR);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.marginHeight = 1;
		gl_composite.marginWidth = 1;
		composite.setLayout(gl_composite);
		
		businessEvalResultComposite = new BusinessEvalResultComposite(composite, SWT.NONE);
		businessEvalResultComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
	}
	
	/**
	 * @Description: 刷新
	 * @author chenxw
	 * @param tenderProject
	 * @param evaluationStep
	 * @param projectRule
	 */
	public void refresh(TenderProjectEntity tenderProject, EvaluationStep evaluationStep, TenderProjectRuleEntity projectRule) {
		this.tenderProject = tenderProject;
		this.evaluationStep = evaluationStep;
		this.projectRule = projectRule;
		refreshForm();
		refreshSupplierList();
		refreshTableComposite();
	}
	
	/**
	 * @Description: 刷新表单
	 * @author chenxw
	 */
	private void refreshForm() {
		StringBuilder msg = new StringBuilder();
		String stepStatus = evaluationStep.getStepStatus();
		String stepName = evaluationStep.getStepName();
		boolean visible = false;
		if (CommonEnum.COMPLETE.equals(stepStatus)) {
			msg.append("已完成[").append(stepName).append("]！");
			if (isThisStepOperator()) visible = true;
		} else if (CommonEnum.IN_PROGRESS.equals(stepStatus)) {
			msg.append("[").append(stepName).append("]进行中...   ");
		} else {
			msg.append("未开始[").append(stepName).append("]！");
		}
		messageLabel.setText(msg.toString());
		applyReEvaluation_link.setVisible(visible);
		applyReEvaluation_link.setText("申请退回[" + stepName + "]");
		applyReEvaluation_link.getParent().layout();
	}
	
	/**
	 * @Description: 当前步骤操作者
	 * @author chenxw
	 * @return
	 */
	private boolean isThisStepOperator() {
		String roleType = evaluationStep.getRoleType();
		if (com.gx.obe.components.core.enumeration.EvaluationStepEnum.EXPERT_LEADER.equals(roleType)) {
			Expert expertLeader = expertService.getExpertLeader(tenderProject.getId());
			if (Constants.USER.getId().equals(expertLeader.getUserId())) {
				return true;
			}
		} else if (com.gx.obe.components.core.enumeration.EvaluationStepEnum.OPERATOR.equals(roleType)) {
			if (Constants.USER.getId().equals(tenderProject.getUserId())) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * @Description: 刷新供应商列表
	 * @author chenxw
	 */
	private void refreshSupplierList() {
		List<SupplierOpeningResult> resultList = supplierOpeningResultService.getSupplierOpeningResultListByTenderIdAndBidOpeningStatus(tenderProject.getId(), SupplierEnum.OPENBID_SUCCESS);
		Map<String, SupplierOpeningResult> resultMap = CollectionUtils.toHashMap(resultList, SupplierOpeningResult::getSupplierId);
		supplierList = supplierService.getEvaluationStepSupplierList(tenderProject.getId(), evaluationStep);
		if (null == supplierList) {
			supplierList = new ArrayList<Supplier>();
		}
		for (Supplier supplier : supplierList) {
			SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
			if (null == supplierOpeningResult) {
				supplier.setSupplierOpeningResult(resultMap.get(supplier.getId()));
			}
		}
	}
	
	/**
	 * @Description: 刷新表格界面
	 * @author chenxw
	 */
	private void refreshTableComposite() {
		List<EvaluationFactorResult> factorResultList = evaluationFactorResultService.getExpertEvaluationFactorResult(tenderProject.getId(), evaluationStep.getId(), ExpertEnum.COMMON_EXPERT, null);
		List<ExpertEvaluationResult> evaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProject.getId(), evaluationStep.getId(), ExpertEnum.COMMON_EXPERT);
		
		BigDecimal basePrice = null;
		if (CollectionUtils.isNotNull(factorResultList)) for (EvaluationFactorResult evaluationFactorResult : factorResultList) {
			basePrice = evaluationFactorResult.getBasePrice();
			if (null != basePrice) {
				break;
			}
		}
		
		List<BusinessEvalResult> businessEvalResultList = new ArrayList<BusinessEvalResult>();
		
		Map<String, EvaluationFactorResult> factorResultMap = CollectionUtils.toHashMap(factorResultList, new CollectionUtils.NewMap<String, EvaluationFactorResult>() {
			public String getKey(EvaluationFactorResult t) {
				return t.getSupplierId();
			}
		});
		Map<String, ExpertEvaluationResult> evalResultMap = CollectionUtils.toHashMap(evaluationResultList, new CollectionUtils.NewMap<String, ExpertEvaluationResult>() {
			public String getKey(ExpertEvaluationResult t) {
				return t.getSupplierId();
			}
		});
		for (Supplier supplier : supplierList) {
			businessEvalResultList.add(getBusinessEvalResult(supplier, factorResultMap, evalResultMap));
		}
		
		Collections.sort(businessEvalResultList, new Comparator<BusinessEvalResult>() {
			public int compare(BusinessEvalResult evalResult1, BusinessEvalResult evalResult2) {
				if (evalResult1.getSortNo() > evalResult2.getSortNo()) {
					return 1;
				}
				if (evalResult1.getSortNo() < evalResult2.getSortNo()) {
					return -1;
				}
				return 0;
			}
		});
		
		businessEvalResultComposite.refresh(tenderProject, projectRule, basePrice, businessEvalResultList);
	}
	
	/**
	 * @Description: 获取得分结果
	 * @author chenxw
	 * @param supplier
	 * @param resultMap
	 * @param evalResultMap
	 * @param scoreCalculator
	 * @return
	 */
	private BusinessEvalResult getBusinessEvalResult(Supplier supplier, Map<String, EvaluationFactorResult> factorResultMap, Map<String, ExpertEvaluationResult> evalResultMap) {
		BusinessEvalResult businessEvalResult = new BusinessEvalResult();
		businessEvalResult.setSupplierName(supplier.getSupplierName());
		BigDecimal bidPrice = null;
		BigDecimal evaluationPrice = null;
		SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
		if (null != supplierOpeningResult) {
			bidPrice = supplierOpeningResult.getBidPrice();
			evaluationPrice = supplierOpeningResult.getEvaluationPrice();
		}
		businessEvalResult.setBidPrice(bidPrice);
		businessEvalResult.setEvaluationPrice(evaluationPrice);
		BigDecimal deviationRate = null;
		BigDecimal evaluationScore = null;
		if (null != factorResultMap) {
			EvaluationFactorResult result = factorResultMap.get(supplier.getId());
			if (null != result) {
				deviationRate = result.getDeviationRate();
				evaluationScore = result.getEvaluationScore();
			}
		}
		businessEvalResult.setDeviationRate(deviationRate);
		businessEvalResult.setScore(evaluationScore);
		int sortNo = Integer.MAX_VALUE;
		if (null != evalResultMap) {
			ExpertEvaluationResult evaluationResult = evalResultMap.get(supplier.getId());
			if (null != evaluationResult) {
				sortNo = evaluationResult.getSortNo();
			}
		}
		businessEvalResult.setSortNo(sortNo);
		return businessEvalResult;
	}
	
	/**
	 * @Description: 申请回退评审步骤事件
	 * @author chenxw
	 */
	private void applyReEvaluationAction() {
		if (!applyReEvaluation_link.getEnabled()) {
			return;
		}
		ExpertEvaluationStep step = expertEvaluationStepService.getExpertEvaluationStep(tenderProject.getId(), evaluationStep.getId(), ExpertEnum.COMMON_EXPERT);
		if (null == step) {
			return;
		}
		new ApplyReEvaluationDialog(getShell(), evaluationStep, step).open();
	}
	
	protected void checkSubclass() {}
	
}
