package com.gx.obe.evaluation.step.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.ImageResolver;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
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.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.EvaluationOpinionDialog;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.util.utils.UuidUtils;
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.expert.ExpertEvaluationResultService;
import com.gx.obe.web.service.expert.ExpertEvaluationStepService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.editors.KTableCellEditorGRadio;
import de.kupzog.ktable.editors.KTableCellEditorMultilineWrapText;
import de.kupzog.ktable.model.CommonKtableCModel;
import de.kupzog.ktable.renderers.CellAlignmentRender;
import de.kupzog.ktable.renderers.CellContentRender;
import de.kupzog.ktable.renderers.CellEditContentRender;
import de.kupzog.ktable.renderers.CellEditorRender;
import de.kupzog.ktable.renderers.CellForegroundRender;
import de.kupzog.ktable.renderers.CellImageRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedWrapCellRenderer;
import de.kupzog.ktable.renderers.TextWrapCellRenderer;

/**
 * @Description: 限价评审面板
 * @author chenxw
 */
public class LimitPriceEvaluationTableComposite extends Composite {

	private String EVAL_ACCESSMENT_YES = Messages.Qualified;
	private String EVAL_ACCESSMENT_NO = Messages.Unqualified;
	private ImageResolver imageResolver = new ImageResolver();
	private Composite evaluationTableComposite;
	private Composite bodyComposite;
	private boolean isShowLimitPrice;
	private boolean isShowBidPrice;
	private String[] title;
	private List<Supplier> supplierList;
	private KTable resultKTable;
	private CommonKtableCModel commonKtableCModel;
	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private EvaluationStep evaluationStep;
	private Expert CURRENT_EXPERT;
	private boolean resultChanged;
	private ExpertEvaluationStepService expertEvaluationStepService ;
	private ExpertEvaluationResultService expertEvaluationResultService;
	private Map<String, ExpertEvaluationResult> expertEvaluationResultMap;
	private Composite headComposite;
	private TipsComposite noteMessageLabel;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public LimitPriceEvaluationTableComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		headComposite = new Composite(this, SWT.NONE);
		headComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridData gd_composite_5 = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_composite_5.widthHint = 500;
		headComposite.setLayoutData(gd_composite_5);
		GridLayout gl_composite_5 = new GridLayout(3, false);
		headComposite.setLayout(gl_composite_5);
		headComposite.setBackgroundMode(SWT.INHERIT_FORCE);

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

		bodyComposite = new Composite(this, SWT.NONE);
		bodyComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_composite_1 = new GridLayout(1, false);
		gl_composite_1.marginHeight = 1;
		gl_composite_1.marginWidth = 1;
		bodyComposite.setLayout(gl_composite_1);
		bodyComposite.setBackground(ColorConstants.BORDER_LINE_COLOR);

		evaluationTableComposite = new Composite(bodyComposite, 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);
		GridData gd_evaluationTableComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_evaluationTableComposite.minimumHeight = 200;
		evaluationTableComposite.setLayoutData(gd_evaluationTableComposite);
		resultChanged = true;
		expertEvaluationStepService = new ExpertEvaluationStepService();
		expertEvaluationResultService = new ExpertEvaluationResultService();
	}

	/**
	 * @Description: 初始化
	 * @author chenxw
	 * @param evaluationStep
	 * @param tenderProjectEntity
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, TenderProjectRuleEntity tenderProjectRuleEntity, EvaluationStep evaluationStep, Expert CURRENT_EXPERT, List<Supplier> supplierList) {
		this.tenderProjectEntity = tenderProjectEntity;
		this.tenderProjectRuleEntity = tenderProjectRuleEntity;
		this.evaluationStep = evaluationStep;
		this.CURRENT_EXPERT = CURRENT_EXPERT;
		this.supplierList = supplierList;
		expertEvaluationResultMap = new HashMap<String, ExpertEvaluationResult>();
		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;
		}
		
		noteMessageLabel.clear();
		noteMessageLabel.addTips(Messages.Tips_exceedsBiddingLimit);
		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 };
//		title = new String[] {com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType())+Messages.Name, "投标报价（"+tenderProjectRuleEntity.getPriceUintCN()+"）", "是否超出限价", "评审结论", Messages.Title_evaluationOpinion };
		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);
		}
		
//		Label noteMessageLabel = new Label(headComposite, SWT.NONE);
//		noteMessageLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
//		noteMessageLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
//		noteMessageLabel.setText(Messages.Tips_exceedsBiddingLimit);

		headComposite.layout();
		resultChanged = true;
		drawEvaluationTable();
		layout();
	}

	private void initEvaluationResult() {
		List<ExpertEvaluationResult> queryExpertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
		for (Supplier supplier : supplierList) {
			// 获取评标专家对投标人的评审记录
			ExpertEvaluationResult expertEvaluationResult = null;
			if (null != queryExpertEvaluationResultList && queryExpertEvaluationResultList.size() > 0) {
				for (ExpertEvaluationResult queryExpertEvaluationResult : queryExpertEvaluationResultList) {
					if (ObjectUtils.equals(queryExpertEvaluationResult.getSupplierId(), supplier.getId())) {
						expertEvaluationResult = queryExpertEvaluationResult;
						break;
					}
				}
			}
			if (null == expertEvaluationResult) {
				expertEvaluationResult = new ExpertEvaluationResult();
				expertEvaluationResult.setId(UuidUtils.getUUID());
				expertEvaluationResult.setTenderId(tenderProjectEntity.getId());
				expertEvaluationResult.setStepId(evaluationStep.getId());
				expertEvaluationResult.setUserId(CURRENT_EXPERT.getUserId());
				expertEvaluationResult.setSupplierId(supplier.getId());

				SupplierOpeningResult openingResult = supplier.getSupplierOpeningResult();
				BigDecimal bidPrice = openingResult.getEvaluationPrice();
				BigDecimal bidPriceLimit = tenderProjectEntity.getBidPriceLimit();
				if (null != bidPriceLimit && null != bidPrice && bidPrice.compareTo(bidPriceLimit) > 0) {
					expertEvaluationResult.setAccessment(com.gx.obe.components.core.enumeration.EvaluationStepEnum.UNQUALIFIED);
				} else {
					expertEvaluationResult.setAccessment(com.gx.obe.components.core.enumeration.EvaluationStepEnum.QUALIFIED);
				}
			}
			expertEvaluationResultMap.put(supplier.getId(), expertEvaluationResult);
		}
	}

	/**
	 * @Description: 供应商表格
	 * @author chenxw
	 */
	private void drawEvaluationTable() {
		initEvaluationResult();
		if(null != resultKTable && !resultKTable.isDisposed()){
			resultKTable.dispose();
		}
		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);
		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 if (col == 3) {
							String accessment = expertEvaluationResultMap.get(supplier.getId()).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 = expertEvaluationResultMap.get(supplier.getId()).getSupplierOpinion();
							if (null != supplierOpinion) {
								return supplierOpinion;
							}
						}
					}
				}
				return "";
			}
		};
		commonKtableCModel.setCellContentRender(contentRender);

		CellEditContentRender editContentRender = new CellEditContentRender() {
			public void receiveContent(int row, int col, Object content) {
				if (null == content) {
					return;
				}
				if (row >= commonKtableCModel.getFixedHeaderRowCount()) {
					int suplierListStart = row - commonKtableCModel.getFixedHeaderRowCount();
					if (suplierListStart < supplierList.size()) {
						Supplier supplier = supplierList.get(suplierListStart);
						ExpertEvaluationResult expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
						if (col == 3) {
							expertEvaluationResult.setAccessment(content.toString());
							if(com.gx.obe.components.core.enumeration.EvaluationStepEnum.UNQUALIFIED.equals(content.toString())){
								expertEvaluationResult.setAccessment(com.gx.obe.components.core.enumeration.EvaluationStepEnum.UNQUALIFIED);
								EvaluationOpinionDialog dialog = new EvaluationOpinionDialog(getShell(), tenderProjectEntity, supplier, Constants.USER, expertEvaluationResult);
								dialog.open();
							}else {
								expertEvaluationResult.setSupplierOpinion(null);
							}
							
						} else if (col == 4) {
							expertEvaluationResult.setSupplierOpinion(content.toString());
						}
					}
				}
				resultChanged = true;
			}
		};
		commonKtableCModel.setCellEditContentRender(editContentRender);

		// 设置单元格编辑器
		final KTableCellEditorMultilineWrapText cellEditorText = new KTableCellEditorMultilineWrapText();
		cellEditorText.setTextLimit(500);
		cellEditorText.setSingleClickEdit(true);
		final KTableCellEditorGRadio radio = new KTableCellEditorGRadio();
		radio.setSingleClickEdit(true);
		radio.addItem(EVAL_ACCESSMENT_YES);
		radio.addItem(EVAL_ACCESSMENT_NO);
		CellEditorRender cellEditorRender = new CellEditorRender() {
			public Object receiveCellEditor(int row, int col) {
				if (row >= commonKtableCModel.getFixedHeaderRowCount()) {
					if (col == 3) {
						if (null != tenderProjectEntity.getBidPriceLimit()) {
							radio.setItem(0, EVAL_ACCESSMENT_YES, com.gx.obe.components.core.enumeration.EvaluationStepEnum.QUALIFIED);
							radio.setItem(1, EVAL_ACCESSMENT_NO, com.gx.obe.components.core.enumeration.EvaluationStepEnum.UNQUALIFIED);
							return radio;
						}
					} else if (col == 4) {
						return cellEditorText;
					}
				}
				return null;
			}
		};
		commonKtableCModel.setCellEditorRender(cellEditorRender);

		// 设置单元格渲染器
		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);
		
		// 设置单元格图片
		final Image editImage = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/edit.png");
		commonKtableCModel.setCellImageRender(new CellImageRender() {
			public Image receiveCellImage(int row, int col) {
				if (row > 0) {
					switch (col) {
						case 4: return editImage;
					}
				}
				return null;
			}
		});
		
		// 设置单元格前景颜色
		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) {
						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);
		evaluationTableComposite.layout();
	}

	/**
	 * @Description: 保存评审结果
	 * @author chenxw
	 * @return
	 */
	public boolean savePriceEvaluationResult() {
		boolean saveSuccess = true;
		// 如果修改了结果，才保存结果
		if (resultChanged) {
			saveSuccess = expertEvaluationStepService.saveLimitPriceEvaluationResult(tenderProjectEntity.getId(), CURRENT_EXPERT.getUserId(), evaluationStep, expertEvaluationResultMap);
			if (saveSuccess) {
				resultChanged = false;
			} else {
				resultChanged = true;
			}
		}
		return saveSuccess;
	}

	/**
	 * @Description: 提交评审结果
	 * @author chenxw
	 * @return
	 */
	public boolean submitPriceEvaluationResult() {
		return expertEvaluationStepService.submitLimitPriceEvaluationResult(tenderProjectEntity.getId(), CURRENT_EXPERT.getUserId(), evaluationStep, supplierList);
	}

	/**
	 * @Description: 释放资源
	 * @author chenxw
	 */
	public void dispose() {
		imageResolver.disposite();
		super.dispose();
	}

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