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

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.custom.CLabel;
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.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
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.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierEvaluationResult;
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.service.SupplierEvaluationResultService;
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 VetoBidEvaluationTableComposite 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 List<Supplier> supplierList;
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private Expert CURRENT_EXPERT;
	private ExpertEvaluationStepService expertEvaluationStepService ;
	private ExpertEvaluationResultService expertEvaluationResultService;  
	 
	private SupplierEvaluationResultService supplierEvaluationResultService ;
	private Map<String, ExpertEvaluationResult> expertEvaluationResultMap;
	private String supplierName;
	private KTable resultKTable;
	private CLabel cleanTenderStepName;
	
	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public VetoBidEvaluationTableComposite(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));
		
		Composite evaluationComposite = new Composite(this, SWT.NONE);
		evaluationComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		evaluationComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_evaluationComposite = new GridLayout(1, false);
		gl_evaluationComposite.verticalSpacing = 0;
		gl_evaluationComposite.horizontalSpacing = 0;
		gl_evaluationComposite.marginHeight = 0;
		gl_evaluationComposite.marginWidth = 0;
		evaluationComposite.setLayout(gl_evaluationComposite);
		
		Composite headComposite = new Composite(evaluationComposite, 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(1, false);
		headComposite.setLayout(gl_composite_5);
		headComposite.setBackgroundMode(SWT.INHERIT_FORCE);
		
		cleanTenderStepName = new CLabel(headComposite, SWT.NONE);
		cleanTenderStepName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
		cleanTenderStepName.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		cleanTenderStepName.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/tips_blue.png"));
		
		Composite bodyComposite = new Composite(evaluationComposite, 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);
		supplierEvaluationResultService = new SupplierEvaluationResultService();
 			expertEvaluationResultService = new ExpertEvaluationResultService();
		 
		expertEvaluationStepService = new ExpertEvaluationStepService();
	}
	
	/**
	 * @Description: 初始化
	 * @author chenxw
	 * @param evaluationStep
	 * @param tenderProjectEntity
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, EvaluationStep evaluationStep, Expert currentExpert, List<Supplier> supplierList) {
		this.tenderProjectEntity = tenderProjectEntity;
		this.evaluationStep = evaluationStep;
		this.CURRENT_EXPERT = currentExpert;
		this.supplierList = supplierList;
		expertEvaluationResultMap = new HashMap<String, ExpertEvaluationResult>();
		initEvaluationResult();
		drawEvaluationTable();
	}
	
	private void initEvaluationResult() {
		supplierName = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType());
		cleanTenderStepName.setText("请对" + supplierName + "设置“" + EVAL_ACCESSMENT_YES + "”或“" + EVAL_ACCESSMENT_NO + "”，" + EVAL_ACCESSMENT_NO + "的" + supplierName + "将不能入围下一评标环节！");
		List<ExpertEvaluationResult> queryExpertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
		List<SupplierEvaluationResult> supplierEvaluationResultList = supplierEvaluationResultService.getSupplierEvaluationResultListByTenderId(tenderProjectEntity.getId());
		for (Supplier supplier : supplierList) {
			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);
			// 获取评标专家对投标人的评审记录
			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.setTenderId(tenderProjectEntity.getId());
				expertEvaluationResult.setStepId(evaluationStep.getId());
				expertEvaluationResult.setUserId(CURRENT_EXPERT.getUserId());
				expertEvaluationResult.setSupplierId(supplier.getId());
				expertEvaluationResult.setAccessment(com.gx.obe.components.core.enumeration.EvaluationStepEnum.QUALIFIED);
			}
			expertEvaluationResultMap.put(supplier.getId(), expertEvaluationResult);
		}
	}
	
	/**
	 * @Description: 供应商表格
	 * @author chenxw
	 */
	private void drawEvaluationTable() {
		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));
		final CommonKtableCModel commKTableModel = new CommonKtableCModel(resultKTable, 1, 1, supplierList.size(), 1);
		commKTableModel.setColumnMinWidth(1, 200);
//		commKTableModel.setColumnMaxWidth(2, 500);
		
		final String[] tableTitles = new String[] { supplierName, "评审结论" };
//		final String[] tableTitles = new String[] { supplierName, "评审结论", Messages.Title_evaluationOpinion };
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender() {
			public Object receiveContent(int row, int col) {
				if (row < commKTableModel.getFixedRowCount()) {
					return tableTitles[col];
				} else {
					int supplierIndex = row - commKTableModel.getFixedRowCount();
					Supplier supplier = supplierList.get(supplierIndex);
					if (col == 0) {
						return supplier.getSupplierName();
					} else {
						ExpertEvaluationResult expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
						if (null != expertEvaluationResult) {
							if (col == 1) {
								String accessment = expertEvaluationResult.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 == 2) {
								return expertEvaluationResult.getSupplierOpinion();
//								SupplierEvaluationResult evaluationResult = supplier.getSupplierEvaluationResult();
//								if (null != evaluationResult) {
//									String supplierOpinion = evaluationResult.getEvaluationOpinion();
//									if (null != supplierOpinion) {
//										return supplierOpinion;
//									}
//								}
							}
						}
						
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 设置单元格编辑器
		final KTableCellEditorGRadio radio = new KTableCellEditorGRadio();
		radio.setSingleClickEdit(true);
		radio.addItem(EVAL_ACCESSMENT_YES);
		radio.addItem(EVAL_ACCESSMENT_NO);
		final KTableCellEditorMultilineWrapText cellEditorText = new KTableCellEditorMultilineWrapText();
		cellEditorText.setTextLimit(500);
		cellEditorText.setSingleClickEdit(true);
		CellEditorRender cellEditorRender = new CellEditorRender() {
			public Object receiveCellEditor(int row, int col) {
				if (row >= commKTableModel.getFixedRowCount()) {
					if (col == 1) {
						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 == 2) {
//						return cellEditorText;
//						return new KTableCellEditorAction(null, new CellEventActionRender(){
//							public void receiveAction(int row, int col) {
//								Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
//								ExpertEvaluationResult expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
//								if (null != expertEvaluationResult) {
//									SupplierEvaluationResult evaluationResult = supplier.getSupplierEvaluationResult();
//									EvaluationOpinionDialog dialog = new EvaluationOpinionDialog(getShell(), tenderProjectEntity, supplier, Constants.CUR_USER, expertEvaluationResult);
//									dialog.open();
//									evaluationResult.setEvaluationOpinion(expertEvaluationResult.getSupplierOpinion());
//								}
//							}
//						});
						
					}
				}
				return null;
			}
		};
		commKTableModel.setCellEditorRender(cellEditorRender);
		
		// 编辑单元格内容
		CellEditContentRender editContentRender = new CellEditContentRender() {
			public void receiveContent(int row, int col, Object content) {
				if (null == content) return;
				if (row >= commKTableModel.getFixedRowCount()) {
					int supplierIndex = row - commKTableModel.getFixedRowCount();
					Supplier supplier = supplierList.get(supplierIndex);
					ExpertEvaluationResult expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
					if (null != expertEvaluationResult) {
						if (col == 1) {
							expertEvaluationResult.setAccessment(content.toString());
							SupplierEvaluationResult evaluationResult = supplier.getSupplierEvaluationResult();
							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();
								evaluationResult.setEvaluationOpinion(expertEvaluationResult.getSupplierOpinion());
							}else {
								evaluationResult.setEvaluationOpinion(null);
							}
						} 
//						else if (col == 2) {
//							SupplierEvaluationResult evaluationResult = supplier.getSupplierEvaluationResult();
//							if (null != evaluationResult) {
//								evaluationResult.setEvaluationOpinion(content.toString());
//							}
//							expertEvaluationResult.setSupplierOpinion(content.toString());
//						}
					}
				}
			}
		};
		commKTableModel.setCellEditContentRender(editContentRender);
		
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				if (row >= commKTableModel.getFixedRowCount()) {
					if (col == 1) {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
					} else {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					}
				}
				return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
		// 设置单元格渲染器
		CellRender cellRender = new CellRender() {
			public Object receiveCellRender(int row, int col) {
				if (commKTableModel.isFixedCell(col, row)) {
					return new FixedWrapCellRenderer();
				} else {
					return new TextWrapCellRenderer();
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		// 设置单元格图片
		final Image editImage = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/edit.png");
		commKTableModel.setCellImageRender(new CellImageRender() {
			public Image receiveCellImage(int row, int col) {
				if (row > 0) {
					switch (col) {
						case 2: return editImage;
					}
				}
				return null;
			}
		});
		
		// 设置单元格前景颜色
		CellForegroundRender cellForegroundRender = new CellForegroundRender() {
			public Color receiveCellForeground(int row, int col) {
				if (row >= commKTableModel.getFixedRowCount()) {
					int supplierIndex = row - commKTableModel.getFixedRowCount();
					Supplier supplier = supplierList.get(supplierIndex);
					ExpertEvaluationResult expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
					if (null != expertEvaluationResult && null != expertEvaluationResult.getAccessment()) {
						if (col == 1) {
							if (expertEvaluationResult.getAccessment().equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.QUALIFIED)) {
								return SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN);
							} else if (expertEvaluationResult.getAccessment().equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.UNQUALIFIED)) {
								return SWTResourceManager.getColor(SWT.COLOR_RED);
							}
						}
					}
				}
				return null;
			}
		};
		commKTableModel.setCellForegroundRender(cellForegroundRender);
		resultKTable.setModel(commKTableModel);
		evaluationTableComposite.layout();
	}
	
	/**
	 * @Description: 保存评审结果
	 * @author chenxw
	 * @return
	 */
	public boolean saveVetoBidEvaluationResult() {
		return expertEvaluationStepService.saveVetoBidEvaluationResult(tenderProjectEntity.getId(), CURRENT_EXPERT.getUserId(), evaluationStep, expertEvaluationResultMap);
	}
	
	/**
	 * @Description: 提交评审结果
	 * @author chenxw
	 * @return
	 */
	public boolean submitVetoBidEvaluationResult() {
		return expertEvaluationStepService.submitVetoBidEvaluationResult(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
	}
}
