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

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

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.utils.WidgetUtils;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.gx.obe.ColorConstants;
import com.gx.obe.action.bean.Action;
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.common.widget.composite.TipsComposite;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.util.MoneyUtils;
import com.gx.obe.evaluation.step.dialog.ApplyReEvaluationDialog;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
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.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.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;

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;
import de.kupzog.ktable.renderers.CellForegroundRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedWrapCellRenderer;
import de.kupzog.ktable.renderers.TextWrapCellRenderer;

public class LimitPriceCheckResultComposite extends Composite {

	private String EVAL_ACCESSMENT_YES = Messages.Qualified;
	private String EVAL_ACCESSMENT_NO = Messages.Unqualified;
	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private EvaluationStep evaluationStep;
	private Expert CURRENT_EXPERT;
	private String OPERATOR_USER_ID;
	private ELink applyReEvaluation_link;
	private Composite tableComposite;
	private List<Supplier> supplierList;
	private KTable resultKTable;
	private CommonKtableCModel commonKtableCModel;
	private SupplierService supplierService = new SupplierService();
	private SupplierOpeningResultService supplierOpeningResultService ;
//	private ExpertEvaluationStepService expertEvaluationStepService ;
	private ExpertEvaluationResultService expertEvaluationResultService;
	private ExpertService expertService ;
	private String[] title;
	private boolean isShowLimitPrice;
	private boolean isShowBidPrice;
	private Map<String, ExpertEvaluationResult> expertEvaluationResultMap;
	private Composite evaluationTableComposite;
	
	private ExpertEvaluationStepService expertEvaluationStepService = new ExpertEvaluationStepService();
	private TipsComposite noteMessageLabel;
	
	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param action 
	 * @param style
	 */
	public LimitPriceCheckResultComposite(Composite parent, Action action, int style) {
		super(parent, style);
		this.tenderProjectEntity = action.getTenderProject();
		this.evaluationStep = (EvaluationStep) parent.getData("evaluationStep");
		this.tenderProjectRuleEntity = action.getTenderProjectRule();
		this.OPERATOR_USER_ID = (String)parent.getData(Constants.OPERATOR_USERID);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 1;
		gridLayout.marginWidth = 1;
		setLayout(gridLayout);

		Composite composite = new Composite(this, SWT.NONE);
		composite.setLayout(new GridLayout(2, false));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

		noteMessageLabel = new TipsComposite(composite, SWT.WRAP);
		noteMessageLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		noteMessageLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
		noteMessageLabel.addTips(Messages.Tips_exceedsBiddingLimit);

		applyReEvaluation_link = new ELink(composite, SWT.NONE);
		applyReEvaluation_link.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/hand.png"));
		applyReEvaluation_link.setText(Messages.Button_appllyForBack);
		applyReEvaluation_link.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				applyReEvaluationAction();
			}
		});

		tableComposite = new Composite(this, SWT.NONE);
		tableComposite.setBackground(SWTResourceManager.getColor(220, 220, 220));
		GridLayout gl_tableComposite = new GridLayout(1, false);
		gl_tableComposite.marginHeight = 1;
		gl_tableComposite.marginWidth = 1;
		tableComposite.setLayout(gl_tableComposite);
		tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		evaluationTableComposite = new Composite(tableComposite, SWT.NONE);
		evaluationTableComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_evaluationTableComposite = new GridLayout(1, false);
		gl_evaluationTableComposite.marginHeight = 0;
		gl_evaluationTableComposite.marginWidth = 0;
		evaluationTableComposite.setLayout(gl_evaluationTableComposite);
		evaluationTableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		init();
	}

	private void init() {
		expertEvaluationResultService = new ExpertEvaluationResultService();
		supplierOpeningResultService = new SupplierOpeningResultService();
		
		expertService = new ExpertService();
		CURRENT_EXPERT = expertService.getEvaluationStepExpert(tenderProjectEntity.getId(), evaluationStep);
		
		expertEvaluationResultMap = new HashMap<String, ExpertEvaluationResult>();
		List<ExpertEvaluationResult> queryExpertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
		applyReEvaluation_link.setText(MessageFormat.format(Messages.Button_appllyForBackFormat, evaluationStep.getStepName()));
		WidgetUtils.setControlVisible(applyReEvaluation_link, null != OPERATOR_USER_ID && OPERATOR_USER_ID.equals(Constants.USER.getId()));
		boolean isShowLimitPriceObj = evaluationStep.getEvaluationParamByKey(com.gx.obe.components.core.enumeration.EvaluationStepEnum.IS_SHOW_LIMIT_PRICE, Boolean.class);
		if(isShowLimitPriceObj){
			isShowLimitPrice = true;
		}else {
			isShowLimitPrice = false;
			
		}
		boolean isShowBidPriceObj = evaluationStep.getEvaluationParamByKey(com.gx.obe.components.core.enumeration.EvaluationStepEnum.IS_SHOW_BID_PRICE, Boolean.class);
		if(isShowBidPriceObj){
			isShowBidPrice = true;
		}else {
			isShowBidPrice = false;
		}
		if (null != tenderProjectEntity.getBidPriceLimit()) {
			if(isShowLimitPrice){
				noteMessageLabel.addTips(Messages.TenderLimit + "："+ MoneyUtils.getMoneyWidthUnit(tenderProjectEntity.getBidPriceLimit(), tenderProjectRuleEntity.getEvalPriceUnit()));
			}else {
				noteMessageLabel.addTips(Messages.TenderLimit + "：***");
			}
		}else {
			noteMessageLabel.addTips(MessageFormat.format(Messages.Tips_notSetFormat, Messages.TenderLimit), ColorConstants.FONT_RED_COLOR, null);
		}
		title = new String[] {MessageFormat.format(Messages.NameFormat, com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType())), Messages.EvaluationPrice + "（"+tenderProjectRuleEntity.getEvalPriceUnit()+"）", Messages.CheckResult, Messages.Conclusion };
		supplierList = supplierService.getEvaluationStepSupplierList(tenderProjectEntity.getId(), evaluationStep);
		// 则获取开标成功的投标人
		List<SupplierOpeningResult> supplierOpeningResultList = supplierOpeningResultService.getSupplierOpeningResultListByTenderIdAndBidOpeningStatus(tenderProjectEntity.getId(), SupplierEnum.OPENBID_SUCCESS);
		for (final Supplier supplier : supplierList) {
			expertEvaluationResultMap.put(supplier.getId(), CollectionUtils.get(queryExpertEvaluationResultList, t -> {
				return ObjectUtils.equals(t.getSupplierId(), supplier.getId());
			}));
			supplier.setSupplierOpeningResult(CollectionUtils.get(supplierOpeningResultList, t -> {
				return ObjectUtils.equals(t.getSupplierId(), supplier.getId());
			}));
		}
		drawEvaluationTable();
	}

	private void drawEvaluationTable() {
		resultKTable = new KTable(evaluationTableComposite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY);
		resultKTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		commonKtableCModel = new CommonKtableCModel(resultKTable, 1, 1, supplierList.size(), title.length - 1);
		// 设置列宽
		commonKtableCModel.setColumnMaxWidth(0, 200);
		commonKtableCModel.setColumnMinWidth(0, 150);
		commonKtableCModel.setColumnWidth(1, 50);
		commonKtableCModel.setColumnWidth(2, 30);
		commonKtableCModel.setColumnWidth(3, 30);
		commonKtableCModel.setColumnWidth(4, 300);
		CellContentRender contentRender = new CellContentRender() {
			public Object receiveContent(int row, int col) {
				if (row < commonKtableCModel.getFixedHeaderRowCount()) {
					return title[col];
				} else {
					int suplierListStart = row - commonKtableCModel.getFixedHeaderRowCount();
					if (suplierListStart < supplierList.size()) {
						Supplier supplier = supplierList.get(suplierListStart);
						SupplierOpeningResult openingResult = supplier.getSupplierOpeningResult();
						if (col == 0) {
							return null != supplier.getSupplierName() ? supplier.getSupplierName() : "";
						} else if (col == 1) {
							if (null != openingResult) {
								if (isShowBidPrice) {
									return openingResult.getFormatEvaluatoinPriceByUnit(tenderProjectRuleEntity.getEvalPriceUnit());
								}
								return "***";
							}
						} else if (col == 2) {
							if (null != openingResult) {
								BigDecimal bidPriceLimit = tenderProjectEntity.getBidPriceLimit();
								BigDecimal bidPrice = openingResult.getEvaluationPrice();
								if (null != bidPriceLimit && null != bidPrice) {
									if (bidPrice.compareTo(bidPriceLimit) > 0) {
										return Messages.ExceedLimitPrice;
									} else {
										return Messages.NotExceedLimitPrice;
									}
								}
							}
						} else {
							ExpertEvaluationResult evaluationResult = expertEvaluationResultMap.get(supplier.getId());
							if (null != evaluationResult && null != evaluationResult.getAccessment()) {
								if (col == 3) {
									String accessment = evaluationResult.getAccessment();
									if (null != accessment) {
										if (accessment.equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.QUALIFIED)) {
											return EVAL_ACCESSMENT_YES;
										} else if (accessment.equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.UNQUALIFIED)) {
											return EVAL_ACCESSMENT_NO;
										}
									}
								} else if (col == 4) {
									String supplierOpinion = evaluationResult.getSupplierOpinion();
									if (null != supplierOpinion) {
										return supplierOpinion;
									}
								}
							}
						}
					}
				}
				return "";
			}
		};
		commonKtableCModel.setCellContentRender(contentRender);
		// 设置单元格渲染器
		CellRender cellRender = new CellRender() {
			public Object receiveCellRender(int row, int col) {
				if (commonKtableCModel.isFixedCell(col, row)) {
					return new FixedWrapCellRenderer();
				} else {
					return new TextWrapCellRenderer();
				}
			}
		};
		commonKtableCModel.setCellRender(cellRender);
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				if (row >= commonKtableCModel.getFixedHeaderRowCount()) {
					if (col == 0 || col == 4) {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					}
					if (col == 1) {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_RIGHT;
					}
				}
				return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
			}
		};
		commonKtableCModel.setCellAlignmentRender(cellAlignmentRender);
		
		// 设置单元格前景颜色
		CellForegroundRender cellForegroundRender = new CellForegroundRender() {
			public Color receiveCellForeground(int row, int col) {
				if (row >= commonKtableCModel.getFixedHeaderRowCount()) {
					int suplierListStart = row - commonKtableCModel.getFixedHeaderRowCount();
					Supplier supplier = supplierList.get(suplierListStart);
					if (col > 0 && col < 3) {
						SupplierOpeningResult openingResult = supplier.getSupplierOpeningResult();
						if (null != openingResult) {
							BigDecimal bidPriceLimit = tenderProjectEntity.getBidPriceLimit();
							BigDecimal bidPrice = openingResult.getEvaluationPrice();
							if (null != bidPriceLimit && null != bidPrice) {
								if (bidPrice.compareTo(bidPriceLimit) > 0) {
									return SWTResourceManager.getColor(SWT.COLOR_RED);
								}
							}
						}
					} else if (col == 3) {
						ExpertEvaluationResult evaluationResult = expertEvaluationResultMap.get(supplier.getId());
						if(null != evaluationResult){
							String accessment = expertEvaluationResultMap.get(supplier.getId()).getAccessment();
							if (StringUtils.isNotEmpty(accessment)) {
								if (accessment.equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.QUALIFIED)) {
									return SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN);
								} else if (accessment.equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.UNQUALIFIED)) {
									return SWTResourceManager.getColor(SWT.COLOR_RED);
								}
							}
						}
					}
				}
				return null;
			}
		};
		commonKtableCModel.setCellForegroundRender(cellForegroundRender);
		resultKTable.setModel(commonKtableCModel);
	}

	/**
	 * @Description: 申请回退
	 * @author guoyr
	 */
	private void applyReEvaluationAction() {
		if (applyReEvaluation_link.getEnabled()) {
			ExpertEvaluationStep expertEvaluationStep = expertEvaluationStepService.getExpertEvaluationStep(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
			if (null != expertEvaluationStep) {
				ApplyReEvaluationDialog applyReEvaluationDialog = new ApplyReEvaluationDialog(getShell(), evaluationStep, expertEvaluationStep);
				applyReEvaluationDialog.open();
			}
		}
	}

	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
