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

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
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 org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;

import com.gx.obe.ColorConstants;
import com.gx.obe.action.bean.Action;
import com.gx.obe.business.entity.ExpertEvaluationStep;
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.components.core.enumeration.CommonEnum;
import com.gx.obe.evaluation.step.dialog.ApplyReEvaluationDialog;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.DateUtils;
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.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.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;

/**
 * @Description: 
 * @author guoyr
 */
public class VetoBidEvaluationResultComposite extends Composite {

	private String EVAL_ACCESSMENT_YES = Messages.Qualified;
	private String EVAL_ACCESSMENT_NO = Messages.Unqualified;
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private Expert CURRENT_EXPERT;
	private String OPERATOR_USER_ID;
	private SupplierService supplierService = new SupplierService();
//	private ExpertEvaluationStepService expertEvaluationStepService ;
	private ExpertEvaluationResultService expertEvaluationResultService;
	private SupplierEvaluationResultService supplierEvaluationResultService ;
	private ExpertService expertService;
	private List<Supplier> supplierList;
	private boolean isShowObjectiveDialog = false;// 是否显示客观项评审意见信息。
	private String supplierName;
	private Map<String, Color> contentBackgroundMap = new HashMap<String, Color>();
	private Composite load_composite;
	private Label message_label;
	private ELink applyReEvaluation_link;
	private Composite message_composite;
	private HashMap<Integer, Supplier> supplierMap;
	private Map<String, ExpertEvaluationResult> expertEvaluationResultMap;
//	private Expert curEvaluationExpert;
	
	private ExpertEvaluationStepService expertEvaluationStepService = new ExpertEvaluationStepService();
	
	{
		LogUtils.logClass(VetoBidEvaluationResultComposite.class);
	}
	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public VetoBidEvaluationResultComposite(Composite parent,Action action, int style) {
		super(parent, style);
		this.tenderProjectEntity = action.getTenderProject();
		this.evaluationStep = (EvaluationStep)parent.getData("evaluationStep");
		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);
		
		message_composite = new Composite(this, SWT.NONE);
		GridLayout gl_composite_6 = new GridLayout(2, false);
		message_composite.setLayout(gl_composite_6);
		message_composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		message_label = new Label(message_composite, SWT.NONE);
		message_label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		message_label.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		message_label.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		
		applyReEvaluation_link = new ELink(message_composite, SWT.NONE);
		applyReEvaluation_link.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
		applyReEvaluation_link.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/hand.png"));
		applyReEvaluation_link.setText(Messages.Button_appllyForBack);
		applyReEvaluation_link.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				applyReEvaluationAction();
			}
		});
		
		Composite composite_2 = new Composite(this, SWT.NONE);
		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		composite_2.setBackground(ColorConstants.BORDER_LINE_COLOR);
		GridLayout gl_composite_2 = new GridLayout(1, false);
		gl_composite_2.marginHeight = 1;
		gl_composite_2.marginWidth = 1;
		composite_2.setLayout(gl_composite_2);
		
		load_composite = new Composite(composite_2, SWT.NONE);
		load_composite.setBackgroundMode(SWT.INHERIT_FORCE);
		load_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_load_composite = new GridLayout(1, false);
		gl_load_composite.verticalSpacing = 0;
		gl_load_composite.horizontalSpacing = 0;
		gl_load_composite.marginHeight = 0;
		gl_load_composite.marginWidth = 0;
		load_composite.setLayout(gl_load_composite);
		load_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		init();
	}
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		expertEvaluationResultService = new ExpertEvaluationResultService();
		supplierEvaluationResultService = new SupplierEvaluationResultService();
		expertService = new ExpertService();
		supplierName = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType());
		supplierList = supplierService.getEvaluationStepSupplierList(tenderProjectEntity.getId(), evaluationStep);
		if(null != OPERATOR_USER_ID && OPERATOR_USER_ID.equals(Constants.USER.getId())){
			applyReEvaluation_link.setText(MessageFormat.format(Messages.Button_appllyForBackFormat, evaluationStep.getStepName()));
		}else {
			applyReEvaluation_link.dispose();
		}
		
		CURRENT_EXPERT = expertService.getEvaluationStepExpert(tenderProjectEntity.getId(), evaluationStep);
		
		// 为了显示样式，没有投标人时生成临时投标人
		if(null == supplierList || supplierList.size() == 0){
			supplierList = new ArrayList<Supplier>();
			Supplier tempSupplier = new Supplier();
			tempSupplier.setSupplierName("                    ");
			supplierList.add(tempSupplier);
		}
		drawEvaluationTable();
	}
	
	/**
	 * @Description: 初始化评标结果
	 * @author guoyr
	 * @param userId 
	 */
	private void initEvaluationResult(){
		// 评审当前评标专家所有的评标结果
		List<ExpertEvaluationResult> queryExpertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
		contentBackgroundMap.clear();
		
		if(null != supplierMap){
			supplierMap.clear();
		}else {
			supplierMap = new HashMap<Integer, Supplier>();
		}
		if(null != expertEvaluationResultMap){
			expertEvaluationResultMap.clear();
		}else {
			expertEvaluationResultMap = new HashMap<String, ExpertEvaluationResult>();
		}
		
		List<SupplierEvaluationResult> supplierEvaluationResultList = supplierEvaluationResultService.getSupplierEvaluationResultListByTenderId( tenderProjectEntity.getId());
		
		for(Supplier supplier : supplierList){
			// 获取评标专家对投标人的评审记录
			if(null != queryExpertEvaluationResultList && queryExpertEvaluationResultList.size() > 0){
				for(ExpertEvaluationResult expertEvaluationResult : queryExpertEvaluationResultList){
					if(StringUtils.equals(expertEvaluationResult.getSupplierId(), supplier.getId())){
						expertEvaluationResultMap.put(supplier.getId(), expertEvaluationResult);
						break;
					}
				}
			}
			SupplierEvaluationResult supplierEvaluationResult = null;
			if(null != supplierEvaluationResultList && supplierEvaluationResultList.size() > 0){
				for(SupplierEvaluationResult evalResult : supplierEvaluationResultList){
					if(ObjectUtils.equals(evalResult.getSupplierId(), supplier.getId())){
						supplierEvaluationResult = evalResult;
						break;
					}
				}
			}
			supplier.setSupplierEvaluationResult(supplierEvaluationResult);
		}
	}
	
	private void drawEvaluationTable(){
		for(Control control : load_composite.getChildren()){
			control.dispose();
		}
		if(!applyReEvaluation_link.isDisposed()){
			applyReEvaluation_link.setVisible(false);
		}
		StringBuilder msg = new StringBuilder();
		ExpertEvaluationStep expertEvaluationStep = expertEvaluationStepService.getExpertEvaluationStep(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
		if(null != expertEvaluationStep){
			msg.append("[");
			msg.append(evaluationStep.getStepName());
			msg.append("]");
			msg.append(Messages.EvalStartTime);
			msg.append("：");
			msg.append(null != expertEvaluationStep.getStartTime()?DateUtils.getTimestampFormat(expertEvaluationStep.getStartTime()):"");
			msg.append("---");
			if(ObjectUtils.equals(expertEvaluationStep.getStepStatus(), CommonEnum.COMPLETE)){
				msg.append(Messages.EvalEndTime);
				msg.append("：");
				msg.append(null != expertEvaluationStep.getEndTime()?DateUtils.getTimestampFormat(expertEvaluationStep.getEndTime()):"");
				if(!applyReEvaluation_link.isDisposed()){
					applyReEvaluation_link.setVisible(true);
					applyReEvaluation_link.setData("expertEvaluationStep", expertEvaluationStep);
				}
			}else {
				msg.append(MessageFormat.format(Messages.Tips_progressIn, evaluationStep.getStepName()));
			}
		}else {
			msg.append(MessageFormat.format(Messages.Tips_progressNotStart, evaluationStep.getStepName()));
		}
		
		initEvaluationResult();
		drawRankEvaluationTable();
		message_label.setText(msg.toString());
		message_composite.layout();
		load_composite.layout();
	}
	
	private void drawRankEvaluationTable() {
		KTable resultKTable = new KTable(load_composite, 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() , 2);
//		commKTableModel.setColumnMinWidth(1, 50);
		commKTableModel.setColumnWidth(1, 50);
		commKTableModel.setColumnWidth(2, 300);
		commKTableModel.setColumnMaxWidth(2, 500);
		
		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) {
								String supplierOpinion = expertEvaluationResult.getSupplierOpinion();
								if (null != supplierOpinion) {
									return supplierOpinion;
								}
							}
						}
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 编辑单元格对齐方式
		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);
		
		// 设置单元格前景颜色
		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) {
						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);
	}

	/**
	 * @Description: 申请回退
	 * @author guoyr 
	 */
	private void applyReEvaluationAction(){
		if(applyReEvaluation_link.getEnabled()){
			if(null != applyReEvaluation_link.getData("expertEvaluationStep")){
				ExpertEvaluationStep expertEvaluationStep = (ExpertEvaluationStep)applyReEvaluation_link.getData("expertEvaluationStep");
				if(null != expertEvaluationStep){
					ApplyReEvaluationDialog applyReEvaluationDialog = new ApplyReEvaluationDialog(getShell(), evaluationStep, expertEvaluationStep);
					applyReEvaluationDialog.open();
				}
			}
		}
	}
	
	public boolean isShowObjectiveDialog() {
		return isShowObjectiveDialog;
	}
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
