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

import java.math.BigDecimal;
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.core.widgets.EButton;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StackLayout;
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.action.bean.EAction;
import com.gx.obe.action.utils.ActionUtil;
import com.gx.obe.business.entity.ExpertEvaluationStep;
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.common.widget.utils.MenuFunctionUtils;
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.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.evaluation.step.action.ViewBidPriceEvaluationResultAction;
import com.gx.obe.evaluation.step.composite.CorrectPriceComposite;
import com.gx.obe.evaluation.step.composite.PriceEvaluationTableComposite;
import com.gx.obe.evaluation.step.dialog.ReReasonDialog;
import com.gx.obe.evaluation.step.dialog.ViewResultDialog;
import com.gx.obe.evaluation.step.inter.IPriceEvaluationTable;
import com.gx.obe.evaluation.step.listener.ExpertEvaluationListener;
import com.gx.obe.evaluation.step.listener.PriceEvaluationListener;
import com.gx.obe.evaluation.step.listener.PriceReviewEvaluationListener;
import com.gx.obe.formula.PriceParam;
import com.gx.obe.message.Messages;
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.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
import com.gx.obe.web.entity.auth.Menu;
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.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 PriceEvaluationComposite extends Composite {

	private Composite left_tool_composite;
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private Expert CURRENT_EXPERT;
	private ExpertService expertService ;
	private SupplierOpeningResultService supplierOpeningResultService ;
	private ProjectRuleService projectRuleService ;
	private SupplierService supplierService = new SupplierService();
//	private ExpertEvaluationStepService expertEvaluationStepService ;
	private EvaluationStepService evaluationStepService = new EvaluationStepService();
	private ExpertEvaluationListener expertEvaluationListener;
	private Composite price_evaluation_table;
	private List<Supplier> supplierList;
	private IPriceEvaluationTable evaluationTable = null;
	private Composite right_composite;
	private StackLayout stackLayout = new StackLayout();
	private Composite evaluationComposite;
	private Composite correct_evalprice_composite;
	// 获得项目的价格公式参数
	private PriceParam priceParam = null;
	private PriceEvaluationListener priceEvaluationListener;
//	private ELink recorrect_btn;
	private EvaluationButton save_result_btn;
	private EvaluationButton submit_result_btn;
	private Object hideLeft;
//	private Composite composite;
	private ScrolledComposite scrolledComposite;
	private PriceReviewEvaluationListener priceReviewEvaluationListener;
	private EvaluationStep noComplateFilterStep = null;
	private Menu menu;
	private ExpertEvaluationStepService expertEvaluationStepService = new ExpertEvaluationStepService();
 	private MenuFunctionUtils menuFunctionUtils = new MenuFunctionUtils();
	{
		LogUtils.logClass(PriceEvaluationComposite.class);
	}
	
	/**
	 * @param parent
	 * @param style
	 */
	public PriceEvaluationComposite(Composite parent,Action action, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(2, 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");
		menu = (Menu) parent.getData("menu");
		
		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.SELECTED);
		goto_back.setLayoutData(new GridData(SWT.CENTER, 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.SELECTED);
		goto_back.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
		refresh_evaluation.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/refresh.png"));
		refresh_evaluation.setToolTipText(Messages.Button_refresh);
		
		refresh_evaluation.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				refreshTenderInfo();
			}
		});
		
		EvalLeftButton bidPrice = new EvalLeftButton(left_tool_composite, SWT.NONE);
		bidPrice.setToolTipText(Messages.Button_viewBidEvaluationResults);
//		bidPrice.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/bidPrice.png"));
		bidPrice.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/result.png"));
		bidPrice.setText("");
		bidPrice.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				viewFinalResultAction();
			}
		});
		menuFunctionUtils.addFunction(bidPrice, "EVALUATION_VIEW_RESULTS");
		
		right_composite = new Composite(this, SWT.NONE);
		right_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		right_composite.setLayout(stackLayout);
		
		
		correct_evalprice_composite = new Composite(right_composite, SWT.NONE);
		correct_evalprice_composite.setLayout(new FillLayout(SWT.HORIZONTAL));
		
		evaluationComposite = new Composite(right_composite, SWT.NONE);
		GridLayout gl_container = new GridLayout(1, false);
		gl_container.verticalSpacing = 0;
		gl_container.marginHeight = 0;
		gl_container.marginWidth = 0;
		gl_container.horizontalSpacing = 0;
		evaluationComposite.setLayout(gl_container);
		
		scrolledComposite = new ScrolledComposite(evaluationComposite, SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		
		price_evaluation_table = new Composite(scrolledComposite, SWT.NONE);
		price_evaluation_table.setLayout(new FillLayout(SWT.HORIZONTAL));
		price_evaluation_table.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		evaluationTable = new PriceEvaluationTableComposite(price_evaluation_table, SWT.NONE);
		
		
		scrolledComposite.setContent(price_evaluation_table);
		scrolledComposite.setMinSize(price_evaluation_table.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		
		Composite composite_5 = new Composite(evaluationComposite, SWT.NONE);
		composite_5.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		composite_5.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		composite_5.setLayout(new GridLayout(2, false));
		
		save_result_btn = new EvaluationButton(composite_5, SWT.NONE | EButton.CSS_GREEN);
		save_result_btn.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));
		save_result_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				saveEvaluationResultAction();
			}
		});
		save_result_btn.setText(Messages.Button_saveEvaluationResult);
		
		submit_result_btn = new EvaluationButton(composite_5, SWT.NONE | EButton.CSS_GREEN);
		submit_result_btn.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
		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(){
		supplierOpeningResultService = new SupplierOpeningResultService();
		expertService = new ExpertService();
		projectRuleService = new ProjectRuleService();
		if(null != hideLeft){
			left_tool_composite.dispose();
		}
		menuFunctionUtils.initFunctionAuthority(menu);
		
		CURRENT_EXPERT = expertService.getEvaluationStepExpert(tenderProjectEntity.getId(), evaluationStep);

		priceEvaluationListener = new PriceEvaluationListener(){
			public void priceEvaluation() {
				showEvalPriceComposite();
			}
			public void goBack(){
				goBackAction();
			}
		};
		
		priceReviewEvaluationListener = new PriceReviewEvaluationListener(){
			public void goBack(){
				goBackAction();
			}
			public void priceReviewEvaluation() {
				showCorrectPriceComposite();
				
			}
		};

		// 修改状态为正在进行中
		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();
		boolean showCorrectPriceComposite = false;
		getNoComplateFilterStep();
		// 如果需要修正评标价
		if(ObjectUtils.equals(tenderProjectRuleEntity.getCorrectPrice(), CommonEnum.YES)){
			stackLayout.topControl = correct_evalprice_composite;
			
			ExpertEvaluationStep memberEvaluationStep = expertEvaluationStepService.getExpertEvaluationStep(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
			if(null != memberEvaluationStep && ObjectUtils.equals(memberEvaluationStep.getPriceConfirmStatus(), CommonEnum.YES)){
				showCorrectPriceComposite = true;
			}
		}
		if(showCorrectPriceComposite){
			showCorrectPriceComposite();
		}else {
			showEvalPriceComposite();
		}
	}
	
	/**
	 * @Description: 查看投标报价
	 * @author guoyr
	 * @param supplier 
	 */
	public void viewBidPice(){
		EAction action = (EAction)ActionUtil.getEAction(ViewBidPriceEvaluationResultAction.class.getName());
		action.setData("evaluationStep", evaluationStep);
		action.setTenderProject(tenderProjectEntity);
		action.setTenderProjectRule(tenderProjectRuleEntity);
		action.setData(Constants.CUR_EXPERT, CURRENT_EXPERT);
		action.setName("查看价格");
		action.setParent(getShell());
		action.run();
	}
	/**
     * @Description: 
     * @author chenxw 
     */
    private void viewFinalResultAction() {
        String viewOpenResult = CommonEnum.YES;
        String viewEvalResult = CommonEnum.YES;
        String expertSelfUserId = null;
        // 如果是专家组长，则全部可以查看
        if(!ExpertEnum.LEADER_YES.equals(CURRENT_EXPERT.getIsLeader())){
            viewOpenResult = tenderProjectRuleEntity.getViewBidPrice();
            if (StringUtils.isEmpty(viewOpenResult)) {
                viewOpenResult = PropertiesUtils.getProperty(ConfigConstants.VIEW_OPEN_RESULT, CommonEnum.YES);
            }
            viewEvalResult = tenderProjectRuleEntity.getViewPriceScore();
            if (StringUtils.isEmpty(viewEvalResult)) {
                viewEvalResult = PropertiesUtils.getProperty(ConfigConstants.VIEW_EVAL_RESULT, CommonEnum.YES);
            }
            expertSelfUserId = CURRENT_EXPERT.getUserId();
        }
        ViewResultDialog viewResultDialog = new ViewResultDialog(getShell(), tenderProjectEntity, viewOpenResult, viewEvalResult, expertSelfUserId);
        viewResultDialog.open();
    }
    
	
	/**
	 * @Description: 显示修正评标价
	 * @author guoyr
	 */
	private void showCorrectPriceComposite(){
		for(Control control : correct_evalprice_composite.getChildren()){
			control.dispose();
		}
		
		correct_evalprice_composite.setData("tenderProjectEntity", tenderProjectEntity);
		correct_evalprice_composite.setData("tenderProjectRuleEntity", tenderProjectRuleEntity);
		correct_evalprice_composite.setData("evaluationStep", evaluationStep);
		correct_evalprice_composite.setData(Constants.CUR_EXPERT, CURRENT_EXPERT);
		CorrectPriceComposite correctPriceComposite = new CorrectPriceComposite(correct_evalprice_composite, SWT.NONE);
		correctPriceComposite.addCorrectEvalPriceListener(priceEvaluationListener);
		correct_evalprice_composite.layout();
		stackLayout.topControl = correct_evalprice_composite;
		right_composite.layout();
	}
	
	/**
	 * @Description: 显示价格评审
	 * @author guoyr
	 */
	private void showEvalPriceComposite(){
		stackLayout.topControl = evaluationComposite;
		drawEvaluationTable();
		right_composite.layout();
	}

	
	/**
	 * @Description: 实现评审表格
	 * @author guoyr
	 */
	private void drawEvaluationTable(){
		// 获取投标人评标结果
		supplierList = getSupplierList();
		((PriceEvaluationTableComposite) evaluationTable).addPriceReviewEvaluationListener(priceReviewEvaluationListener);
		evaluationTable.refresh(tenderProjectEntity, tenderProjectRuleEntity, CURRENT_EXPERT, evaluationStep, supplierList);
		price_evaluation_table.layout();
		scrolledComposite.setMinSize(price_evaluation_table.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);
			
			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);
			}
		}else {
			submit_result_btn.setEnabled(false);
		}
		if(null == supplierList)supplierList = new ArrayList<Supplier>();
		return supplierList;
	}

	
	/**
	 * @Description: 获得价格分的四舍五入
	 * @author guoyr
	 * @param priceScore
	 * @return
	 */
	public BigDecimal getPriceScoreRound(BigDecimal priceScore){
		return BigDecimalUtils.round(priceScore, priceParam.getPriceScorePoint());
	}
	
	
	/**
	 * @Description: 重新修正评标价
	 * @author guoyr
	 */
//	private void reCorrectEvalPriceAction(){
//		if(recorrect_btn.getEnabled()){
//			expertEvaluationStepService.reCorrectEvalPrice(tenderProjectEntity.getId(), evaluationStep.getId());
//			showCorrectPriceComposite();
//		}
//	}

	/**
	 * @Description: 保存评标结果
	 * @author guoyr
	 */
	private void saveEvaluationResultAction(){
		
		if(save_result_btn.getEnabled()){
//			if(checkNoEvaluation()){
			
			   
				boolean saveSuccess = evaluationTable.savePriceEvaluationResult();
				if(saveSuccess){
					MessageDialog.openShortMessage(Messages.Tips_saveEvalResultSuccess);
				}else {
					MessageDialog.openInformation(getShell(), Messages.Dialog_warmTips, Messages.Tips_saveEvalResultFailed);
				}
//			}
		}
	}
	
	/**
	 * @Description: 评审完成
	 * @author guoyr
	 */
	private void submitEvaluationResultAction(){
		if(submit_result_btn.getEnabled()){
			
			//判断是否是复议项目并且判断是否是专家组长 如果是的话填写得分修正原因
			if(!StringUtils.isEmpty(tenderProjectEntity.getTenderSourceId()) && CURRENT_EXPERT.getIsLeader().equals("1")) {
			ReReasonDialog dialog = new ReReasonDialog(getShell(), tenderProjectEntity,evaluationStep);
			dialog.open();
			if(dialog.isNull() && !dialog.isSave()) {
				  return;
				}
			}

			boolean saveSuccess = evaluationTable.savePriceEvaluationResult();
			if(saveSuccess){
				
				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;
					}
					if(evaluationTable.submitPriceEvaluationResult()){
						expertEvaluationStepService.updateExpertEvaluationStatus(CommonEnum.COMPLETE, tenderProjectEntity.getId(), evaluationStep,CURRENT_EXPERT.getUserId());
						goBackAction();
					}
				}
			}else {
				MessageDialog.openInformation(getShell(), Messages.Dialog_warmTips, Messages.Tips_saveEvalResultFailed);
			}
		
		}
	}
	
	/**
	 * @Description: 检查未完成的评标步骤
	 * @author guoyr
	 * @return 
	 */
	private boolean checkNoEvaluation(){
		// 在提交前先验证是否存在有未完成的可以废标的步骤
		List<EvaluationStep> evaluationStepList = evaluationStepService.getNotComplateFilterStepList(tenderProjectEntity.getId(), evaluationStep.getSortNo());
		if (null != evaluationStepList && evaluationStepList.size() > 0) {
			MessageDialog.openWarning(getShell(), Messages.Dialog_warmTips, MessageFormat.format(Messages.Tips_saveAllComplate, evaluationStepList.get(0).getStepName()));
			return false;
		}
		return true;
	}
	
	public void addExpertEvaluationListener(ExpertEvaluationListener expertEvaluationListener){
		this.expertEvaluationListener = expertEvaluationListener;
	}
	
	/**
	 * @Description: 获得未完成的可能会存在废标的评审节点
	 * @author guoyr 
	 */
	private void getNoComplateFilterStep(){
		List<EvaluationStep> evaluationStepList = evaluationStepService.getNotComplateFilterStepList(tenderProjectEntity.getId(), evaluationStep.getSortNo());
//		List<EvaluationStep> evaluationStepList = evaluationStepService.getNotComplateStepList(tenderProjectEntity.getId(), evaluationStep.getSortNo());
		if (null != evaluationStepList && evaluationStepList.size() > 0) {
			noComplateFilterStep =  evaluationStepList.get(0);
		}else {
			noComplateFilterStep = null;
		}
	}
	
	@Override
	protected void checkSubclass() {
	}
}
