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.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 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.ExpertEnum;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.evaluation.step.composite.LimitPriceEvaluationTableComposite;
import com.gx.obe.evaluation.step.dialog.ViewResultDialog;
import com.gx.obe.evaluation.step.listener.ExpertEvaluationListener;
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.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 chenxw
 */
public class LimitPriceEvaluationComposite extends Composite {

	private Composite left_tool_composite;
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private EvaluationButton submit_result_btn;
	private SupplierService supplierService = new SupplierService();
	private ProjectRuleService projectRuleService;
	private EvaluationStepService evaluationStepService = new EvaluationStepService();
	private ExpertEvaluationStepService expertEvaluationStepService ;
	private SupplierOpeningResultService supplierOpeningResultService;
	private SupplierEvaluationResultService supplierEvaluationResultService ;
	private ExpertService expertService;
	private ExpertEvaluationListener expertEvaluationListener;
	private Composite price_evaluation_table;
	// private List<Supplier> supplierList;
	private Composite right_composite;
	private Composite evaluationComposite;
	// 获得项目的价格公式参数
	private PriceParam priceParam = null;
	private EvaluationButton save_result_btn;
	private Object hideLeft;
	private Expert CURRENT_EXPERT;
	private LimitPriceEvaluationTableComposite evaluationTable;
	private EvalLeftButton bidPrice;
	private EvaluationStep noComplateFilterStep = null;

	{
		LogUtils.logClass(LimitPriceEvaluationComposite.class);
	}

	/**
	 * @param parent
	 * @param action 
	 * @param style
	 */
	public LimitPriceEvaluationComposite(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");

		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() {
			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() {
			public void mouseUp(MouseEvent e) {
				refreshTenderInfo();
			}
		});

		bidPrice = new EvalLeftButton(left_tool_composite, SWT.NONE);
		bidPrice.setToolTipText(Messages.Button_viewBidEvaluationResults);
		bidPrice.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/result.png"));
		bidPrice.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				viewFinalResultAction();
			}
		});
		
		right_composite = new Composite(this, SWT.NONE);
		GridLayout gl_right_composite = new GridLayout(1, false);
		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));

		evaluationComposite = new Composite(right_composite, SWT.NONE);
		evaluationComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		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);


		price_evaluation_table = new Composite(evaluationComposite, SWT.NONE);
		price_evaluation_table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		price_evaluation_table.setBackground(SWTResourceManager .getColor(SWT.COLOR_WHITE));
		GridLayout gl_price_evaluation_table = new GridLayout(1, false);
		gl_price_evaluation_table.marginHeight = 0;
		gl_price_evaluation_table.marginWidth = 0;
		price_evaluation_table.setLayout(gl_price_evaluation_table);
		
		evaluationTable = new LimitPriceEvaluationTableComposite(price_evaluation_table, SWT.NONE);
		evaluationTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		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);
		GridData gd_save_result_btn = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1);
		save_result_btn.setLayoutData(gd_save_result_btn);
		save_result_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				saveEvaluationResultAction();
			}
		});
		save_result_btn.setText(Messages.Button_saveEvaluationResult);

		submit_result_btn = new EvaluationButton(composite_5, SWT.NONE);
		GridData gd_signBtn = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
		submit_result_btn.setLayoutData(gd_signBtn);
		submit_result_btn.setText(Messages.Button_submitEvaluationResult);
		submit_result_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				submitEvaluationResultAction();
			}
		});

		init();
	}

	/**
	 * @Description: 初始化界面数据
	 * @author chenxw
	 */
	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();
		}
		
		this.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();
		Boolean isShowBidPrice = evaluationStep.getEvaluationParamByKey(com.gx.obe.components.core.enumeration.EvaluationStepEnum.IS_SHOW_BID_PRICE, Boolean.class);
		if (!bidPrice.isDisposed()) {
			bidPrice.setVisible(null != isShowBidPrice && isShowBidPrice);
		}
	}

	/**
	 * @Description: 返回
	 * @author chenxw
	 */
	private void goBackAction() {
		if (null != expertEvaluationListener) {
			expertEvaluationListener.complete();
		}
	}

	/**
	 * @Description: 刷新项目信息
	 * @author chenxw
	 */
	private void refreshTenderInfo() {
		tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
		if (null == tenderProjectRuleEntity) tenderProjectRuleEntity = new TenderProjectRuleEntity();
		getNoComplateFilterStep();
		showEvalPriceComposite();
	}

	/**
     * @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 chenxw
	 */
	private void showEvalPriceComposite() {
		drawEvaluationTable();
		right_composite.layout();
	}

	/**
	 * @Description: 实现评审表格
	 * @author chenxw
	 */
	private void drawEvaluationTable() {
		// 获取投标人评标结果
		evaluationTable.refresh(tenderProjectEntity, tenderProjectRuleEntity, evaluationStep, CURRENT_EXPERT, getSupplierList());
		price_evaluation_table.layout();
	}

	/**
	 * @Description: 刷新投标人的价格分
	 * @author chenxw
	 * @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 chenxw
	 * @param priceScore
	 * @return
	 */
	public BigDecimal getPriceScoreRound(BigDecimal priceScore) {
		return BigDecimalUtils.round(priceScore, priceParam.getPriceScorePoint());
	}

	/**
	 * @Description: 保存评标结果
	 * @author chenxw
	 */
	private void saveEvaluationResultAction() {
		if (save_result_btn.getEnabled()) {
			if (null == tenderProjectEntity.getBidPriceLimit()) {
				MessageDialog.openInformation(getShell(), MessageFormat.format(Messages.Tips_notSetFormat, Messages.TenderLimit));
				return;
			}
			boolean saveSuccess = evaluationTable.savePriceEvaluationResult();
			if (saveSuccess) {
				MessageDialog.openShortMessage(Messages.Tips_saveEvalResultSuccess);
			} else {
				MessageDialog.openInformation(getShell(), Messages.Dialog_warmTips, Messages.Tips_saveEvalResultFailed);
			}
		}
	}

	/**
	 * @Description: 评审完成
	 * @author chenxw
	 */
	private void submitEvaluationResultAction() {
		if (submit_result_btn.getEnabled()) {
			if (null == tenderProjectEntity.getBidPriceLimit()) {
				MessageDialog.openInformation(getShell(), MessageFormat.format(Messages.Tips_notSetFormat, Messages.TenderLimit));
				return;
			}
			if (!evaluationTable.savePriceEvaluationResult()) {
				MessageDialog.openInformation(getShell(), Messages.Dialog_warmTips, Messages.Tips_saveEvalResultFailed);
				return;
			}
			
			// 检查是否存在当前评标步骤之前未完成的步骤
			boolean isFreeProgress = ObjectUtils.equals(tenderProjectRuleEntity.getOrderReview(), com.gx.obe.components.core.enumeration.EvaluationStepEnum.ORDER_SELF_FREE);
			if (isFreeProgress) {
				List<EvaluationStep> evaluationStepList = evaluationStepService.getNotComplateStepList(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 ;
				}
			}
			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.Tips_submitEvaluationResult, evaluationStep.getStepName());
			if (!MessageDialog.openConfirm(getShell(), Messages.Button_submitEvaluationResult, message, new String[] { Messages.Button_confirmComplate, Messages.Button_continueEvaluation})) {
				return;
			}
			if (!evaluationTable.submitPriceEvaluationResult()) {
				MessageDialog.openInformation(getShell(), Messages.Dialog_warmTips, Messages.Tips_submitEvalResultFailed);
				return;
			}
			goBackAction();
		}
	}

	private void getNoComplateFilterStep(){
		List<EvaluationStep> evaluationStepList = evaluationStepService.getNotComplateFilterStepList(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;
	}

	protected void checkSubclass() {

	}
}
