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

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
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 org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import com.gx.obe.action.bean.Action;
import com.gx.obe.business.enumeration.SupplierEnum;
import com.gx.obe.common.widget.button.EvalLeftButton;
import com.gx.obe.common.widget.button.EvaluationButton;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.components.core.enumeration.EvaluationStepEnum;
import com.gx.obe.evaluation.step.composite.RecommonedEvaluationTableComposite;
import com.gx.obe.evaluation.step.composite.RecommonedRankEvaluationTableComposite;
import com.gx.obe.evaluation.step.inter.IRecommonedTable;
import com.gx.obe.evaluation.step.listener.ExpertEvaluationListener;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierEvaluationResult;
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.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.SupplierEvaluationResultService;
import com.gx.obe.web.service.SupplierOpeningResultService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.evaluation.EvaluationStepService;
import com.gx.obe.web.service.expert.ExpertEvaluationStepService;
import com.gx.obe.web.service.expert.ExpertService;
import com.gx.utils.ActionLogUtils;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 推荐中标候选人
 * @author guoyr
 */
public class RecommonedEvaluationComposite extends Composite {

	private Composite left_tool_composite;
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private EvaluationButton submit_result_btn;
	private Expert CURRENT_EXPERT;
	private ExpertService expertService;
	private ProjectRuleService projectRuleService;
	private SupplierService supplierService = new SupplierService();
	private SupplierEvaluationResultService supplierEvaluationResultService;
	private SupplierOpeningResultService supplierOpeningResultService ;
	private EvaluationStepService evaluationStepService = new EvaluationStepService();
	private ExpertEvaluationStepService expertEvaluationStepService ;
	private ExpertEvaluationListener expertEvaluationListener;
	private ScrolledComposite scrolledComposite;
	private Composite evaluation_table_composite;
	private List<Supplier> supplierList;
	private IRecommonedTable evaluationTable = null;
	private Composite right_composite;
	private Object hideLeft;
	private EvaluationStep noComplateFilterStep = null;
	{
		LogUtils.logClass(RecommonedEvaluationComposite.class);
	}
	
	/**
	 * @param parent
	 * @param style
	 */
	public RecommonedEvaluationComposite(Composite parent,Action action, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(4, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		this.tenderProjectEntity = action.getTenderProject();
		this.evaluationStep = (EvaluationStep)parent.getData("evaluationStep");
		hideLeft = parent.getData("hideLeft");
		left_tool_composite = new Composite(this, SWT.NONE);
		left_tool_composite.setBackground(EvalLeftButton.BG);
		left_tool_composite.setBackgroundMode(SWT.INHERIT_FORCE);
		left_tool_composite.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 1, 1));
		GridLayout gl_left_tool_composite = new GridLayout(1, false);
		left_tool_composite.setLayout(gl_left_tool_composite);
		
		EvalLeftButton goto_back = new EvalLeftButton(left_tool_composite, SWT.NONE);
		goto_back.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		goto_back.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/back.png"));
		goto_back.setToolTipText(Messages.Button_return);
		goto_back.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				goBackAction();
			}
		});
		
		EvalLeftButton refresh_evaluation = new EvalLeftButton(left_tool_composite, SWT.NONE);
		refresh_evaluation.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/refresh.png"));
		refresh_evaluation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		refresh_evaluation.setToolTipText(Messages.Button_refresh);
		refresh_evaluation.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				refreshTenderInfo();
			}
		});
		
		right_composite = new Composite(this, SWT.NONE);
		GridLayout gl_right_composite = new GridLayout(1, false);
		gl_right_composite.verticalSpacing = 0;
		gl_right_composite.horizontalSpacing = 0;
		gl_right_composite.marginHeight = 0;
		gl_right_composite.marginWidth = 0;
		right_composite.setLayout(gl_right_composite);
		right_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		scrolledComposite = new ScrolledComposite(right_composite, SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		
		evaluation_table_composite = new Composite(scrolledComposite, SWT.NONE);
		evaluation_table_composite.setLayout(new FillLayout(SWT.HORIZONTAL));
		evaluation_table_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		evaluation_table_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		
		scrolledComposite.setContent(evaluation_table_composite);
		scrolledComposite.setMinSize(evaluation_table_composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		
		Composite composite_5 = new Composite(right_composite, SWT.NONE);
		composite_5.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		composite_5.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1));
		composite_5.setLayout(new GridLayout(1, false));
		
		submit_result_btn = new EvaluationButton(composite_5, SWT.NONE);
		GridData gd_signBtn = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
		submit_result_btn.setLayoutData(gd_signBtn);
		submit_result_btn.setText(Messages.Button_submitEvaluationResult);
		submit_result_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				submitEvaluationResultAction();
			}
		});
		
		init();
	}

	/**
	 * @Description: 初始化界面数据
	 * @author guoyr
	 */
	private void init(){
		expertEvaluationStepService = new ExpertEvaluationStepService();
		supplierEvaluationResultService = new SupplierEvaluationResultService();
		supplierOpeningResultService = new SupplierOpeningResultService();
		expertService = new ExpertService();
		projectRuleService = new ProjectRuleService();
		if(null != hideLeft){
			left_tool_composite.dispose();
		}
		
		CURRENT_EXPERT = expertService.getEvaluationStepExpert(tenderProjectEntity.getId(), evaluationStep);
		
		// 修改状态为正在进行中
		ActionLogUtils.addServerLog(tenderProjectEntity.getId(), "进入" + evaluationStep.getStepName(), Constants.USER.getUserName());
//		expertEvaluationStepService.updateExpertEvaluationStatus(CommonEnum.IN_PROGRESS, tenderProjectEntity.getId(), evaluationStep, CURRENT_EXPERT.getUserId());
		refreshTenderInfo();
		scrolledComposite.getVerticalBar().setIncrement(20);
		scrolledComposite.forceFocus();
		scrolledComposite.addListener(SWT.Activate, new Listener() {
	        public void handleEvent(Event e) {
	            scrolledComposite.setFocus();
	        }
	    });
	}
	
	/**
	 * @Description: 返回
	 * @author guoyr 
	 */
	private void goBackAction(){
		if(null != expertEvaluationListener){
			expertEvaluationListener.complete();
		}
	}
	/**
	 * @Description: 刷新项目信息
	 * @author guoyr
	 */
	private void refreshTenderInfo(){
		tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
		if(null == tenderProjectRuleEntity)tenderProjectRuleEntity = new TenderProjectRuleEntity();
		getNoComplateFilterStep();
		// 获取投标人评标结果
		supplierList = getSupplierList();
		if(null == supplierList || supplierList.size() == 0){
			submit_result_btn.setEnabled(false);
		}else {
			submit_result_btn.setEnabled(true);
		}
		showRecommonedTable();
	}
	
	/**
	 * @Description: 显示推荐评审
	 * @author guoyr
	 */
	private void showRecommonedTable(){
		for(Control control : evaluation_table_composite.getChildren()){
			control.dispose();
		}
		List<EvaluationStep> recommonedRankList = evaluationStepService.getEvaluationStepListByType(tenderProjectEntity.getId(), EvaluationStepEnum.RECOMMONED_RANK);
		if (null != recommonedRankList && recommonedRankList.size() > 0) {
			evaluationTable = new RecommonedRankEvaluationTableComposite(evaluation_table_composite, SWT.NONE, recommonedRankList.get(0));
		} else {
			evaluationTable = new RecommonedEvaluationTableComposite(evaluation_table_composite, SWT.NONE);
		}
		evaluationTable.refresh(tenderProjectEntity, tenderProjectRuleEntity, evaluationStep, CURRENT_EXPERT.getUser(), supplierList);
		evaluation_table_composite.layout();
		scrolledComposite.setMinSize(evaluation_table_composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
	}

	/**
	 * @Description: 刷新投标人的价格分
	 * @author guoyr
	 * @return
	 */
	private List<Supplier> getSupplierList(){
		
		List<Supplier> supplierList = supplierService.getEvaluationStepSupplierList(tenderProjectEntity.getId(), evaluationStep);
		if(null != supplierList && supplierList.size() > 0){
			// 则获取开标成功的投标人
			List<SupplierOpeningResult> supplierOpeningResultList = supplierOpeningResultService.getSupplierOpeningResultListByTenderIdAndBidOpeningStatus(tenderProjectEntity.getId(), SupplierEnum.OPENBID_SUCCESS);
			
			// 获取投标人评标结果
			
			List<SupplierEvaluationResult> supplierEvaluationResultList = supplierEvaluationResultService.getSupplierEvaluationResultListByTenderId(tenderProjectEntity.getId());
		
			for(Supplier supplier : supplierList){
				SupplierOpeningResult supplierOpeningResult = null;
				if(null != supplierOpeningResultList && supplierOpeningResultList.size() > 0){
					for(SupplierOpeningResult result : supplierOpeningResultList){
						if(ObjectUtils.equals(result.getSupplierId(), supplier.getId())){
							if(null == result.getEvaluationPrice()){
								result.setEvaluationPrice(result.getBidPrice());
							}
							supplierOpeningResult = result;
							break;
						}
					}
				}
				if(null == supplierOpeningResult){
					supplierOpeningResult = new SupplierOpeningResult();
					supplierOpeningResult.setTenderId(tenderProjectEntity.getId());
					supplierOpeningResult.setSupplierId(supplier.getId());
				}
				supplier.setSupplierOpeningResult(supplierOpeningResult);
				
				SupplierEvaluationResult supplierEvaluationResult = null;
				if(null != supplierEvaluationResultList && supplierEvaluationResultList.size() > 0){
					for(SupplierEvaluationResult evalResult : supplierEvaluationResultList){
						if(ObjectUtils.equals(evalResult.getSupplierId(), supplier.getId())){
							supplierEvaluationResult = evalResult;
							break;
						}
					}
				}
				
				if(null == supplierEvaluationResult){
					supplierEvaluationResult = new SupplierEvaluationResult();
					supplierEvaluationResult.setTenderId(tenderProjectEntity.getId());
					supplierEvaluationResult.setSupplierId(supplier.getId());
				}
				supplier.setSupplierEvaluationResult(supplierEvaluationResult);
			}
		}else {
			submit_result_btn.setEnabled(false);
		}
		if(null == supplierList)supplierList = new ArrayList<Supplier>();
		return supplierList;
	}

	
	/**
	 * @Description: 评审完成
	 * @author guoyr
	 */
	private void submitEvaluationResultAction(){
		if(submit_result_btn.getEnabled()){
			expertEvaluationStepService.updateExpertEvaluationStatus(CommonEnum.IN_PROGRESS, tenderProjectEntity.getId(), evaluationStep, CURRENT_EXPERT.getUserId());
			
			if(checkNoEvaluation()){
				
				if(null != noComplateFilterStep){
					
					if (MessageDialog.openConfirm(getShell(), Messages.Dialog_warmTips, MessageFormat.format(Messages.Tips_preStepNotCompletedBeforeEntry, noComplateFilterStep.getStepName()), new String[]{Messages.Button_refresh, Messages.Button_cancel})) {
						refreshTenderInfo();
					}
					return;
				}
				String message = MessageFormat.format(Messages.Button_submitAndEndEvaluation, evaluationStep.getStepName());
				if(!MessageDialog.openConfirm(getShell(), Messages.Button_submitEvaluationResult, message, new String[]{Messages.Button_confirmComplate, Messages.Button_continueEvaluation})){
					return ;
				}
				if(evaluationTable.submitRecommonedEvaluationResult()){
					goBackAction();
				}
			}
		}
	}
	
	/**
	 * @Description: 检查未完成的评标步骤
	 * @author guoyr
	 * @return 
	 */
	private boolean checkNoEvaluation(){
		// 在提交前先验证是否完成所有评标操作
		List<EvaluationStep> evaluationStepList = evaluationStepService.getEvaluationStepList(tenderProjectEntity.getId());
		// 推荐时需要验证是否所有的评标步骤已经完成
		StringBuilder notEvaluationComplate = new StringBuilder();
		int notComplateCount = 0;
		notEvaluationComplate.append(Messages.Tips_unComplateProgress);
		notEvaluationComplate.append("\r\n");
		for(EvaluationStep node : evaluationStepList){
			if(node.getStepType().equals(EvaluationStepEnum.SIGIN)){
				continue;
			}
			
			if(!node.getId().equals(evaluationStep.getId()) && !ObjectUtils.equals(node.getStepStatus(), CommonEnum.COMPLETE)){
				notEvaluationComplate.append("    （");
				notEvaluationComplate.append(notComplateCount+1);
				notEvaluationComplate.append("）");
				notEvaluationComplate.append(node.getStepName());
				notEvaluationComplate.append("\r\n");
				notComplateCount ++;
			}
		}
		notEvaluationComplate.append(Messages.Tips_pleaseWait);
		if(notComplateCount > 0){
			MessageDialog.openInformation(getShell(), notEvaluationComplate.toString());
			return false;
		}
	
		return true;
	}
	
	/**
	 * @Description: 获得未完成的可能会存在废标的评审节点
	 * @author guoyr 
	 */
	private void getNoComplateFilterStep(){
		List<EvaluationStep> evaluationStepList = evaluationStepService.getNotComplateStepList(tenderProjectEntity.getId(), evaluationStep.getSortNo());
		if (null != evaluationStepList && evaluationStepList.size() > 0) {
			noComplateFilterStep =  evaluationStepList.get(0);
		}else {
			noComplateFilterStep = null;
		}
	}
	
	public void addExpertEvaluationListener(ExpertEvaluationListener expertEvaluationListener){
		this.expertEvaluationListener = expertEvaluationListener;
	}
	@Override
	protected void checkSubclass() {
	}
}
