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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.listener.RoundBorderLineListener;
import org.eclipse.swt.core.utils.WidgetUtils;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.entity.SupplierEvaluationFactor;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.button.EvaluationButton;
import com.gx.obe.components.core.Constants;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.evaluation.EvaluationFactor;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.SupplierEvaluationFactorService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

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

/**
 * @Description: 标书清标（评议）意见
 * @author guoyr
 */
public class CompareEvaluationTableComposite extends Composite {
	
	private SupplierEvaluationFactorService supplierEvaluationFactorService = new SupplierEvaluationFactorService();
	
	private ImageResolver imageResolver = new ImageResolver();
	
	private Composite evaluationComposite;
	private Composite evaluationTableComposite;
	private EvaluationButton submit_result_btn;
	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
	
	private boolean isViewSupplierOpinion;
	private boolean editFlag;
	
	private TenderProjectEntity tenderProject;
	private List<Supplier> supplierList;
	private List<EvaluationFactor> evaluationTopFactorList;
	
	private int maxLevel;
	private List<EvaluationFactor> evaluationFactorList = new ArrayList<EvaluationFactor>();
	private EvaluationFactor singleEvaluationFactor;
	private boolean showSingleEvaluationFactor = true;
	// 记录供应商每个指标的评审结果
	private Map<String, Map<String, SupplierEvaluationFactor>> supplierEvaluationFactorResultMap;
	
	private int fontSize = 9;
	private int maxFactorNameLength = 30;
	
	public static int defaultAllFactorWidth = 200;
	public static int defaultSingleFactorWidth = 150;

	private ELink showAllFactorLink;

	private Composite titleComposite;

	private Label factorNameLabel;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public CompareEvaluationTableComposite(Composite parent, int style, boolean isViewSupplierOpinion, boolean editFlag) {
		super(parent, style);
		
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		
		this.isViewSupplierOpinion = isViewSupplierOpinion;
		this.editFlag = editFlag;
		
		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);
		
		titleComposite = new Composite(evaluationComposite, SWT.NONE);
		titleComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		titleComposite.setLayout(new GridLayout(5, false));
		titleComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		factorNameLabel = new Label(titleComposite, SWT.WRAP);
		factorNameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		factorNameLabel.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		factorNameLabel.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
		
		showAllFactorLink = new ELink(titleComposite, SWT.NONE);
		showAllFactorLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/change.png"));
		showAllFactorLink.setText("显示当前指标");
		showAllFactorLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				changeSingleFactor();
			}
		});
		showAllFactorLink.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		ELink addWidthLink = new ELink(titleComposite, SWT.NONE);
		addWidthLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/enlarge_width.png"));
		addWidthLink.setText(Messages.Button_enlargeColumnWidth);
		addWidthLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				reSizeColumnWidth(true);
			}
		});
		addWidthLink.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		ELink reduceWidthLink = new ELink(titleComposite, SWT.NONE);
		reduceWidthLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/reduce_width.png"));
		reduceWidthLink.setText(Messages.Button_reducedColumnWidth);
		reduceWidthLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				reSizeColumnWidth(false);
			}
		});
		reduceWidthLink.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		new Label(titleComposite, SWT.NONE);
		
//		ESepator sep = new ESepator(evaluationComposite, SWT.NONE);
//		sep.setBackground(ColorConstants.BORDER_LINE_COLOR);
//		sep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		evaluationTableComposite = new Composite(evaluationComposite, SWT.NONE);
		evaluationTableComposite.addPaintListener(new RoundBorderLineListener(ColorConstants.BORDER_LINE_COLOR));
		FillLayout fl_evaluationTableComposite = new FillLayout(SWT.HORIZONTAL);
		fl_evaluationTableComposite.marginHeight = 1;
		fl_evaluationTableComposite.marginWidth = 1;
		evaluationTableComposite.setLayout(fl_evaluationTableComposite);
		evaluationTableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		init();
	}
	
	/**
	 * @Description:
	 * @author guoyr
	 */
	public void init() {
		if (isViewSupplierOpinion && editFlag) {
			ESepator factor_sep = new ESepator(evaluationComposite, SWT.NONE);
			factor_sep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
			factor_sep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
			
			Composite composite = new Composite(evaluationComposite, SWT.NONE);
			RowLayout rl_composite = new RowLayout(SWT.HORIZONTAL);
			rl_composite.justify = true;
			rl_composite.fill = true;
			rl_composite.spacing = 5;
			composite.setLayout(rl_composite);
			composite.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, false, 1, 1));
			
			submit_result_btn = new EvaluationButton(composite, SWT.NONE);
			submit_result_btn.addMouseListener(new MouseAdapter() {
				public void mouseUp(MouseEvent e) {
					saveEvaluationFactorResultBySupplier();
				}
			});
			submit_result_btn.setText(Messages.Button_save);
			submit_result_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/save.png"));
		}
	}
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	public void refresh(TenderProjectEntity tenderProject, List<Supplier> supplierList, List<EvaluationFactor> evaluationTopFactorList) {
		refresh(tenderProject, supplierList, evaluationTopFactorList, null);
	}
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	public void refresh(TenderProjectEntity tenderProject, List<Supplier> supplierList, List<EvaluationFactor> evaluationTopFactorList, EvaluationFactor evaluationFactor) {
		WidgetUtils.setControlVisible(titleComposite, true);
		this.tenderProject = tenderProject;
		this.supplierList = supplierList;
		if(null == evaluationTopFactorList){
			evaluationTopFactorList = new ArrayList<EvaluationFactor>();
		}
		this.evaluationTopFactorList = evaluationTopFactorList;
		this.singleEvaluationFactor = evaluationFactor;
		
//		if (PropertiesUtils.getProperty("showSingleFactorOpinion", "01").equals("01") && null != singleEvaluationFactor) {
		if(null == singleEvaluationFactor){
			WidgetUtils.setControlVisible(showAllFactorLink, false);
		} else {
			WidgetUtils.setControlVisible(showAllFactorLink, true);
		}
		
		if (null != singleEvaluationFactor && showSingleEvaluationFactor) {
			evaluationFactorList.clear();
			evaluationFactorList.add(singleEvaluationFactor);
			initBidFileOpinionResult();
			drawSingleFactorEvaluationTable();
			showAllFactorLink.setText(Messages.Button_showAllFactors);
//			factorNameLabel.setText(ObjectUtils.getObjString(singleEvaluationFactor.getFactorName()));
			factorNameLabel.setText(Messages.Button_bidFileOpinion);
		}else {
			factorNameLabel.setText(Messages.Button_bidFileOpinion);
			showAllFactorLink.setText(Messages.Button_showOneFactor);
			initEvaluationStepFactor();
			initBidFileOpinionResult();
			drawLeftFactorEvaluationTable();
		}
		titleComposite.layout();
		evaluationComposite.layout();
	}
	
	/**
	 * @Description: 初始化评标结果
	 * @author guoyr
	 */
	private void initBidFileOpinionResult() {
		
		
		// 记录供应商每个指标的评审结果
		supplierEvaluationFactorResultMap = new HashMap<String, Map<String, SupplierEvaluationFactor>>();
		
		List<SupplierEvaluationFactor> evalFactorResultList = supplierEvaluationFactorService.getEntityListByTenderId(tenderProject.getId());
		if (null == evalFactorResultList) evalFactorResultList = new ArrayList<SupplierEvaluationFactor>();
		
		for (Supplier supplier : supplierList) {
			List<SupplierEvaluationFactor> supplierEvaluationFactorList = new ArrayList<SupplierEvaluationFactor>();
			for (SupplierEvaluationFactor supplierEvaluationFactor : evalFactorResultList)
				if (supplier.getId().equals(supplierEvaluationFactor.getSupplierId())) supplierEvaluationFactorList.add(supplierEvaluationFactor);
			// 获取评标专家对投标人的评审记录
			Map<String, SupplierEvaluationFactor> evaluationFactorResultMap = new HashMap<String, SupplierEvaluationFactor>();
			for (final EvaluationFactor evaluationFactor : evaluationFactorList) {
				if (null == evaluationFactor.getFactorCode()) evaluationFactor.setFactorCode(evaluationFactor.getId());
				SupplierEvaluationFactor evalFactorResult = CollectionUtils.get(supplierEvaluationFactorList, t -> {
					return evaluationFactor.getFactorCode().equals(t.getFactorCode());
				});
				if (null == evalFactorResult) {
					evalFactorResult = new SupplierEvaluationFactor();
					evalFactorResult.setTenderId(tenderProject.getId());
					evalFactorResult.setSupplierId(supplier.getId());
					evalFactorResult.setFactorName(evaluationFactor.getFactorName());
					evalFactorResult.setFactorCode(evaluationFactor.getFactorCode());
				}
				evaluationFactorResultMap.put(evaluationFactor.getId(), evalFactorResult);
			}
			supplierEvaluationFactorResultMap.put(supplier.getId(), evaluationFactorResultMap);
		}
	}
	
	/**
	 * @Description: 初始化当前评标步骤的评审指标
	 * @author guoyr
	 */
	private void initEvaluationStepFactor() {
		evaluationFactorList.clear();
		maxLevel = 1;
		if (CollectionUtils.isNotNull(evaluationTopFactorList)) for (EvaluationFactor topFactor : evaluationTopFactorList)
			initAddChildEvaluationFactor(topFactor);
	}
	
	/**
	 * @Description: 递归获取所有的评审叶子指标
	 * @author guoyr
	 * @param evalFactor
	 */
	private void initAddChildEvaluationFactor(EvaluationFactor evalFactor) {
		if (CollectionUtils.isNotNull(evalFactor.getChildFactorList())) {
			for (EvaluationFactor childFactor : evalFactor.getChildFactorList()) {
				childFactor.setLevel(evalFactor.getLevel() + 1);
				initAddChildEvaluationFactor(childFactor);
			}
		} else {
			maxLevel = Math.max(maxLevel, evalFactor.getLevel());
			evaluationFactorList.add(evalFactor);
		}
	}
	
	private void changeSingleFactor(){
		showSingleEvaluationFactor = !showSingleEvaluationFactor;
		refresh(tenderProject, supplierList, evaluationTopFactorList, singleEvaluationFactor);
	}
	
	/**
	 * @Description: 左边是评审指标表格
	 * @author guoyr
	 */
	private void drawLeftFactorEvaluationTable() {
		showSingleEvaluationFactor = false;
		if (null != resultKTable && !resultKTable.isDisposed()) {
			resultKTable.dispose();
		}
		
		resultKTable = new KTable(evaluationTableComposite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY);
		commKTableModel = new CommonKtableCModel(resultKTable, 1, maxLevel, evaluationFactorList.size(), supplierList.size());
		commKTableModel.addColSpan(0, 0, commKTableModel.getFixedColumnCount());
		
		final Map<String, String> tableTitleMap = new HashMap<String, String>();
		tableTitleMap.put("0_0", Messages.EvalFactor);
		int col = commKTableModel.getFixedColumnCount();
		for (Supplier supplier : supplierList) {
			tableTitleMap.put("0_" + col, supplier.getSupplierName());
			commKTableModel.setColumnWidth(col, defaultAllFactorWidth);
			col++;
		}
		
		commKTableModel.setRowHeight(0, 25);
		for(int row = 1; row < commKTableModel.getRowCount(); row ++){
			commKTableModel.setRowHeight(row, 50);
		}
		
		String parentId = "";
		int childCount = 0;
		for (col = 0; col < maxLevel; col++) {
			commKTableModel.addRowSpan(0, col, commKTableModel.getFixedRowCount());
			if (col == maxLevel - 1) {
				// 将指标的最后一列设置宽一点
				commKTableModel.setColumnMaxWidth(col, 200);
			} else {
				commKTableModel.setColumnMaxWidth(col, 150);
			}
			int row = commKTableModel.getFixedRowCount();
			for (EvaluationFactor evaluationFactor : evaluationFactorList) {
				EvaluationFactor parentFactor = getParentFactor(evaluationFactor, col + 1);
				if (null != parentFactor && StringUtils.isNotEmpty(parentFactor.getId())) {
					if (!parentId.equals(parentFactor.getId())) {
						childCount = 0;
					}
					if (childCount++ == 0) {
						commKTableModel.addRowSpan(row, col, getChildCount(parentFactor));
					}
					parentId = parentFactor.getId();
					tableTitleMap.put(row + "_" + col, maxFactorNameLength > 0 ? parentFactor.getFactorName().substring(0, Math.min(maxFactorNameLength, parentFactor.getFactorName().length())) : parentFactor.getFactorName());
				} else {
					childCount = 0;
					tableTitleMap.put(row + "_" + col, maxFactorNameLength > 0 ? evaluationFactor.getFactorName().substring(0, Math.min(maxFactorNameLength, evaluationFactor.getFactorName().length())) : evaluationFactor.getFactorName());
				}
				if (col + 1 == evaluationFactor.getLevel()) {
					commKTableModel.addColSpan(row, col, commKTableModel.getFixedColumnCount() - col);
				}
				if (col < commKTableModel.getFixedColumnCount()) {
					if (null != evaluationFactor) {
						tableTitleMap.put(row + "_" + (maxLevel - 1), maxFactorNameLength > 0 ? evaluationFactor.getFactorName().substring(0, Math.min(maxFactorNameLength, evaluationFactor.getFactorName().length())) : evaluationFactor.getFactorName());
					}
				}
				row++;
			}
		}
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender() {
			public Object receiveContent(int row, int col) {
				// 表头
				if (col < commKTableModel.getFixedColumnCount()) {
					if (row < commKTableModel.getFixedRowCount()) {
						return Messages.EvalFactor;
					} else if (row < commKTableModel.getFixedRowCount() + evaluationFactorList.size() && col == commKTableModel.getFixedColumnCount() - 1) {
						EvaluationFactor evaluationFactor = evaluationFactorList.get(row - commKTableModel.getFixedRowCount());
						if (col == commKTableModel.getFixedColumnCount() - 1 && resultKTable.isLockedRow(row)) {
							return (maxFactorNameLength > 0 ? evaluationFactor.getFactorName().substring(0, Math.min(maxFactorNameLength, evaluationFactor.getFactorName().length())) : evaluationFactor.getFactorName()) + "\r\n[已锁定]";
						} else {
							return maxFactorNameLength > 0 ? evaluationFactor.getFactorName().substring(0, Math.min(maxFactorNameLength, evaluationFactor.getFactorName().length())) : evaluationFactor.getFactorName();
						}
					} else if (null != tableTitleMap.get(row + "_" + col)) {
						return tableTitleMap.get(row + "_" + col);
					}
				} else if (col < commKTableModel.getFixedColumnCount() + supplierList.size()) {
					Supplier supplier = supplierList.get(col - commKTableModel.getFixedColumnCount());
					if (row < commKTableModel.getFixedRowCount()) {
						return (col - commKTableModel.getFixedColumnCount() + 1) + "、" + supplier.getSupplierName();
					} else if (row < commKTableModel.getFixedRowCount() + evaluationFactorList.size()) {
						EvaluationFactor evaluationFactor = evaluationFactorList.get(row - commKTableModel.getFixedRowCount());
						SupplierEvaluationFactor evalFactorResult = supplierEvaluationFactorResultMap.get(supplier.getId()).get(evaluationFactor.getId());
						if (isViewSupplierOpinion) {
							if (null != evalFactorResult.getOpinion()) {
								return evalFactorResult.getOpinion();
							}
						} else {
							if (null != evalFactorResult.getFactorResponse()) {
								return evalFactorResult.getFactorResponse();
							}
						}
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 设置单元格渲染器
		final FixedWrapCellRenderer fixedWrapCellRenderer = new FixedWrapCellRenderer();
		final TextWrapCellRenderer textWrapCellRenderer = new TextWrapCellRenderer();
		CellRender cellRender = new CellRender() {
			public Object receiveCellRender(int row, int col) {
				if (commKTableModel.isFixedCell(col, row)) {
					fixedWrapCellRenderer.setFont(SWTResourceManager.getFont("微软雅黑", fontSize, SWT.NORMAL));
					return fixedWrapCellRenderer;
				} else {
					textWrapCellRenderer.setFont(SWTResourceManager.getFont("微软雅黑", fontSize + 1, SWT.NORMAL));
					return textWrapCellRenderer;
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		if (isViewSupplierOpinion && editFlag) {
			
			// 设置单元格编辑器
			final KTableCellEditorMultilineWrapText text = new KTableCellEditorMultilineWrapText();
			text.setSingleClickEdit(true);
			CellEditorRender cellEditorRender = new CellEditorRender() {
				public Object receiveCellEditor(int row, int col) {
					if (col >= commKTableModel.getFixedColumnCount() && col < commKTableModel.getFixedColumnCount() + supplierList.size() && row >= commKTableModel.getFixedRowCount() && row < commKTableModel.getFixedRowCount() + evaluationFactorList.size()) {
						return text;
					}
					return null;
				}
			};
			commKTableModel.setCellEditorRender(cellEditorRender);
			
			// 编辑单元格内容
			CellEditContentRender editContentRender = new CellEditContentRender() {
				public void receiveContent(int row, int col, Object content) {
					Supplier supplier = supplierList.get(col - commKTableModel.getFixedColumnCount());
					EvaluationFactor evaluationFactor = evaluationFactorList.get(row - commKTableModel.getFixedRowCount());
					SupplierEvaluationFactor evalFactorResult = supplierEvaluationFactorResultMap.get(supplier.getId()).get(evaluationFactor.getId());
					if (null != evalFactorResult) {
						if (null != content && content.toString().length() > 0) {
							evalFactorResult.setOpinion(content.toString());
						} else {
							evalFactorResult.setOpinion(null);
						}
					}
					resultKTable.redraw();
				}
			};
			commKTableModel.setCellEditContentRender(editContentRender);
		}
		
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					if(col < commKTableModel.getFixedColumnCount()){
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					}else {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
					}
				}else {
					return SWTX.ALIGN_VERTICAL_TOP | SWTX.ALIGN_HORIZONTAL_LEFT;
				}
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
//		resultKTable.addCellSelectionListener(new KTableCellSelectionAdapter(){
//			@Override
//			public void cellSelected(int col, int row, int statemask) {
//				EvaluationFactor evaluationFactor = evaluationFactorList.get(row - commKTableModel.getFixedRowCount());
//			}
//			@Override
//			public void fixedCellSelected(int col, int row, int statemask) {
//				EvaluationFactor evaluationFactor = evaluationFactorList.get(row - commKTableModel.getFixedRowCount());
//			}
//		});
//		
		resultKTable.setModel(commKTableModel);
		evaluationTableComposite.layout();
		resultKTable.addControlListener(new ControlAdapter() {
			public void controlResized(ControlEvent e) {
				if(null != resultKTable && !resultKTable.isDisposed()){
					resultKTable.autoComputerColumnWidth();
					defaultAllFactorWidth = Math.max(defaultAllFactorWidth, commKTableModel.getColumnWidth(commKTableModel.getFixedColumnCount()));
				}
			}
		});
	}
	
	private void drawSingleFactorEvaluationTable() {
		showSingleEvaluationFactor = true;
		if (null != resultKTable && !resultKTable.isDisposed()) {
			resultKTable.dispose();
		}
		
		resultKTable = new KTable(evaluationTableComposite, SWTX.AUTO_SCROLL | SWTX.EDIT_ON_KEY);
		commKTableModel = new CommonKtableCModel(resultKTable, 1, 0, 1, supplierList.size());
		commKTableModel.addColSpan(0, 0, commKTableModel.getFixedColumnCount());
		
		final Map<String, String> tableTitleMap = new HashMap<String, String>();
		int col = commKTableModel.getFixedColumnCount();
		for (Supplier supplier : supplierList) {
			tableTitleMap.put("0_" + col, supplier.getSupplierName());
			commKTableModel.setColumnWidth(col, defaultSingleFactorWidth);
			col++;
		}
		commKTableModel.setRowHeight(0, 25);
		commKTableModel.setRowHeight(1, 100);
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender() {
			public Object receiveContent(int row, int col) {
				// 表头
				if (col < commKTableModel.getFixedColumnCount()) {
					return tableTitleMap.get(row + "_" + col);
				} else if (col < commKTableModel.getFixedColumnCount() + supplierList.size()) {
					Supplier supplier = supplierList.get(col - commKTableModel.getFixedColumnCount());
					if (row < commKTableModel.getFixedRowCount()) {
						return (col - commKTableModel.getFixedColumnCount() + 1) + "、" + supplier.getSupplierName();
					} else if (row < commKTableModel.getFixedRowCount() + evaluationFactorList.size()) {
						SupplierEvaluationFactor evalFactorResult = supplierEvaluationFactorResultMap.get(supplier.getId()).get(singleEvaluationFactor.getId());
						if (isViewSupplierOpinion) {
							if (null != evalFactorResult.getOpinion()) {
								return evalFactorResult.getOpinion();
							}
						} else {
							if (null != evalFactorResult.getFactorResponse()) {
								return evalFactorResult.getFactorResponse();
							}
						}
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 设置单元格渲染器
		final FixedWrapCellRenderer fixedWrapCellRenderer = new FixedWrapCellRenderer();
		final TextWrapCellRenderer textWrapCellRenderer = new TextWrapCellRenderer();
		CellRender cellRender = new CellRender() {
			public Object receiveCellRender(int row, int col) {
				if (commKTableModel.isFixedCell(col, row)) {
					fixedWrapCellRenderer.setFont(SWTResourceManager.getFont("微软雅黑", fontSize, SWT.NORMAL));
					return fixedWrapCellRenderer;
				} else {
					textWrapCellRenderer.setFont(SWTResourceManager.getFont("微软雅黑", fontSize + 1, SWT.NORMAL));
					return textWrapCellRenderer;
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		if (isViewSupplierOpinion && editFlag) {
			
			// 设置单元格编辑器
			final KTableCellEditorMultilineWrapText text = new KTableCellEditorMultilineWrapText();
			text.setSingleClickEdit(true);
			CellEditorRender cellEditorRender = new CellEditorRender() {
				public Object receiveCellEditor(int row, int col) {
					if (col >= commKTableModel.getFixedColumnCount() && col < commKTableModel.getFixedColumnCount() + supplierList.size() && row >= commKTableModel.getFixedRowCount() && row < commKTableModel.getFixedRowCount() + evaluationFactorList.size()) {
						return text;
					}
					return null;
				}
			};
			commKTableModel.setCellEditorRender(cellEditorRender);
			
			// 编辑单元格内容
			CellEditContentRender editContentRender = new CellEditContentRender() {
				public void receiveContent(int row, int col, Object content) {
					Supplier supplier = supplierList.get(col - commKTableModel.getFixedColumnCount());
					SupplierEvaluationFactor evalFactorResult = supplierEvaluationFactorResultMap.get(supplier.getId()).get(singleEvaluationFactor.getId());
					if (null != evalFactorResult) {
						if (null != content && content.toString().length() > 0) {
							evalFactorResult.setOpinion(content.toString());
						} else {
							evalFactorResult.setOpinion(null);
						}
					}
					resultKTable.redraw();
				}
			};
			commKTableModel.setCellEditContentRender(editContentRender);
		}
		
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				}
				return SWTX.ALIGN_VERTICAL_TOP | SWTX.ALIGN_HORIZONTAL_LEFT;
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
//		resultKTable.addCellSelectionListener(new KTableCellSelectionAdapter(){
//			@Override
//			public void cellSelected(int col, int row, int statemask) {
//				EvaluationFactor evaluationFactor = evaluationFactorList.get(row - commKTableModel.getFixedRowCount());
//			}
//			@Override
//			public void fixedCellSelected(int col, int row, int statemask) {
//				EvaluationFactor evaluationFactor = evaluationFactorList.get(row - commKTableModel.getFixedRowCount());
//			}
//		});
//		
		resultKTable.setModel(commKTableModel);
		evaluationTableComposite.layout();
		resultKTable.redraw();
		resultKTable.addControlListener(new ControlAdapter() {
			public void controlResized(ControlEvent e) {
				if(null != resultKTable && !resultKTable.isDisposed()){
					resultKTable.autoComputerColumnWidth();
					defaultSingleFactorWidth = Math.max(defaultSingleFactorWidth, commKTableModel.getColumnWidth(commKTableModel.getFixedColumnCount()));
				}
			}
		});
	}
	
	
	private void reSizeColumnWidth(boolean addWidth){
		int columnWidth = defaultAllFactorWidth;
		if(showSingleEvaluationFactor){
			columnWidth = defaultSingleFactorWidth;
		}
		columnWidth += (addWidth ? 50 : -50);
		if(columnWidth < 100){
			columnWidth = 100;
			MessageDialog.openShortMessage("已到最小宽度！");
		}else if(columnWidth > 800){
			columnWidth = 800;
			MessageDialog.openShortMessage("已到最大宽度！");
			return;
		}
		commKTableModel.setRowHeight(0, 25);
		if(!showSingleEvaluationFactor && addWidth){
			for(int row = 1; row < commKTableModel.getRowCount(); row ++){
				int rowHeight = commKTableModel.getRowHeight(row);
				rowHeight -= 20;
				if(rowHeight < 50){
					rowHeight = 50;
				}
				commKTableModel.setRowHeight(row, rowHeight);
			}
		}
		for (int col = commKTableModel.getFixedColumnCount() ; col < commKTableModel.getColCount(); col ++) {
			commKTableModel.setColumnWidth(col, columnWidth);
		}
		if(showSingleEvaluationFactor){
			defaultSingleFactorWidth = columnWidth;
		}else {
			defaultAllFactorWidth = columnWidth;
		}
		resultKTable.autoComputerColumnWidth();
	}
	
	/**
	 * @Description: 递归获取当前指标指定上级如果上级为空则为本身
	 * @author guoyr
	 * @param factor
	 * @param row
	 * @return
	 */
	private EvaluationFactor getParentFactor(EvaluationFactor evaluationFactor, int level) {
		EvaluationFactor parent = evaluationFactor.getParentFactor();
		if (null != parent) {
			if (parent.getLevel() == level) {
				return parent;
			} else if (parent.getLevel() > level) {
				return getParentFactor(parent, level);
			} else {
				return evaluationFactor;
			}
		}
		return parent;
	}
	
	/**
	 * @Description: 递归获取当前指标的所有下级指标的个数
	 * @author guoyr
	 * @param factor
	 * @return
	 */
	private int getChildCount(EvaluationFactor evaluationFactor) {
		List<EvaluationFactor> childrenList = evaluationFactor.getChildFactorList();
		int childCount = null != childrenList ? childrenList.size() : 0;
		if (childCount > 0) {
			for (EvaluationFactor childrenFactor : childrenList) {
				List<EvaluationFactor> subChildrenList = childrenFactor.getChildFactorList();
				if (null != subChildrenList && subChildrenList.size() > 0) {
					childCount--;
					childCount += getChildCount(childrenFactor);
				}
			}
		}
		return childCount;
	}
	
	/**
	 * @Description: 保存按供应商打分结果
	 * @author guoyr
	 */
	private void saveEvaluationFactorResultBySupplier() {
		new Thread(new Runnable() {
			public void run() {
				List<SupplierEvaluationFactor> supplierEvaluationFactorList = new ArrayList<SupplierEvaluationFactor>();
				for (Supplier supplier : supplierList) {
					Map<String, SupplierEvaluationFactor> supplierFactorResultMap = supplierEvaluationFactorResultMap.get(supplier.getId());
					for (Entry<String, SupplierEvaluationFactor> resultEntry : supplierFactorResultMap.entrySet()) {
						SupplierEvaluationFactor evaluationFactorResult = resultEntry.getValue();
						if (null == evaluationFactorResult.getFactorResponse() || evaluationFactorResult.getFactorResponse().length() == 0) {
							continue;
						}
						supplierEvaluationFactorList.add(evaluationFactorResult);
					}
				}
				final int flag = supplierEvaluationFactorService.batchSaveOrUpdate(supplierEvaluationFactorList);
				Display.getDefault().syncExec(new Runnable() {
					public void run() {
						if (flag > 0) {
							MessageDialog.openShortMessage(Messages.Tips_saveSuccess);
						} else {
							MessageDialog.openError(getShell(), Messages.Tips_saveFail);
						}
					}
				});
			}
		}).start();
	}
	
	/**
	 * @Description: 调整列大小
	 * @author chenxw
	 * @param width
	 */
	public void resizeColumn(int width) {
		for (int i = commKTableModel.getFixedColumnCount(); i < commKTableModel.getColCount(); i++) {
			commKTableModel.setColumnWidth(i, width);
		}
		resultKTable.autoComputerColumnWidth();
	}
	
	/**
	 * @Description: 设置表格中的字体大小
	 * @author guoyr
	 * @param fontSize
	 */
	public void setTableFontSize(int fontSize) {
		this.fontSize = fontSize;
		resultKTable.refreshRowResize(0, commKTableModel.getRowCount() - 1);
		resultKTable.redraw();
	}
	
	/**
	 * @Description: 关闭编辑器
	 * @author guoyr
	 */
	public void closeCellEditor() {
		if (null != resultKTable) {
			resultKTable.closeCellEditor();
		}
	}
	
	/**
	 * @Description: 切换评分面板
	 * @author guoyr
	 */
	public void switchCoordinateAction() {
		if (null != resultKTable && !resultKTable.isDisposed()) {
			resultKTable.dispose();
		}
		Constants.FACTOR_IS_HORIZONTAL = !Constants.FACTOR_IS_HORIZONTAL;
		if (Constants.FACTOR_IS_HORIZONTAL) {
			drawLeftFactorEvaluationTable();
		} else {
//			drawLeftSupplierEvaluationTable();
		}
		evaluationTableComposite.layout();
	}
	
	/**
	 * @Description: 释放资源
	 * @author guoyr
	 */
	public void dispose() {
		imageResolver.disposite();
		evaluationFactorList.clear();
		evaluationFactorList = null;
		super.dispose();
	}
	
	protected void checkSubclass() {}
	
}
