package com.gx.obe.management.composite;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.MessageFormat;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.CallBack;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.utils.FileDialogUtils;
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.core.widgets.ImageButton;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;

import com.gx.obe.ColorConstants;
import com.gx.obe.DictEnum;
import com.gx.obe.action.bean.Action;
import com.gx.obe.business.entity.MenuFunction;
import com.gx.obe.common.dialog.BidRegulationsConfigDialog;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.dialog.MessageViewDialog;
import com.gx.obe.common.widget.thread.MyRunnable;
import com.gx.obe.common.widget.thread.SyncThread;
import com.gx.obe.common.widget.utils.MenuFunctionUtils;
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.utils.PropertiesUtils;
import com.gx.obe.management.dialog.ApplyToOtherTenderPackEvaluationFactorDialog;
import com.gx.obe.management.dialog.ImportFactorFromTenderProjectDialog;
import com.gx.obe.management.dialog.SelectTranscationServerDialog;
import com.gx.obe.management.thread.DownloadEvaluationFactorThread;
import com.gx.obe.management.thread.EvaluationFactorXmlResolverThread;
import com.gx.obe.management.thread.ImportBillOfQuantitiesThread;
import com.gx.obe.management.thread.NewExportEvaluationFactorThread;
import com.gx.obe.management.thread.SupplierEvaluationFactorXmlResolverThread;
import com.gx.obe.message.Messages;
import com.gx.obe.thread.SyncThreadSet;
import com.gx.obe.util.utils.CollectionUtils;
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.DictionaryValue;
import com.gx.obe.web.entity.auth.Menu;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.listener.WebBoolearListener;
import com.gx.obe.web.listener.WebIntegerListener;
import com.gx.obe.web.service.BaseDictionaryValueService;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.TenderProjectService;
import com.gx.obe.web.service.evaluation.EvaluationFactorService;
import com.gx.obe.web.service.evaluation.EvaluationStepService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 评标指标管理
 * @author guoyr
 */
public class EvaluationFactorsManagerComposite extends Composite {
	
	private Composite eval_method_composite;
	private Combo evaluation_method, evaluationWayCombo;
	private ELink importBillOfQuantities;
	private Composite type_composite;
	private ImageButton complianceFactor, scoreFactor, billFactor, creditFactor, priceFactor;
	private ELink applyToOtherPackBtn;
	private Composite load_composite;
	private Menu menu;
	private ImageButton curEvaluationFactor;
	private TenderProjectRuleEntity projectRule;
	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectService tenderProjectService  ;
	private ProjectRuleService projectRuleService ;
	private BaseDictionaryValueService baseDictionaryValueService  ;
	private EvaluationFactorService evaluationFactorService ;
	private EvaluationStepService evaluationStepService ;
	private boolean isExistEvaluationStep;
	private Action projectAction;
	private List<DictionaryValue> dictionaryValueList;
	private boolean isInProgress = false;
	private boolean returnFlag = false;
	private MenuFunctionUtils menuFunctionUtils = new MenuFunctionUtils();
	
	{
		LogUtils.logClass(EvaluationFactorsManagerComposite.class);
	}
	
	static {
		/**
		 * 第三层验证
		 * **/
		try {
			// 这是公钥
			String publicKey = "308201b83082012c06072a8648ce3804013082011f02818100fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c70215009760508f15230bccb292b982a2eb840bf0581cf502818100f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a0381850002818100def368b8757ce205e46b76640e4886cbd1604753a90cb07527b834a65e83b4f21b97ef443097e882e7c18dea3daea499e31201fa8e4df0f36b0cc00a64a01ccdd831f2856b7549f0eae5d7150fe5800e40bb3b25e3b2a38c51b3f07edd6c90b6f3db70ac12bc11d480cbcaa23a9f30f4db77c0928f3faf477f5e672f43a42a73";
			byte pub[] = com.gx.security.CertUtil.decodeHex(publicKey);
			java.security.spec.X509EncodedKeySpec pubKeySpec = new java.security.spec.X509EncodedKeySpec(pub);
			java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance(com.gx.security.CertEnum.KEY_INIT_CODE);
			java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
			java.security.Signature sig = java.security.Signature.getInstance(com.gx.security.CertEnum.SIGN_RNG_NAME);/* 建立一个签名并用公共密钥初始化 */
			sig.initVerify(pubKey);
			// 这里指定license文件
			File licenseFile = new File(FileConstants.PRODUCT_ROOT + com.gx.security.CertValidator.getInstance().getSequence() + ".cer");
			BufferedReader in = new BufferedReader(new FileReader(licenseFile));
			String certificateXml = com.gx.security.CertUtil.decodeBase64(in.readLine());// 解码
			in.close();
			com.gx.security.Cert certificate = com.gx.security.CertUtil.fromXML(certificateXml);// 从xml读取license
			sig.update(certificate.getSignnatureData());/* 更新并校验数据 */
			boolean flag = sig.verify(com.gx.security.CertUtil.decodeHex(certificate.getSignature()));
			if (!flag) {
				throw new com.gx.security.SecurityRuntimeException("您的授权证书无效 ，请与" + certificate.getIssuer() + "联系。");
			}
			if (certificate.getExpiresDate().before(com.gx.security.NowTimeUtils.getNowDate())) {
				throw new com.gx.security.SecurityRuntimeException("您的授权证书已过期，请与" + certificate.getIssuer() + "联系。");
			}
			boolean valMac = true;
			// 如果是试用版本则不需要验证mac
			if (certificate.getCertType().getType().equals(com.gx.security.Cert.CertType.TRIAL.getType())) {
				valMac = false;
			}
			if (valMac && null != certificate.getMotherBoardSN()) {
				if (!certificate.getMotherBoardSN().contains(com.gx.security.CertValidator.getInstance().getMotherBoardSN())) {
					throw new com.gx.security.SecurityRuntimeException("不是当前设备SN的授权文件，请与" + certificate.getIssuer() + "联系。");
				}
			}
			if (valMac && null != certificate.getMac()) {
				if (!certificate.getMac().contains(com.gx.security.CertValidator.getInstance().getMac())) {
					throw new com.gx.security.SecurityRuntimeException("不是当前设备的授权文件，请与" + certificate.getIssuer() + "联系。");
				}
			}
		} catch (Exception e) {
			throw new com.gx.security.SecurityRuntimeException(e);
		}
	}
	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public EvaluationFactorsManagerComposite(Composite parent, Action projectAction, int style) {
		super(parent, style);
		this.projectAction = projectAction;
		
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.marginHeight = 1;
		gridLayout.marginWidth = 1;
		setLayout(gridLayout);
		
		eval_method_composite = new Composite(this, SWT.NONE);
		GridLayout gl_composite_4 = new GridLayout(7, false);
		eval_method_composite.setLayout(gl_composite_4);
		eval_method_composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		Label label = new Label(eval_method_composite, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		label.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		label.setText(Messages.EvalMethod);
		menuFunctionUtils.addFunction(label, "EVALUATION_METHOD");
		
		evaluation_method = new Combo(eval_method_composite, SWT.READ_ONLY);
		evaluation_method.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				evaluationMethodSelectAction();
			}
		});
		GridData gd_evalMethodCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_evalMethodCombo.widthHint = 150;
		evaluation_method.setLayoutData(gd_evalMethodCombo);
		menuFunctionUtils.addFunction(evaluation_method, "EVALUATION_METHOD");
		
		Label label_11 = new Label(eval_method_composite, SWT.NONE);
		label_11.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_11.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		label_11.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		label_11.setText(Messages.EvalWay);
		menuFunctionUtils.addFunction(label_11, "EVALUATION_WAY");
		
		evaluationWayCombo = new Combo(eval_method_composite, SWT.READ_ONLY);
		evaluationWayCombo.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				evaluationWaySelectAction();
			}
		});
		GridData gd_evalWayCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_evalWayCombo.widthHint = 150;
		evaluationWayCombo.setLayoutData(gd_evalWayCombo);
		menuFunctionUtils.addFunction(evaluationWayCombo, "EVALUATION_WAY");
		
		ELink configRegulations = new ELink(eval_method_composite, SWT.WRAP);
		configRegulations.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				new BidRegulationsConfigDialog(getShell(), tenderProjectEntity).open();
			}
		});
		configRegulations.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/config.png"));
		configRegulations.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
		configRegulations.setText(Messages.Button_votoClause);
		menuFunctionUtils.addFunction(configRegulations, "CONFIG_REGULATIONS");
		
		ELink importsupplierFactorResponse = new ELink(eval_method_composite, SWT.WRAP);
		importsupplierFactorResponse.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				analySupplierResonce();
			}
		});
		importsupplierFactorResponse.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/import.png"));
		importsupplierFactorResponse.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
		importsupplierFactorResponse.setText(Messages.Button_analysisResponse);
		menuFunctionUtils.addFunction(importsupplierFactorResponse, "ANALYSIS_RESPONSE");
		
		importBillOfQuantities = new ELink(eval_method_composite, SWT.WRAP);
		importBillOfQuantities.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				importBillOfQuantitiesAction();
			}
		});
		importBillOfQuantities.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/import.png"));
		importBillOfQuantities.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
		importBillOfQuantities.setText("一键解析工程量清单");
		menuFunctionUtils.addFunction(importBillOfQuantities, "ANALYSIS_BILL");
		
		type_composite = new Composite(this, SWT.NONE);
		GridLayout gl_score_type_composite = new GridLayout(6, false);
		gl_score_type_composite.verticalSpacing = 0;
		type_composite.setLayout(gl_score_type_composite);
		type_composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		complianceFactor = new ImageButton(type_composite, SWT.NONE);
		complianceFactor.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				loadEvaluationFaction(EvaluationFactorEnum.AUDIT_COMPLIANCE);
			}
			
			public void mouseDoubleClick(MouseEvent e) {
				editFactorName(complianceFactor, Messages.Factor_compliance);
			}
		});
		complianceFactor.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		complianceFactor.setText(Messages.Factor_compliance);
		setFactorBtnCss(complianceFactor);
		
		scoreFactor = new ImageButton(type_composite, SWT.NONE);
		scoreFactor.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				loadEvaluationFaction(EvaluationFactorEnum.AUDIT_SCORE);
			}
			
			public void mouseDoubleClick(MouseEvent e) {
				editFactorName(scoreFactor, Messages.Factor_score);
			}
		});
		scoreFactor.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		scoreFactor.setText(Messages.Factor_score);
		setFactorBtnCss(scoreFactor);
		
		billFactor = new ImageButton(type_composite, SWT.NONE);
		billFactor.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				loadEvaluationFaction(EvaluationFactorEnum.AUDIT_BILL);
			}
			
			public void mouseDoubleClick(MouseEvent e) {
				editFactorName(billFactor, I18NEnum.BILL_FACTOR);
			}
		});
		billFactor.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		billFactor.setText("清单指标");
		menuFunctionUtils.addFunction(billFactor, "BILL_FACTOR");
		setFactorBtnCss(billFactor);
		
		creditFactor = new ImageButton(type_composite, SWT.NONE);
		creditFactor.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				loadEvaluationFaction(EvaluationFactorEnum.AUDIT_CREDIT);
			}
			
			public void mouseDoubleClick(MouseEvent e) {
				editFactorName(creditFactor, I18NEnum.CREDIT_FACTOR);
			}
		});
		creditFactor.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		creditFactor.setText(PropertiesUtils.getEnum(I18NEnum.CREDIT_FACTOR, "综合信用") + "指标");
		menuFunctionUtils.addFunction(creditFactor, "CREDIT_FACTOR");
		setFactorBtnCss(creditFactor);
		
		priceFactor = new ImageButton(type_composite, SWT.NONE);
		priceFactor.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				loadEvaluationFaction(EvaluationFactorEnum.AUDIT_PRICE);
			}
			
			public void mouseDoubleClick(MouseEvent e) {
				editFactorName(priceFactor, Messages.Factor_price);
			}
		});
		priceFactor.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		priceFactor.setText(Messages.Factor_price);
		menuFunctionUtils.addFunction(priceFactor, "PRICE_FACTOR");
		setFactorBtnCss(priceFactor);
		
		Composite composite = new Composite(type_composite, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		composite.setLayout(new GridLayout(7, false));
		
		Label lblNewLabel = new Label(composite, SWT.NONE);
		lblNewLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		applyToOtherPackBtn = new ELink(composite, SWT.NONE);
		applyToOtherPackBtn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				applyToOtherPackAction();
			}
		});
		applyToOtherPackBtn.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		applyToOtherPackBtn.setText(MessageFormat.format(Messages.Button_applyToOthers, Messages.Package));
		applyToOtherPackBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/copy.png"));
		menuFunctionUtils.addFunction(applyToOtherPackBtn, "APPLY_FACTOR");
		
		ELink refresh_btn = new ELink(composite, SWT.NONE);
		refresh_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				refreshFactorTree();
			}
		});
		refresh_btn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		refresh_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/refresh.png"));
		refresh_btn.setText(Messages.Button_refresh);
		
		ELink download_btn = new ELink(composite, SWT.NONE);
		download_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				downLoadFactorAction();
			}
		});
		download_btn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		download_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/download.png"));
		download_btn.setText(Messages.Button_download);
		menuFunctionUtils.addFunction(download_btn, "DOWNLOAD_FACTOR");
		
		ELink import_btn = new ELink(composite, SWT.NONE);
		import_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				importFactorFromTenderProject();
			}
		});
		import_btn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		import_btn.setText(Messages.Button_import);
		import_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/import.png"));
		import_btn.setToolTipText(Messages.Tips_importFromProject);
		menuFunctionUtils.addFunction(import_btn, "IMPORT_FACTOR");
		
		ELink export_btn = new ELink(composite, SWT.NONE);
		export_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				exportFactorFromTenderProject();
			}
		});
		export_btn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		export_btn.setText(Messages.Button_export);
		export_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/export.png"));
		export_btn.setToolTipText(Messages.Tips_exportFromProject);
		menuFunctionUtils.addFunction(export_btn, "EXPORT_FACTOR");
		
		ELink cleanall_btn = new ELink(composite, SWT.NONE);
		cleanall_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				delAllFactorAction();
			}
		});
		cleanall_btn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		cleanall_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/delete.png"));
		cleanall_btn.setText(Messages.Button_clearAllFactor);
		cleanall_btn.setToolTipText(Messages.Button_deleteAll);
		menuFunctionUtils.addFunction(cleanall_btn, "DELETE_ALL_FACTOR");
		
		ESepator fact_tab = new ESepator(type_composite, SWT.NONE);
		fact_tab.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 6, 1));
		fact_tab.setLineWidth(2);
		fact_tab.setBackground(ColorConstants.SKIN_BG);
		
		Composite content_omposite = new Composite(this, SWT.NONE);
		content_omposite.setBackground(ColorConstants.BORDER_LINE_COLOR);
		content_omposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_content_omposite = new GridLayout(1, false);
		gl_content_omposite.marginHeight = 0;
		gl_content_omposite.marginWidth = 0;
		content_omposite.setLayout(gl_content_omposite);
		
		load_composite = new Composite(content_omposite, SWT.NONE);
		load_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		FillLayout fl_load_composite = new FillLayout(SWT.HORIZONTAL);
		fl_load_composite.marginHeight = 5;
		fl_load_composite.marginWidth = 5;
		load_composite.setLayout(fl_load_composite);
		load_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		init();
		
	}
	
	
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init() {
		this.tenderProjectEntity = projectAction.getTenderProject();
		this.menu = projectAction.getMenu();
		menuFunctionUtils.initFunctionAuthority(menu);
		tenderProjectEntity.setTenderType(TenderProjectEnum.TENDER_YTPE_JZGC);;
		applyToOtherPackBtn.setText(MessageFormat.format(Messages.Button_applyToOthers, com.gx.obe.components.core.I18N.getString(I18NEnum.SUBPACKAGE, tenderProjectEntity.getTenderType())));
		load_composite.setData("menu", menu);
		tenderProjectService  = new TenderProjectService();
		projectRuleService = new ProjectRuleService();
		baseDictionaryValueService = new BaseDictionaryValueService();
		evaluationFactorService = new EvaluationFactorService();
		evaluationStepService  = new EvaluationStepService();
		SyncThreadSet myThreadSet = new SyncThreadSet("加载指标", new SyncThreadSet.Runnable() {
			public void run(){
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(load_composite.isDisposed())return;
						loadEvaluationFaction(EvaluationFactorEnum.AUDIT_COMPLIANCE);
						
						if (null == tenderProjectEntity.getParentId()) {
							WidgetUtils.setControlVisible(applyToOtherPackBtn, false);
						}
                        initEvalMethodAction();
					}
				});
			}
		});		
		myThreadSet.addSyncExec(new SyncThread("刷新规则", new SyncThread.Runnable() {
			public void run() {
				projectRule = projectAction.refreshTenderProjectRule();
			}
		}));
		
//		myThreadSet.addSyncExec(new SyncThread("是否存在步骤", new SyncThread.Runnable() {
//			public void run() {
//				
//			}
//		}));
		myThreadSet.addSyncExec(new SyncThread("获取评标办法", new SyncThread.Runnable() {
			public void run() {
				dictionaryValueList = baseDictionaryValueService.getDictionaryValueList(DictEnum.DIC_EVAL_METHOD);
			}
		}));
		myThreadSet.addSyncExec(new SyncThread("如果没有步骤且没有指标，则自动解析文件中的指标", new SyncThread.Runnable() {
			public void run() {
				isInProgress = tenderProjectService.isInProgress(tenderProjectEntity.getId(), null);
				List<String> nodeList = evaluationStepService.getIdByTenderIdCount(tenderProjectEntity.getId());
				isExistEvaluationStep = CollectionUtils.isNotNull(nodeList);
				if(isInProgress || isExistEvaluationStep) {
					return;
				}
				final int factorCount = evaluationFactorService.getFactorCountByTenderId(tenderProjectEntity.getId());
				
				// 验证项目下是否存在评审指标，如果没有则自动导入招标文件或投标文件下的指标信息。
				if (factorCount > 0) {
					return;
				}
				// 导入评审指标线程（项目下没有评审指标，先从招标文件下找(EvalFactors.xml)，未找到则再从投标文件下找(EvalFactors.xml)。）
				new EvaluationFactorXmlResolverThread(tenderProjectEntity, new CallBack() {
					public void callBackBoolean(boolean bool) {
						Display.getDefault().asyncExec(new Runnable(){
							public void run(){
								if (!evaluation_method.isDisposed()) {
									refreshFactorTree();
									initEvalMethodAction();
								}
							}
						});
					}
				}).start();
			}
		}));
		myThreadSet.setMessage(Messages.Tips_requesting);
		myThreadSet.start();

		WidgetUtils.setControlVisible(importBillOfQuantities, TenderProjectEnum.TENDER_YTPE_JZGC.equals(tenderProjectEntity.getTenderType()));
		
		menuFunctionUtils.initFunctionAuthority(menu);
		
//		exportFactorBtn.addMouseListener(new MouseAdapter() {
//			@Override
//			public void mouseUp(MouseEvent e) {
//				exportFactorAction();
//			}
//		});
		
	}
	
	/**
	 * @Description: 加载评标办法数据
	 */
	private void initEvalMethodAction() {
		evaluation_method.removeAll();
		if (null != dictionaryValueList && dictionaryValueList.size() > 0) {
			for (DictionaryValue evaluationMethod : dictionaryValueList) {
				int index = evaluation_method.getItemCount();
				evaluation_method.add(evaluationMethod.getDictValueName(), index);
				evaluation_method.setData(ObjectUtils.getObjString(index), evaluationMethod.getDictValueCode());
			}
			WidgetUtils.setComboSelection(evaluation_method, projectRule.getEvalMethodType());
		}
		showFactorType();
		evaluationWayCombo.removeAll();
		evaluationWayCombo.add(TenderProjectEnum.getEvalWayCn(TenderProjectEnum.EVALWAY_COMPREHENSIVE), 0);
		evaluationWayCombo.setData("0", TenderProjectEnum.EVALWAY_COMPREHENSIVE);
		evaluationWayCombo.add(TenderProjectEnum.getEvalWayCn(TenderProjectEnum.EVALWAY_GROUP), 1);
		evaluationWayCombo.setData("1", TenderProjectEnum.EVALWAY_GROUP);
		WidgetUtils.setComboSelection(evaluationWayCombo, projectRule.getEvalWay());
		if (isInProgress) {
			evaluation_method.setEnabled(false);
			evaluationWayCombo.setEnabled(false);
		} else {
			evaluation_method.setEnabled(true);
			evaluationWayCombo.setEnabled(true);
		}
		eval_method_composite.layout();
	}
	
	/**
	 * @Description: 加载评审指标
	 * @author guoyr
	 * @param auditType
	 */
	private void loadEvaluationFaction(String auditType) {
		if(load_composite.isDisposed())return;
		for (Control control : load_composite.getChildren()) {
			control.dispose();
		}
		if (null != curEvaluationFactor && !curEvaluationFactor.isDisposed()) {
			curEvaluationFactor.setSelection(false);
		}
		if (auditType.equals(EvaluationFactorEnum.AUDIT_COMPLIANCE)) {
			new ComplianceFactorsComposite(load_composite, projectAction, SWT.NONE);
			curEvaluationFactor = complianceFactor;
		} else if (auditType.equals(EvaluationFactorEnum.AUDIT_SCORE)) {
			new ScoreFactorsManagerComposite(load_composite, projectAction, SWT.NONE);
			curEvaluationFactor = scoreFactor;
		} else if (auditType.equals(EvaluationFactorEnum.AUDIT_PRICE)) {
			new PriceFactorsManagerComposite(load_composite, projectAction, SWT.NONE);
			curEvaluationFactor = priceFactor;
		} else if (auditType.equals(EvaluationFactorEnum.AUDIT_BILL)) {
			new BusinessFactorManagerComposite(load_composite, SWT.NONE).refresh(tenderProjectEntity, projectRule, projectRule.getEvalMethodType());
			curEvaluationFactor = billFactor;
		} else if (auditType.equals(EvaluationFactorEnum.AUDIT_CREDIT)) {
			new CreditFactorManagerComposite(load_composite, SWT.NONE).refresh(tenderProjectEntity);
			curEvaluationFactor = creditFactor;
		}
		curEvaluationFactor.setSelection(true);
		load_composite.layout();
	}
	
	/**
	 * @Description: 选择评标办法事件
	 * @author chenxw
	 */
	private void evaluationMethodSelectAction() {
		if (null != projectRule && !StringUtils.equals(ObjectUtils.getObjString(WidgetUtils.getComboSelection(evaluation_method)), projectRule.getEvalMethodType())) {
			if (null != projectRule) {
				projectRule.setEvalMethodName(evaluation_method.getText());
				projectRule.setEvalMethodType(ObjectUtils.getObjString(WidgetUtils.getComboSelection(evaluation_method)));
				String[] params = new String[] {"id" , "evalMethodName", "evalMethodType" };
				// 如果是二阶段评标法，则设置不允许查看投标报价
				if (ObjectUtils.equals(projectRule.getEvalMethodType(), TenderProjectEnum.TWO_STAGE)) {
					projectRule.setViewBidPrice(CommonEnum.NO);
					projectRule.setViewPriceScore(CommonEnum.NO);
					projectRule.setShowBidPrice(CommonEnum.NO);// 开标时是否显示投标报价
					params = new String[] {"id" ,"evalMethodName", "evalMethodType", "viewBidPrice", "viewPriceScore", "showBidPrice" };
				} else {
					params = new String[] {"id" , "evalMethodName", "evalMethodType" };
				}
				UpdateAssignPropertyThread updateAssignPropertyThread = new UpdateAssignPropertyThread(projectRule, params, new WebBoolearListener() {
					@Override
					public void run(boolean isOk) {
						MessageDialog.openShortMessage(Messages.Tips_operateSuccess);
						showFactorType();
					}
				});
				updateAssignPropertyThread.start();
			}
		}
	}

	/**
	 * @Description: 设置显示指标分类
	 * @author chenxw 
	 */
	private void showFactorType() {
		boolean isMinMethod = TenderProjectEnum.MIN_METHOD.equals(projectRule.getEvalMethodType());
		if (isMinMethod) {
			WidgetUtils.setControlVisible(billFactor, false);
			WidgetUtils.setControlVisible(creditFactor, false);
			if (!complianceFactor.equals(curEvaluationFactor)) {
				loadEvaluationFaction(EvaluationFactorEnum.AUDIT_COMPLIANCE);
			}
			if(MenuFunction.HIDE.equals(menuFunctionUtils.getAuthority("PRICE_FACTOR_MIN_METHOD"))){
				WidgetUtils.setControlVisible(priceFactor, false);
			}
			if(MenuFunction.HIDE.equals(menuFunctionUtils.getAuthority("SCORE_FACTOR_MIN_METHOD"))){
				WidgetUtils.setControlVisible(scoreFactor, false);
			}
		}else {
			if (billFactor.equals(curEvaluationFactor)) {
				loadEvaluationFaction(EvaluationFactorEnum.AUDIT_BILL);
			}
		}
		if(TenderProjectEnum.TENDER_YTPE_JZGC.equals(tenderProjectEntity.getTenderType())) {
			if(MenuFunction.HIDE.equals(menuFunctionUtils.getAuthority("PRICE_FACTOR_JZGC"))){
				WidgetUtils.setControlVisible(priceFactor, false);
			}
			if(MenuFunction.HIDE.equals(menuFunctionUtils.getAuthority("BILL_FACTOR_JZGC"))){
				WidgetUtils.setControlVisible(billFactor, false);
				WidgetUtils.setControlVisible(importBillOfQuantities, false);
			}
			if(MenuFunction.HIDE.equals(menuFunctionUtils.getAuthority("CREDIT_FACTOR_JZGC"))){
				WidgetUtils.setControlVisible(creditFactor, false);
			}
		}else {
			WidgetUtils.setControlVisible(billFactor, false);
			WidgetUtils.setControlVisible(creditFactor, false);
			WidgetUtils.setControlVisible(importBillOfQuantities, false);
		}
		
		
		type_composite.layout();
	}
	
	/**
	 * @Description: 选择评审方式事件
	 * @author chenxw
	 */
	private void evaluationWaySelectAction() {
		String selectEvalWayType = ObjectUtils.getObjString(WidgetUtils.getComboSelection(evaluationWayCombo));
		if (null != projectRule && null != selectEvalWayType && !selectEvalWayType.equals(projectRule.getEvalWay())) {
			if (null != projectRule) {
				projectRule.setEvalWay(selectEvalWayType);
				UpdateAssignPropertyThread  updateAssignPropertyThread = new UpdateAssignPropertyThread(projectRule, new String[] {"id" , "evalWay" }, new WebBoolearListener() {	
					@Override
					public void run(boolean isOk) {
						if(isOk){
							MessageDialog.openShortMessage(Messages.Tips_operateSuccess);
						}else{
							MessageDialog.openShortMessage(Messages.Tips_operateFail);
						}
					}
				});
				updateAssignPropertyThread.start();
			}
		}
	}
	class UpdateAssignPropertyThread extends MyRunnable{
		private WebBoolearListener listener;
		private TenderProjectRuleEntity tenderProjectRuleEntity;
		private String [] params ;
		public UpdateAssignPropertyThread(TenderProjectRuleEntity tenderProjectRuleEntity ,String [] params ,WebBoolearListener listener){
			this.listener = listener;	
			this.tenderProjectRuleEntity = tenderProjectRuleEntity;
			this.params = params;
		}
		@Override
		public void run() {
			 final boolean isUpdate = projectRuleService.updateAssignProperty(this.tenderProjectRuleEntity, this.params);
			Display.getDefault().syncExec(new Runnable(){
				public void run(){
					listener.run(isUpdate);
				} 
			});
		}
	}
	
	/**
	 * @Description: 解析供应商相应评审点
	 * @author guoyr
	 */
	private void analySupplierResonce() {
		if (MessageDialog.openConfirm(getShell(), "此操作会覆盖上一次操作数据，确认要进行数据覆盖吗？")) {
			MessageViewDialog dialog = new MessageViewDialog(getShell(), -1);
			new SupplierEvaluationFactorXmlResolverThread(tenderProjectEntity, dialog.getCallBack()).start();
			dialog.setTitle("解析投标响应文件");
			dialog.open();
		}
	}
	
	/**
	 * @Description: 解析工程量清单按钮点击事件
	 * @author chenxw
	 */
	private void importBillOfQuantitiesAction() {
		if (tenderProjectService.isInProgress(tenderProjectEntity.getId(), EvaluationStepEnum.CLEAN_TENDER)) {
			MessageDialog.openInformation(getShell(), "已进入清标环节，不能进行此操作！");
			return;
		}
		if (MessageDialog.openConfirm(getShell(), "确认要全部重新解析工程量清单吗？")) {
			MessageViewDialog dialog = new MessageViewDialog(getShell(), -1);
			ImportBillOfQuantitiesThread thread = new ImportBillOfQuantitiesThread(tenderProjectEntity, dialog.getCallBack());
			thread.start();
			dialog.setTitle("解析工程量清单");
			dialog.open();
			thread.stop();
		}
	}
	
	/**
	 * @Description: 编辑指标名称
	 * @author guoyr
	 * @param factorButton
	 * @param auditType
	 */
	private void editFactorName(final ImageButton factorButton, final String enumKey) {
//		final ToolsShell moreToolsShell = new ToolsShell(getShell());
//		final Composite composite = moreToolsShell.addToolBar("修改指标分类名称", null, false);
//		composite.setLayout(new GridLayout(3, false));
//		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
//		
//		Label label = new Label(composite, SWT.NONE);
//		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
//		label.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
//		label.setText("指标分类名称：");
//		
//		final Text text = new Text(composite, SWT.NONE | SWT.BORDER);
//		text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
//		text.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
//		text.setText(PropertiesUtils.getEnum(enumKey, factorButton.getText()));
//		text.setTextLimit(15);
//		
//		Label text_1 = new Label(composite, SWT.NONE);
//		text_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
//		text_1.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
//		text_1.setText("指标");
//		
//		EButton saveBtn = new EButton(composite, SWT.NONE);
//		saveBtn.setBackground(ColorConstants.SKIN_BG);
//		saveBtn.setForeground(ColorColorConstants.SKIN_FOREGROUND);
//		saveBtn.setActiveBackgroundColor(ColorConstants.SKIN_ACTIVE_BG);
//		saveBtn.setArcWidth(5);
//		saveBtn.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, true, 3, 1));
//		saveBtn.setText(Messages.ConfirmChange);
//		saveBtn.addMouseListener(new MouseAdapter() {
//			public void mouseUp(MouseEvent e) {
//				String newFactorName = text.getText().trim();
//				if (newFactorName.length() > 0) {
//					moreToolsShell.close();
//					factorButton.setText(newFactorName + "指标");
//					score_type_composite.layout();
//					PropertiesUtils.saveEnum(enumKey, newFactorName);
//				} else {
//					MessageDialog.openShortMessage("指标分类名称不能为空！");
//				}
//			}
//		});
//		moreToolsShell.pack();
//		SwtUtils.setCenter(moreToolsShell);
//		moreToolsShell.open();
	}
	
	/**
	 * @Description: 设置指标分类的按钮
	 * @author guoyr
	 * @param factorBtn
	 */
	private void setFactorBtnCss(ImageButton factorBtn) {
		factorBtn.setRightMargin(10);
		factorBtn.setLeftMargin(10);
		factorBtn.setTopMargin(5);
		factorBtn.setBottomMargin(5);
		factorBtn.setRightMargin(20);
		factorBtn.setLeftMargin(20);
		factorBtn.setTopMargin(5);
		factorBtn.setBottomMargin(5);
		factorBtn.setRightMargin(10);
		factorBtn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		factorBtn.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		factorBtn.setBackgroundColor(SWTResourceManager.getColor(245, 245, 245));
		factorBtn.setActiveForeground(ColorConstants.SKIN_ACTIVE_FOREGROUND);
		factorBtn.setActiveBackgroundColor(ColorConstants.SKIN_ACTIVE_BG);
		factorBtn.setSelectionForeground(ColorConstants.SKIN_SELECTOIN_FOREGROUND);
		factorBtn.setSelectionBgColor(ColorConstants.SKIN_BG);
	}
	
	/**
	 * @Description: 应用到其他包件
	 * @author guoyr
	 */
	private void applyToOtherPackAction() {
 
		UpdateEvaluationFactorThread updateEvaluationFactorThread =new UpdateEvaluationFactorThread(tenderProjectEntity.getId(), new WebIntegerListener() {
			
			@Override
			public void run(Integer size) {
				if (size > 0) {
//					final ProgressDialog progressDialog = new ProgressDialog(getShell(), "");
					ApplyToOtherTenderPackEvaluationFactorDialog applyToOtherTenderPackDialog = new ApplyToOtherTenderPackEvaluationFactorDialog(getShell(), tenderProjectEntity);
					applyToOtherTenderPackDialog.open();
				} else {
					MessageDialog.openShortMessage("请先设置评审指标！");
				}
				
			}
		});
		updateEvaluationFactorThread.start();

	}
	class UpdateEvaluationFactorThread extends MyRunnable{
		private WebIntegerListener listener;
 		private String id ;
		public UpdateEvaluationFactorThread(String id,WebIntegerListener listener){
			this.listener = listener;	
			this.id = id;
		}
		@Override
		public void run() {
			final int factorCount = evaluationFactorService.getFactorCountByTenderId(this.id);
			Display.getDefault().syncExec(new Runnable(){
				public void run(){
					listener.run(factorCount);
				} 
			});
		}
	}
	
	
	
	/**
	 * @Description: 刷新指标树
	 * @author guoyr
	 */
	private void refreshFactorTree() {
		if (null != curEvaluationFactor && !curEvaluationFactor.isDisposed()) {
			curEvaluationFactor.notifyListeners(SWT.MouseUp, null);
		}
	}
	
	/**
	 * @Description: 下载指标
	 * @author guoyr
	 */
	private void downLoadFactorAction() {
		
		Thread thread = new Thread(new Runnable() {	
			@Override
			public void run() {
				if (isInEvaluationProgress()) {
					return;
				}
				if (isInProgress || isExistEvaluationStep) {
					Display.getDefault().syncExec(new Runnable(){
						public void run() {
							MessageDialog.openConfirm(getShell(), "已经设置评标步骤，不能进行此操作！");
							return;
							
//							if (!MessageDialog.openConfirm(getShell(), "已经设置评标步骤，您下载指标后，需要重新设置评标步骤，确认继续此操作吗？")) {
//								returnFlag = true;
//								return;
//							} else {
//								returnFlag = false;
//							}
						} 
					});
					return;
				} else {
					// 如果是本地项目则弹出执行平台系统界面，对服务器地址选择。
					if (StringUtils.isEmpty(ObjectUtils.getObjString(tenderProjectEntity.getTransactionServerId()))) {
						Display.getDefault().syncExec(new Runnable(){
							public void run(){
								if (!MessageDialog.openConfirm(getShell(), "已经设置评标步骤，您下载指标后，需要重新设置评标步骤，确认继续此操作吗？")) {
									returnFlag = true;
									return;
								}else {
									returnFlag = false;
								}
								SelectTranscationServerDialog expertLibDialog = new SelectTranscationServerDialog(getShell());
								expertLibDialog.setTitle(Messages.Dialog_warmTips);
								expertLibDialog.open();
								String transServerId = expertLibDialog.getTransServerId();
								if (StringUtils.isNotEmpty(transServerId)) {
									tenderProjectEntity.setTransactionServerId(transServerId);
									returnFlag = false;
								} else {
									returnFlag = true;
									return;
								}
 							} 
						});
					} else {
						List<String> factorIdList = evaluationFactorService.getFactorIdList(tenderProjectEntity.getId(), null);
						if (null != factorIdList && factorIdList.size() > 0) {
							Display.getDefault().syncExec(new Runnable(){
								public void run(){
									if (!MessageDialog.openConfirm(getShell(), "已存在评审指标，重新下载后会覆盖已有的指标， 是否继续？")) {
										returnFlag = true;
										return;
									}else {
										returnFlag = false;
									}
								} 
							});
						}
					}
				}
				
				if(!returnFlag) {
					Display.getDefault().syncExec(new Runnable(){
						public void run(){
							MessageViewDialog dialog = new MessageViewDialog(getShell(), -1);
							new DownloadEvaluationFactorThread(tenderProjectEntity, dialog.getCallBack()).start();
							dialog.setTitle(MessageFormat.format(Messages.Button_downloadFormat, Messages.Factor_factor));
							dialog.open();
							refreshFactorTree(); 						 
						} 
					});
				}
				
			}
		});
		thread.start();
	}
	
	/**
	 * @Description: 引入其他项目指标
	 * @author guoyr
	 */
	private void importFactorFromTenderProject() {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				if (isInEvaluationProgress()) {
					return;
				}
				Display.getDefault().syncExec(new Runnable() {
					public void run() {
						if (isExistEvaluationStep) {
							MessageDialog.openWarning(getShell(), "已经设置评标步骤，不能进行此操作！");
							return;
						}
//						if (isExistEvaluationStep) {
//							if (!MessageDialog.openConfirm(getShell(), "已经设置评标步骤，您导入其他项目指标后，需要重新设置评标步骤，确认继续此操作吗？")) {
//								return;
//							}
//						}
						ImportFactorFromTenderProjectDialog dialog = new ImportFactorFromTenderProjectDialog(getShell(), tenderProjectEntity);
						dialog.setCallBack(new CallBack() {
							public void callBack() {
								refreshFactorTree();
							}
						});
						dialog.open();
					}
				});
			}
		});
		thread.start();
	}
	
	/**
	 * @Description: 导出当前项目指标
	 * @author chenxw 
	 */
	private void exportFactorFromTenderProject() {
		String projName = "[" + tenderProjectEntity.getTenderNo() + "]" + tenderProjectEntity.getTenderName() + "_评审指标";
		String saveFilePath = FileDialogUtils.getFileSavePath(projName, Messages.Button_save, new String[] { "*.xml" }, new String[] { "XML文件(*.xml)" });
		if (StringUtils.isNotEmpty(saveFilePath)) {
			MessageViewDialog messageDialog = new MessageViewDialog(getShell(), -1);
			new NewExportEvaluationFactorThread(tenderProjectEntity, saveFilePath, messageDialog.getCallBack()).start();
			messageDialog.setTitle("导出指标");
			messageDialog.open();
		}
	}
	
	/**
	 * @Description: 删除所有的指标
	 * @author guoyr
	 */
	private void delAllFactorAction() {
		if (isInEvaluationProgress()) {
			return;
		}
		if (isExistEvaluationStep) {
			MessageDialog.openWarning(getShell(), "已经设置评标步骤，不能进行此操作！");
			return;
			
//			if (!MessageDialog.openConfirm(getShell(), "已经设置评标步骤，您清空指标后，需要重新设置评标步骤，确认继续此操作吗？")) {
//				return;
//			}
		}
		if (MessageDialog.openConfirm(getShell(), "确认要清空所有的指标吗？")) {
			Thread thread = new Thread(new Runnable() {	
				@Override
				public void run() {
					evaluationFactorService.delAllEvaluationFactor(tenderProjectEntity.getId());
					Display.getDefault().syncExec(new Runnable(){
						public void run(){
							refreshFactorTree();
						} 
					});
				}
			});
			thread.start();	
		}
	}
	
	/**
	 * @Description: 验证是否已经进入评分环节
	 * @author guoyr
	 * @return
	 */
	private boolean isInEvaluationProgress() {
		boolean isInEvaluationProgress = tenderProjectService.isInProgress(tenderProjectEntity.getId(), null);
		if (isInEvaluationProgress) {
			Display.getDefault().syncExec(new Runnable(){
				public void run(){
					MessageDialog.openWarning(getShell(), Messages.Dialog_warmTips, Messages.Tips_enteredEvaluation);
				}
			});
		}
		return isInEvaluationProgress;
	}
	
	protected void checkSubclass() {}
}
