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


import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.IOException;
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.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.gx.obe.ColorConstants;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.button.EvalLeftButton;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18N;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.components.core.enumeration.EvaluationFactorEnum;
import com.gx.obe.components.core.enumeration.EvaluationStepEnum;
import com.gx.obe.components.core.enumeration.TenderProjectEnum;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.evaluation.step.dialog.CreditChinaDialog;
import com.gx.obe.evaluation.step.dialog.CreditChinaDialog2;
import com.gx.obe.evaluation.step.inter.ITianYanCheckComposite;
import com.gx.obe.evaluation.step.listener.ExpertEvaluationListener;
import com.gx.obe.evaluation.step.listener.PriceReviewEvaluationListener;
import com.gx.obe.http.json.JsonUtil;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.Keys;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.ScreenUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.util.utils.UuidUtils;
import com.gx.obe.web.entity.CheckResult;
import com.gx.obe.web.entity.Supplier;
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.CheckResultService;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.TenderProjectService;
import com.gx.obe.web.service.evaluation.EvaluationStepService;
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.gx.tools.ole.DocumentFactory;
import com.gx.tools.ole.DocumentLoader;
import com.gx.utils.ActionLogUtils;
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.CellRender;
import de.kupzog.ktable.renderers.FixedWrapCellRenderer;
import de.kupzog.ktable.renderers.TextWrapCellRenderer;

/** 
 * @Description: 天眼查关联关系
 * @author wangx 
 */
public class TianYanCheckComposite extends Composite implements ITianYanCheckComposite{
	{
		LogUtils.logClass(TianYanCheckComposite.class);
	}
	private SupplierService supplierService = new SupplierService();
	private TenderProjectService tenderProjectService = new TenderProjectService();
	private ExpertEvaluationResultService expertEvaluationResultService = new ExpertEvaluationResultService();
	private ExpertService expertService = new ExpertService();
	private EvaluationStepService evaluationStepService = new EvaluationStepService();
	private ExpertEvaluationStepService expertEvaluationStepService = new ExpertEvaluationStepService();
	private CheckResultService checkResultService = new CheckResultService();
	private String EVAL_ACCESSMENT_YES = "符合";
	private String EVAL_ACCESSMENT_NO = "不符合";
	private List<Supplier> supplierList = new ArrayList<Supplier>();
	private Map<String, Color> contentBackgroundMap = new HashMap<String, Color>();
	private ExpertEvaluationListener expertEvaluationListener;
	private Composite contentComposite;
	private Composite left_tool_composite;
	private Composite featureEvaluationResultComposite;
	private Composite loadComposite;
	private String supplierName;
	private String expertUserId;
	private List<CheckResult> checkResultList;
	private EButton init_default_btn;
	private EButton save_result_btn;
	private Object[][] contentArray;
	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
	private TenderProjectEntity tenderProject;
	private EvaluationStep evaluationStep;
	private Expert CURRENT_EXPERT;
	private ProjectRuleService projectRuleService = new ProjectRuleService();
	private String BIDOPENING_STAGE = TenderProjectEnum.STAGE_ALL;
	private ScreenUtils util = new ScreenUtils();
	private Composite pdfLoadComposite;
	private String pdfType;
	private int fontSize = 9;
	private Text evaluationOpinionText;
	boolean hasFailSupplier = false;
	private boolean isLeader;
	private boolean hasOpen;

	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public TianYanCheckComposite(Composite parent, int style) {
		super(parent, style);
		setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		setBackgroundMode(SWT.INHERIT_FORCE);
		GridLayout gridLayout = new GridLayout(3, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		tenderProject = (TenderProjectEntity) parent.getData("tenderProject");
		evaluationStep = (EvaluationStep) parent.getData("evaluationStep");
		CURRENT_EXPERT = (Expert) parent.getData(Constants.CUR_EXPERT);
		
		left_tool_composite = new Composite(this, SWT.NONE);
		left_tool_composite.setBackground(EvalLeftButton.BG);
		left_tool_composite.setBackgroundMode(SWT.INHERIT_FORCE);
		left_tool_composite.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 1, 1));
		GridLayout gl_left_tool_composite = new GridLayout(1, false);
		left_tool_composite.setLayout(gl_left_tool_composite);
		
		EvalLeftButton goto_back = new EvalLeftButton(left_tool_composite, SWT.NONE);
		goto_back.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		goto_back.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/back.png"));
		goto_back.setToolTipText("返回");
		goto_back.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				goBackAction();
			}
		});
		
		EvalLeftButton refresh_evaluation = new EvalLeftButton(left_tool_composite, SWT.NONE);
		refresh_evaluation.setImage(ResourceManager.getPluginImage("com.gx.obe.evaluation", "icons/refresh.png"));
		refresh_evaluation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		refresh_evaluation.setToolTipText("刷新");
		refresh_evaluation.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				refreshAction();
			}
		});
		
		ESepator menu_sep1 = new ESepator(left_tool_composite, SWT.NONE);
		menu_sep1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		
		ESepator toolv_sepator = new ESepator(this, SWT.VERTICAL);
		toolv_sepator.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 1, 1));
		toolv_sepator.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		loadComposite = new Composite(this, SWT.None);
		loadComposite.setLayout(new GridLayout(2, false));
		loadComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		ESepator toolv_sepator1 = new ESepator(loadComposite, SWT.VERTICAL);
		toolv_sepator1.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 1, 1));
		toolv_sepator1.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		featureEvaluationResultComposite = new Composite(loadComposite, SWT.NONE);
		featureEvaluationResultComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_featureEvaluationResultComposite = new GridLayout(1, false);
		gl_featureEvaluationResultComposite.marginHeight = 0;
		gl_featureEvaluationResultComposite.marginWidth = 0;
		gl_featureEvaluationResultComposite.verticalSpacing = 0;
		featureEvaluationResultComposite.setLayout(gl_featureEvaluationResultComposite);
		
		Composite composite_6 = new Composite(featureEvaluationResultComposite, SWT.NONE);
		composite_6.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, false, 1, 1));
		GridLayout gl_composite_6 = new GridLayout(2, false);
		gl_composite_6.horizontalSpacing = 0;
		composite_6.setLayout(gl_composite_6);
		composite_6.setBackgroundMode(SWT.INHERIT_FORCE);
		
		ELink button = new ELink(composite_6, SWT.NONE);
		button.setImage(ResourceManager.getPluginImage("com.gx.obe.common", "icons/btn/blue/view.png"));
		button.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				openTianYanCha();
			}
		});
		button.setText("幕后关联关系查询   ");
		
		
		
		ELink loserButton = new ELink(composite_6, SWT.NONE);
		loserButton.setImage(ResourceManager.getPluginImage("com.gx.obe.common", "icons/btn/blue/view.png"));
		loserButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				openCreditChina();
			}
		});
		loserButton.setText("失信被执行人查询");
		
		
		ESepator topSep = new ESepator(featureEvaluationResultComposite, SWT.NONE);
		topSep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		topSep.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		
		contentComposite = new Composite(featureEvaluationResultComposite, SWT.NONE);
		contentComposite.setLayout(new FillLayout(SWT.HORIZONTAL));
		contentComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		pdfLoadComposite = new Composite(contentComposite, SWT.NONE);
		pdfLoadComposite.setLayout(new FillLayout(SWT.HORIZONTAL));
		
		ESepator sep = new ESepator(featureEvaluationResultComposite, SWT.SEPARATOR | SWT.HORIZONTAL);
		sep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		sep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		Composite composite_1 = new Composite(featureEvaluationResultComposite, SWT.NONE);
		composite_1.setBackgroundMode(SWT.INHERIT_FORCE);
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		composite_1.setLayout(new GridLayout(3, false));
		
		Composite composite = new Composite(composite_1, SWT.NONE);
		composite.setLayout(new GridLayout(1, false));
		GridData gd_composite1 = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1);
		gd_composite1.heightHint = 100;
		composite.setLayoutData(gd_composite1);
		
		Label label = new Label(composite, SWT.NONE);
		label.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, false, 1, 1));
		label.setText("评审意见录入：");
		
		evaluationOpinionText = new Text(composite, SWT.BORDER | SWT.WRAP);
		evaluationOpinionText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		
//		if(parent.getData("manag").equals("true")) {
//			return;
//		}
		
		Composite composite_2 = new Composite(composite_1, SWT.NONE);
		composite_2.setLayout(new GridLayout(3, false));
		composite_2.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, false, 3, 1));
		
		init_default_btn = new EButton(composite_2, SWT.NONE | EButton.CSS_BLUE);
		init_default_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		GridData gd_init_default_btn = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_init_default_btn.widthHint = 100;
		init_default_btn.setText("一键"+EVAL_ACCESSMENT_YES);
		init_default_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/select_all.png"));
		gd_init_default_btn.heightHint = 30;
		init_default_btn.setLayoutData(gd_init_default_btn);
		init_default_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				passAllAction();
			}
		});
		
		save_result_btn = new EButton(composite_2, SWT.NONE | EButton.CSS_GREEN);
		save_result_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		save_result_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/save.png"));
		save_result_btn.setText("暂存结果");
		GridData gd_save_result_btn = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_save_result_btn.widthHint = 100;
		gd_save_result_btn.heightHint = 30;
		save_result_btn.setLayoutData(gd_save_result_btn);
		save_result_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				saveEvaluationResultAction();
			}
		});
		
		EButton submit_result_btn = new EButton(composite_2, SWT.NONE | EButton.CSS_GREEN);
		submit_result_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		GridData gd_submit_result_btn = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
		gd_submit_result_btn.widthHint = 100;
		gd_submit_result_btn.heightHint = 30;
		submit_result_btn.setLayoutData(gd_submit_result_btn);
		submit_result_btn.setText("完成评审");
		submit_result_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/submit.png"));
		submit_result_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				submitEvaluationResultAction();
			}
		});
		
		init();
	}
	
	protected void openCreditChina() {
		// TODO Auto-generated method stub		
		CreditChinaDialog creditChinaDialog = new CreditChinaDialog(getShell(),tenderProject,supplierList);
		creditChinaDialog.open();
		
	}

	/**
	 * @Description:  初始化界面
	 * @author guoyr
	 */
	private void init(){
		expertEvaluationStepService = new ExpertEvaluationStepService();
		expertEvaluationResultService = new ExpertEvaluationResultService();
		expertUserId = CURRENT_EXPERT.getUserId();
		// 修改评标专家的评审记录
		expertEvaluationStepService.updateExpertEvaluationStatus(CommonEnum.IN_PROGRESS, tenderProject.getId(), evaluationStep, expertUserId);
		supplierName = I18N.getString(I18NEnum.SUPPLIERNAME, tenderProject.getTenderType());
		pdfType = PropertiesUtils.getProperty(ConfigConstants.PDF_ACTIVE_TYPE, DocumentFactory.DEFAULT_PDF_TYPE);
		String filePath = FileConstants.PRODUCT_ROOT + File.separator + FileConstants.RESOURCE_FOLDER + File.separator + Constants.TIANYAN_CHECK_NOTE;
		File biddingFile  = new File(filePath);
		
		
		DocumentLoader bidFileDocumentLoader = DocumentFactory.getDocumentLoader(biddingFile.getAbsolutePath(), pdfType);
		bidFileDocumentLoader.openDocument(pdfLoadComposite, true);
		Expert expert = expertService.getExpertLeader(tenderProject.getId());
		if(null != expert) {
			isLeader = expertUserId.equals(expert.getUserId());
		}
		
		evaluationOpinionText.setEnabled(isLeader);
		
		refreshAction();
	}
	
	/**
	 * @Description: 显示提示信息
	 * @author guoyr 
	 */
	private void showTips(){
		StringBuilder noteMsg = new StringBuilder();
		noteMsg.append("红色文字表示该项特征码存在雷同情况，您可录入或修改评审见，");
		noteMsg.append("并在最后一列选择是否");
		noteMsg.append(EVAL_ACCESSMENT_YES);
		noteMsg.append("。");
		loadComposite.layout();
	}
	
	/**
	 * @Description: 初始化特征码检查的内容
	 * @author guoyr 
	 */
	private void initKtableContent(){
		
		int rowCount = supplierList.size() + 1;
		int colcount =  3;
		contentArray = new Object[rowCount][colcount];
		// 设置标题
		contentArray[0][0] = supplierName + "名称";
		
		contentArray[0][contentArray[0].length - 2] = "检查意见";
		contentArray[0][contentArray[0].length - 1] = "是否"+EVAL_ACCESSMENT_YES;
		// 设置内容
		int row = 1;
		Map<String, String> supplierRsult = new HashMap<String, String>();
		boolean hasFailSupplier = false;
		List<ExpertEvaluationResult> expertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProject.getId(), evaluationStep.getId(), expertUserId);
		if(null != expertEvaluationResultList && expertEvaluationResultList.size() > 0){
			for(ExpertEvaluationResult expertEvaluationResult : expertEvaluationResultList){
				if(StringUtils.isNotEmpty(expertEvaluationResult.getAccessment())){
					supplierRsult.put(expertEvaluationResult.getSupplierId(), expertEvaluationResult.getAccessment());
					if(expertEvaluationResult.getAccessment().equals(EvaluationStepEnum.UNQUALIFIED)){
						hasFailSupplier = true;
					}
				}
			}
		}

		if(hasFailSupplier && StringUtils.isNotEmpty(evaluationStep.getEvaluationOpinion())){
			Display.getDefault().syncExec(new Runnable() {
				public void run() {
					evaluationOpinionText.setText(evaluationStep.getEvaluationOpinion());
				}
			});
		}
		for(Supplier supplier : supplierList){
			// 供应商名称
			contentArray[row][0] = row+"、"+supplier.getSupplierName();
			if(StringUtils.isNotEmpty(supplierRsult.get(supplier.getId()))){
				contentArray[row][contentArray[0].length - 1] = supplierRsult.get(supplier.getId());
			}else{
				//默认通过
				String checkPass = EvaluationStepEnum.QUALIFIED;
				contentArray[row][contentArray[0].length - 1] = checkPass;
			}
			row++;
		}
		if(null != checkResultList){
			checkResultList.clear();
		}
//		checkResultService.get
		
		checkResultList = new ArrayList<CheckResult>();
		// 遍历特征码检查结果
		
//		for(row = 1; row < contentArray.length; row ++){
////			boolean checkPass = true;
//			String checkPass = EvaluationStepEnum.QUALIFIED;
//			// 如果不筛选，则表示全部通过
//			contentArray[row][contentArray[0].length - 1] = checkPass;
//		}
	}
	
	/**
	 * @Description: 画表格
	 * @author guoyr 
	 */
	private void drawKtable(){
		
		if(null != resultKTable && !resultKTable.isDisposed()){
			resultKTable.dispose();
		}
		resultKTable = new KTable(contentComposite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY);
		commKTableModel = new CommonKtableCModel(resultKTable, 1, 1, supplierList.size(), 2);
		commKTableModel.setContentRowHeight(40);// 设置行高
		commKTableModel.setColumnWidth(commKTableModel.getColCount() - 1, 70);// 设置最后一列宽为70
		commKTableModel.setColumnWidth(commKTableModel.getColCount() - 2, 200);// 设置评审意见列宽为200
		commKTableModel.setColumnMinWidth(commKTableModel.getColCount() - 2, 250);// 设置评审意见列宽为200
		commKTableModel.setColumnMinWidth(0, 150);
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender(){
			public Object receiveContent(int row, int col) {
				if(row == 0){
					return ObjectUtils.getObjString(contentArray[row][col]);
				}else {
					if(col == commKTableModel.getColCount() -1){
						if (null != contentArray[row][col] && contentArray[row][col].equals(EvaluationStepEnum.QUALIFIED)) {
							return EVAL_ACCESSMENT_YES;
						} else if (contentArray[row][col].equals(EvaluationStepEnum.UNQUALIFIED)) {
							return EVAL_ACCESSMENT_NO;
						}
						return EVAL_ACCESSMENT_NO;
					}else {
//						System.out.println(row  + " :  " + col +  "数据项" + contentArray[row][col]);
						return ObjectUtils.getObjString(contentArray[row][col]);
					}
				}
			}
		};
		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, SWT.NORMAL));
					return textWrapCellRenderer;
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		
		final KTableCellEditorGRadio radio = new KTableCellEditorGRadio();
		radio.setSingleClickEdit(true);
		radio.addItem(EvaluationFactorEnum.getEvalPassTypeCN(EvaluationFactorEnum.CONFORM), EvaluationFactorEnum.CONFORM);
		radio.addItem(EvaluationFactorEnum.getEvalPassTypeCN(EvaluationFactorEnum.UNCONFORM), EvaluationFactorEnum.UNCONFORM);
		// 设置单元格编辑器
		final KTableCellEditorMultilineWrapText text = new KTableCellEditorMultilineWrapText();
		text.setSingleClickEdit(true);
		CellEditorRender cellEditorRender = new CellEditorRender(){
			public Object receiveCellEditor(int row, int col) {
				if(col == commKTableModel.getColumnCount() - 1){// 是否通过(多选框)
					radio.setItem(0, EvaluationFactorEnum.getEvalPassTypeCN(EvaluationFactorEnum.CONFORM), EvaluationFactorEnum.CONFORM);
					radio.setItem(1, EvaluationFactorEnum.getEvalPassTypeCN(EvaluationFactorEnum.UNCONFORM), EvaluationFactorEnum.UNCONFORM);
					return radio;
				}else if(col == commKTableModel.getColumnCount() - 2){// 评审意见
					text.setTextLimit(200);
					return text;
				}else {
					return null;
				}
			}
		};
		commKTableModel.setCellEditorRender(cellEditorRender);
		
//		if(ObjectUtils.equals(EvaluationStepEnum.FILTER_YES, evaluationStep.getFilterType())){
			// 编辑单元格内容
			CellEditContentRender editContentRender = new CellEditContentRender(){
				public void receiveContent(int row, int col, Object content) {
					// 设置"是否通过"和"评审意见"的值
					contentArray[row][col] = content;
				}
			};
			commKTableModel.setCellEditContentRender(editContentRender);
//		}
		
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender(){
			public int receiveCellAlignment(int row, int col) {
				if(row < commKTableModel.getFixedRowCount()){
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				}else {
					if(col == 0 || col == commKTableModel.getColCount() - 2){
						
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					}
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				}
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
		// 设置单元格前景色
		CellForegroundRender cellForegroundRender = new CellForegroundRender() {
			public Color receiveCellForeground(int row, int col) {
				if (!commKTableModel.isFixedCell(col, row)) {
					Color bgColor = contentBackgroundMap.get(row + "_" + col);
					return bgColor;
				}
				return null;
			}
		};
		commKTableModel.setCellForegroundRender(cellForegroundRender);
		
		resultKTable.setModel(commKTableModel);
		contentComposite.layout();
	}
	
	
	/**
	 * @Description: 一键全部通过
	 * @author guoyr 
	 */
	private void passAllAction(){
		for(int row = 1; row < contentArray.length; row ++){
			Object[] contentRowArray = contentArray[row];
			contentRowArray[contentRowArray.length - 1] = EvaluationFactorEnum.CONFORM;
		}
		resultKTable.redraw();
	}
	
	private boolean saveResult(){
		resultKTable.closeCellEditor();
		List<ExpertEvaluationResult> expertEvaluationResultList = new ArrayList<ExpertEvaluationResult>();
		int row = commKTableModel.getFixedRowCount();
		hasFailSupplier = false;
		for(Supplier supplier : supplierList){
			// 供应商名称
			String supplierOpinion = (String)contentArray[row][contentArray[0].length -2];
			String accessment = ObjectUtils.getObjString(contentArray[row][contentArray[0].length -1]);
			// 获得当前供应商的评标结果
			ExpertEvaluationResult expertEvaluationResult = expertEvaluationResultService.getExpertEvaluationResult(tenderProject.getId(), evaluationStep.getId(), supplier.getId(), expertUserId);
			if(null == expertEvaluationResult) {
				expertEvaluationResult = initExpertEvaluationResult();
			}
			
			expertEvaluationResult.setSupplierId(supplier.getId());
			expertEvaluationResult.setSupplierOpinion(StringUtils.isNotEmpty(supplierOpinion) ? supplierOpinion : null);
			expertEvaluationResult.setAccessment(accessment);
			//不是组长不保存评审意见
			if(StringUtils.isNotEmpty(accessment) &&EvaluationFactorEnum.UNCONFORM.equals(accessment) ){
				hasFailSupplier = true;
			}
			expertEvaluationResultList.add(expertEvaluationResult);
			row ++;
		}
		if(isLeader && hasFailSupplier){
			String value = evaluationOpinionText.getText();
			if(StringUtils.isEmpty(value) ){
				return false;
			}
			evaluationStep.setEvaluationOpinion(value);
		}else{
			evaluationStep.setEvaluationOpinion("关联关系评审无异常");
		}
		return expertEvaluationStepService.saveFeatureEvaluationResult(tenderProject.getId(), expertUserId, evaluationStep, checkResultList, expertEvaluationResultList);
	}
	/**
	 * @Description: 暂存结果
	 * @author guoyr
	 * @return 
	 */
	private boolean saveEvaluationResultAction(){
		boolean saveSuccess = saveResult();
		if(saveSuccess){
			MessageDialog.openShortMessage(evaluationStep.getStepName() + "结果暂存成功！");
		}else {
			if(hasFailSupplier){
				MessageDialog.openError(getShell(), "当前" + evaluationStep.getStepName() + "有废标供应商，请输入评审意见！");
			}else{
				MessageDialog.openError(getShell(), evaluationStep.getStepName() + "结果暂存失败！");
				
			}
		}
		return saveSuccess;
	}
	
	/**
	 * @Description: 提交结果
	 * @author guoyr 
	 */
	private void submitEvaluationResultAction(){
		if(!saveResult()){
			if(hasFailSupplier){
				MessageDialog.openError(getShell(), "当前" + evaluationStep.getStepName() + "有废标供应商，请输入评审意见！");
			}else{
				MessageDialog.openError(getShell(), evaluationStep.getStepName() + "结果暂存失败！");
				
			}
			return;
		}
		
		
//		String errorMessage = checkSubmit();
//		if (null != errorMessage) {
//			MessageDialog.openInformation(getShell(), errorMessage);
//			return;
//		}
		
		// 检查是否存在当前评标步骤之前未完成的步骤
//		boolean isFreeProgress = ObjectUtils.equals(projectRule.getOrderReview(), EvaluationStepEnum.ORDER_SELF_FREE);
//		if (isFreeProgress) {
			List<EvaluationStep> evaluationStepList = evaluationStepService.getNotComplateStepList(tenderProject.getId(), evaluationStep.getSortNo());
			if (null != evaluationStepList && evaluationStepList.size() > 0) {
				MessageDialog.openWarning(getShell(), "["+evaluationStepList.get(0).getStepName()+"]还未完成评审，请先完成！");
				return ;
			}
//		}
		
		StringBuilder noAccessment = new StringBuilder();
		int noAccessmentCount = 0;
		
		for(int row = commKTableModel.getFixedRowCount(); row < contentArray.length; row++){
			Object[] rowArray = contentArray[row];
//			boolean accessment = (Boolean)rowArray[rowArray.length -1];
			if(!rowArray[rowArray.length -1].equals(EvaluationFactorEnum.CONFORM)){
				if(noAccessmentCount > 0){
				}
				noAccessment.append("    ");
				noAccessment.append(rowArray[0]);
				noAccessment.append("\r\n");
				noAccessmentCount++;
			}
		}
		StringBuilder msg = new StringBuilder();
		msg.append("完成评审后将不能再对当前评标结果进行修改，");
		if(noAccessmentCount > 0){
			msg.append("其中以下");
			msg.append(noAccessmentCount);
			msg.append("家");
			msg.append(supplierName);
			msg.append(evaluationStep.getStepName());
			msg.append(EVAL_ACCESSMENT_NO);
			msg.append("：\r\n");
			msg.append(noAccessment.toString());
		}
		msg.append("确认完成[").append(evaluationStep.getStepName()).append("]的评审操作吗？");
		
		if(MessageDialog.openConfirm(getShell(), msg.toString())){
			if(expertEvaluationStepService.submitFeatureEvaluationResult(tenderProject.getId(), expertUserId, evaluationStep, supplierList)){
				goBackAction();
			}else {
				MessageDialog.openError(getShell(), "操作失败！");
			}
		}
	}
	
	/**
	 * @Description: 返回
	 * @author guoyr
	 */
	/**
	 * @Description:  获得评标专家对供应商的评标结果
	 * @author guoyr
	 * @return
	 */
	private ExpertEvaluationResult initExpertEvaluationResult(){
		ExpertEvaluationResult expertEvaluationResult = new ExpertEvaluationResult();
		expertEvaluationResult.setId(UuidUtils.getUUID());
		expertEvaluationResult.setTenderId(tenderProject.getId());
		expertEvaluationResult.setStepId(evaluationStep.getId());
		expertEvaluationResult.setUserId(expertUserId);
		return expertEvaluationResult;
	}
	
	/**
	 * @Description: 返回
	 * @author guoyr
	 */
	private void goBackAction(){
		if(null != expertEvaluationListener){
			expertEvaluationListener.complete();
		}
	}
	
	/**
	 * @Description: 刷新项目信息
	 * @author guoyr
	 */
	private void refreshAction(){
		tenderProject = tenderProjectService.getById(tenderProject.getId());
		
		supplierList = supplierService.getEvaluationStepSupplierList(tenderProject.getId(), evaluationStep);
		
		
		showTips();
		
		final Thread initKtableContentThread = new Thread(new Runnable(){
			public void run(){
				initKtableContent();
			}
		});
		initKtableContentThread.start();
		Thread drawKTableThread = new Thread(new Runnable(){
			public void run(){
				try {
					initKtableContentThread.join();
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
					}
				} catch (InterruptedException e) {
				}
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(null != contentComposite && !contentComposite.isDisposed()){
							drawKtable();
							loadComposite.layout();
						}
					}
				});
			}
		});
		drawKTableThread.start();
	}
	
	/**
	 * @Description: 初始化
	 * @author wangx 
	 */
	private void openTianYanCha(){
		String stageId = tenderProject.getStageId();
//		try {
//			Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "https://test.powerbeijing-ec.com/jndzzb/tianyanchaController.do?queryBehindRelationlist&stageId="+stageId);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
//		if(hasOpen) {
//			return;
//		}
//		hasOpen = true;
		Shell shell = new Shell(Display.getDefault());
		shell.setLayout(new FillLayout());
		shell.setText("天眼查幕后关系");
		final Browser browser;
		try {
			browser = new Browser(shell, SWT.NONE);
		} catch (SWTError e) {
			return;
		}
		String serverUrl = PropertiesUtils.getProperty(ConfigConstants.SERVER_URL, "https://www.powerbeijing-ec.com/jndzzb/");
		
		browser.setUrl(serverUrl + "tianyanchaController.do?queryBehindRelationlist&stageId="+stageId); 
	    shell.open();
//		while (!shell.isDisposed()) {
//			if (!Display.getDefault().readAndDispatch()) Display.getDefault().sleep();
//		}
//		if(shell.isDisposed()) {
//			hasOpen = false;
//		}
	}
	
	
	public void addExpertEvaluationListener(ExpertEvaluationListener expertEvaluationListener){
		this.expertEvaluationListener = expertEvaluationListener;
	}
    
    /**
	 * @Description: 检查是否可以提交
	 * @author guoyr
	 * @return
	 */
	public String checkSubmit() {
			int expertCount = expertService.getEvaluationStepExpertCount(tenderProject.getId(), evaluationStep);
			List<ExpertEvaluationResult> expertEvaluationResultList = expertEvaluationResultService.getAllExpertEvaluationResultList(tenderProject.getId());
			Map<String, List<ExpertEvaluationResult>> useridMap = CollectionUtils.toArrayListHashMap(expertEvaluationResultList, new CollectionUtils.NewMap<String, ExpertEvaluationResult>() {
				public String getKey(ExpertEvaluationResult t) {
					return t.getUserId();
				}
			}, new HashMap<String, List<ExpertEvaluationResult>>());
			
			if (expertCount > useridMap.size()) {
				return "还有专家未进行评审，请等待其他专家保存评审结果，并验证一致性评审项的评审结果一致时才能进行此操作！";
			}
			
			Map<Keys, List<ExpertEvaluationResult>> evaluationFactorResultListMap = CollectionUtils.toArrayListHashMap(expertEvaluationResultList, new CollectionUtils.NewMap<Keys, ExpertEvaluationResult>() {
				public Keys getKey(ExpertEvaluationResult t) {
					return new Keys(t.getSupplierId());
				}
			}, new HashMap<Keys, List<ExpertEvaluationResult>>());
			
			for (Keys key : evaluationFactorResultListMap.keySet()) {
				List<ExpertEvaluationResult> factorResultList = evaluationFactorResultListMap.get(key);
				String evaluationResult = null;
				for (ExpertEvaluationResult expertEvaluationResult : factorResultList) {
						String result = expertEvaluationResult.getAccessment();
						if (result == null) {
							return "还有专家未对一致性评审项进行评审，请等待其他专家保存评审结果，并验证一致性评审项的评审结果一致时才能进行此操作！";
						}
						if (evaluationResult == null) {
							evaluationResult = result;
						} else if (!evaluationResult.equals(result)) {
							return "您与其他专家存在一致性评审项的评审结果不一致，待所有专家对一致性评审项的评审结果一致时才能进行此操作！";
						}
				}
			}
		return null;
	}
    /**
     * 查看帮助
     */
//    private void viewHelp(){
//    	ViewGourpTianyanHelpDialog dialog = new ViewGourpTianyanHelpDialog(new Shell(),pdfType);
//		dialog.open();
//    }
	protected void checkSubclass() {}

	@Override
	public void refresh(TenderProjectEntity tenderProjectEntity,Expert expert, EvaluationStep evaluationStep, List<Supplier> supplierList) {
		// TODO Auto-generated method stub
		this.supplierList = supplierList;
		this.tenderProject = tenderProjectEntity;
		this.CURRENT_EXPERT =expert;
		this.evaluationStep = evaluationStep;
		init();
		refreshAction();
	}

	@Override
	public boolean saveEvaluationResult() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean submitEvaluationResult() {
		// TODO Auto-generated method stub
		return false;
	}
	
}
