package com.gx.obe.management;

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

import org.apache.log4j.Logger;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.CallBack;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.listener.KeyEnterListener;
import org.eclipse.swt.core.utils.SwtUtils;
import org.eclipse.swt.core.utils.WidgetUtils;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.EMenu;
import org.eclipse.swt.core.widgets.ImageButton;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.gx.obe.AboutDialog;
import com.gx.obe.CertificateValidationDialog;
import com.gx.obe.ConfigDialog;
import com.gx.obe.DictEnum;
import com.gx.obe.LoginCaListShell;
import com.gx.obe.LoginCacheListShell;
import com.gx.obe.ProxyConfigDialog;
import com.gx.obe.application.AppApplicationException;
import com.gx.obe.business.UserLogin;
import com.gx.obe.business.enumeration.UserEnum;
import com.gx.obe.common.dialog.EnvironmentTestDialog;
import com.gx.obe.common.dialog.SelectUserRoleTypeDialog;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.shell.DictionaryValueSelectShell;
import com.gx.obe.common.widget.thread.MyThread;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.enttiytdo.BooleanResultDO;
import com.gx.obe.listener.CheckUpdateVersionListener;
import com.gx.obe.message.Messages;
import com.gx.obe.thread.ApplyMachineThread;
import com.gx.obe.thread.CheckUpdateThread;
import com.gx.obe.thread.LoginCacheThread;
import com.gx.obe.thread.UpoladTerminalInfoThread;
import com.gx.obe.update.dialog.UpdateDialog;
import com.gx.obe.util.utils.NetWorkUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.ScreenUtils;
import com.gx.obe.util.utils.StringUtil;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.DictionaryValue;
import com.gx.obe.web.entity.auth.AuthLoginRecordEntity;
import com.gx.obe.web.entity.auth.AuthRole;
import com.gx.obe.web.entity.auth.AuthUser;
import com.gx.obe.web.service.MachineService;
import com.gx.obe.web.service.UserLoginRecordService;
import com.gx.obe.web.service.UserRoleService;
import com.gx.obe.web.service.UserService;
import com.gx.security.CertValidator;
import com.gx.security.SystemTool;
import com.gx.tools.ca.CACert;
import com.gx.tools.ca.CAEngineFactory;
import com.gx.tools.ca.ICAEngine;
import com.gx.utils.NowTimeUtils;
import com.gx.utils.RefreshTokenTask;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 登录界面
 * @author guoyr
 */
public class LoginDialog {

	protected Shell shell;
	private int loginType = 0;
	private ImageResolver imageResolver = new ImageResolver();
	private UserService userService;
 	private UserRoleService userRoleService = new UserRoleService();
	private UserLoginRecordService userLoginRecordService;
	private Label macLabel;
	private Label ipLabel;
	private boolean connectSuccess = false;
	private boolean valMachineSuccess = false;
	private Thread conntectThread;
	private Thread valEvalBidRoomMachine;
	private Composite login_content;
	private Composite centerComposite;
	private Text account_text;
	private Text pwd_text;
	private ImageButton login_btn;
	private CLabel product_info;
	private Label messageLabel;
	private ImageButton loginMenuLabel;
	private CLabel sys_icon;
	private LoginCacheListShell userCacheShell;
	private LoginCaListShell caListShell;
	private StackLayout loginFormStackLayout = new StackLayout();
	private Composite account_form;
	private Composite password_form;
	private Image loginBgImage;
	private AuthUser tempUser;
	private Composite loginForm_composite;
	private Composite account_composite;
	private boolean caLogin = false;
	private Composite ca_composite;
	private Label loginType_label;
	private Composite ca_form;
	private Text ca_text;
	private Label lblca;
	private ImageButton caLogin_btn;
	private Composite composite_4;
	private Label lblusbkey;
	private ICAEngine expertCaEngin;
	private Properties configProperties;
	private ELink ca_img;
	private CLabel changeLoginType_btn;
	private Runnable readCaTimer;
	private MyThread checkUpdateThread;
	private Composite message_composite;
	private Label technicalSupportLabel;
	private boolean checkVersionComplate = false;
	private boolean needUpdate = false;
	private ImageButton config_btn;
	
	private Logger LOG = Logger.getLogger(LoginDialog.class);	

	
	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		SwtUtils.setCenter(shell);
//		createTrayItem();
//		shell.setMaximized(true);
		ScreenUtils  util = new ScreenUtils();
		//计算电脑屏幕空间，电脑显示屏 整个 高度减去任务栏高度
		int screenHight  = util.getScreenHight() -util.getTaskBarHight();
		shell.setSize(util.getScreenWight(),screenHight);
		shell.setLocation(0, 0);//设置窗口显示位置
		shell.open();
		while (!shell.isDisposed()) {
			try {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			} catch (AppApplicationException e) {
				LOG.error("终止系统运行异常："+e.toString());
			}
		}
	}


	/**
	 * Create contents of the window.
	 * @wbp.parser.entryPoint
	 */
	protected void createContents() {
		shell = new Shell(SWT.NO_TRIM);
		shell.setSize(1176, 716);
		shell.setBackgroundMode(SWT.INHERIT_FORCE);
		shell.addShellListener(new ShellAdapter() {
			@Override
			public void shellClosed(ShellEvent e) {
				disposite();
			}
		});
		shell.setText(Messages.Terminal_management);
		shell.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/evaluation-ico.png"));
		shell.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID,"icons/login/bg.jpg"));
		shell.setLayout(new GridLayout(1, false));
		
		centerComposite = new Composite(shell, SWT.NONE);
		centerComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
		centerComposite.setLayout(new GridLayout(1, false));
		
		sys_icon = new CLabel(centerComposite, SWT.NONE);
		sys_icon.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, false, 1, 1));
		sys_icon.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, Messages.LoginDialog_logoIco));
		sys_icon.setText("");
		
		login_content = new Composite(centerComposite, SWT.NONE);
		GridLayout gl_login_content = new GridLayout(2, true);
		gl_login_content.marginHeight = 0;
		gl_login_content.horizontalSpacing = 0;
		login_content.setLayout(gl_login_content);
		login_content.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
		
		Composite composite_1 = new Composite(login_content, SWT.NONE);
		GridData gd_composite_1 = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1);
		gd_composite_1.widthHint = 300;
		composite_1.setLayoutData(gd_composite_1);
		composite_1.setLayout(new GridLayout(1, false));
		
		CLabel lblNewLabel = new CLabel(composite_1, SWT.NONE);
		lblNewLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/pc.png"));
		lblNewLabel.setText("");
		
		Composite loginFormParent_composite = new Composite(login_content, SWT.NONE);
		GridData gd_loginFormParent_composite = new GridData(SWT.LEFT, SWT.FILL, true, true, 1, 1);
		gd_loginFormParent_composite.widthHint = 300;
		loginFormParent_composite.setLayoutData(gd_loginFormParent_composite);
		GridLayout gl_loginFormParent_composite = new GridLayout(1, false);
		gl_loginFormParent_composite.marginHeight = 0;
		gl_loginFormParent_composite.verticalSpacing = 0;
		gl_loginFormParent_composite.marginWidth = 0;
		loginFormParent_composite.setLayout(gl_loginFormParent_composite);
		
		Composite loginType_title_composite = new Composite(loginFormParent_composite, SWT.NONE);
		GridLayout gl_loginType_title_composite = new GridLayout(3, false);
		gl_loginType_title_composite.marginWidth = 0;
		gl_loginType_title_composite.marginHeight = 0;
		loginType_title_composite.setLayout(gl_loginType_title_composite);
		loginType_title_composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		Label label_3 = new Label(loginType_title_composite, SWT.NONE);
		GridData gd_label_3 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_label_3.widthHint = 70;
		label_3.setLayoutData(gd_label_3);
		label_3.setText("");
		
		loginType_label = new Label(loginType_title_composite, SWT.NONE);
		loginType_label.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		loginType_label.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.BOLD));
		loginType_label.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, false, 1, 1));
		loginType_label.setText(Messages.LoginDialog_accountLogin);
		
		changeLoginType_btn = new CLabel(loginType_title_composite, SWT.NONE);
		GridData gd_changeLoginType_btn = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
		gd_changeLoginType_btn.heightHint = 50;
		gd_changeLoginType_btn.widthHint = 70;
		changeLoginType_btn.setLayoutData(gd_changeLoginType_btn);
		changeLoginType_btn.setText("");
		
		loginForm_composite = new Composite(loginFormParent_composite, SWT.NONE);
		loginForm_composite.setLayout(loginFormStackLayout);
		loginForm_composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
		
		account_composite = new Composite(loginForm_composite, SWT.NONE);
		
		GridLayout gl_account_composite = new GridLayout(1, false);
		gl_account_composite.verticalSpacing = 10;
		gl_account_composite.horizontalSpacing = 0;
		gl_account_composite.marginWidth = 0;
		gl_account_composite.marginHeight = 0;
		account_composite.setLayout(gl_account_composite);
		
		account_form = new Composite(account_composite, SWT.NONE);
		account_form.setBackgroundMode(SWT.INHERIT_FORCE);
		GridData gd_composite_username = new GridData(SWT.CENTER, SWT.BOTTOM, true, true, 1, 1);
		gd_composite_username.heightHint = 40;
		gd_composite_username.widthHint = 279;
		account_form.setLayoutData(gd_composite_username);
		GridLayout gl_composite_username = new GridLayout(3, false);
		gl_composite_username.horizontalSpacing = 8;
		account_form.setLayout(gl_composite_username);
		
		CLabel lblNewLabel_1 = new CLabel(account_form, SWT.NONE);
		lblNewLabel_1.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/user.png"));
		lblNewLabel_1.setText("");
		
		account_text = new Text(account_form, SWT.NO_BACKGROUND | SWT.DRAW_TAB);
		account_text.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				if(account_text.getText().trim().length() == 0){
					e.gc.drawText(Messages.LoginDialog_accountInput, 1, 0, true);
				}
			}
		});
		account_text.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		account_text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
		account_text.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
		
		CLabel label = new CLabel(account_form, SWT.NONE);
		label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1));
		label.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		label.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		label.setFont(SWTResourceManager.getFont("微软雅黑", 18, SWT.BOLD));
		label.setText("∨");
		label.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				showLoginHistoryAction();
			}
		});
		
		password_form = new Composite(account_composite, SWT.NONE | SWT.DRAW_TAB);
		GridData gd_composite_password = new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1);
		gd_composite_password.heightHint = 40;
		gd_composite_password.widthHint = 279;
		password_form.setLayoutData(gd_composite_password);
		GridLayout gl_composite_5 = new GridLayout(2, false);
		gl_composite_5.horizontalSpacing = 8;
		password_form.setLayout(gl_composite_5);
		
		CLabel label_9 = new CLabel(password_form, SWT.VERTICAL);
		label_9.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/password.png"));
		label_9.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, true, 1, 1));
		
		pwd_text = new Text(password_form, SWT.PASSWORD);
		pwd_text.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		pwd_text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
		pwd_text.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
		pwd_text.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				if(pwd_text.getText().trim().length() == 0){
					e.gc.drawText(Messages.LoginDialog_passwordInput, 1, 0, true);
				}
			}
		});
		
		login_btn = new ImageButton(account_composite, SWT.NONE);
		login_btn.setText(Messages.LoginDialog_login);
		login_btn.setBackground(SWTResourceManager.getColor(124, 203, 23));
		login_btn.setActiveBgColor(SWTResourceManager.getColor(255, 153, 0));
		login_btn.setActiveForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		login_btn.setArcWidth(6);
		login_btn.setActiveForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		login_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				loginAction();
			}
		});
		login_btn.setAlignment(SWT.CENTER);
		login_btn.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		login_btn.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.BOLD));
		GridData gd_login_btn = new GridData(SWT.CENTER, SWT.TOP, false, true, 1, 1);
		gd_login_btn.widthHint = 279;
		gd_login_btn.heightHint = 40; 
		login_btn.setLayoutData(gd_login_btn);
		
		ca_composite = new Composite(loginForm_composite, SWT.NONE);
		GridLayout gl_ca_composite = new GridLayout(1, false);
		ca_composite.setLayout(gl_ca_composite);
		
		lblca = new Label(ca_composite, SWT.WRAP);
		lblca.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		lblca.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridData gd_lblca = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
		gd_lblca.widthHint = 200;
		lblca.setLayoutData(gd_lblca);
		lblca.setText(Messages.LoginDialog_caLoginTips);
		
		ca_form = new Composite(ca_composite, SWT.NONE);
		ca_form.setBackgroundMode(SWT.INHERIT_FORCE);
		GridData gd_ca_form_username = new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1);
		gd_ca_form_username.heightHint = 40;
		gd_ca_form_username.widthHint = 279;
		ca_form.setLayoutData(gd_ca_form_username);
		GridLayout gl_ca_form_username = new GridLayout(3, false);
		gl_ca_form_username.horizontalSpacing = 8;
		ca_form.setLayout(gl_ca_form_username);
		
		ca_img = new ELink(ca_form, SWT.NONE);
		ca_img.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				configCaAction();
			}
		});
		ca_img.setCursor(ResourceManager.getCursor(SWT.CURSOR_HAND));
		ca_img.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/key.png"));
		ca_img.setToolTipText(Messages.LoginDialog_selectCaType);
		
		ca_text = new Text(ca_form, SWT.NO_BACKGROUND | SWT.DRAW_TAB | SWT.READ_ONLY);
		ca_text.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				if(ca_text.getText().trim().length() == 0){
					e.gc.drawText(Messages.LoginDialog_selectCa, 1, 0, true);
				}
			}
		});
		ca_text.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		ca_text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
		ca_text.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
		
		CLabel caSelect_label = new CLabel(ca_form, SWT.NONE);
		caSelect_label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1));
		caSelect_label.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		caSelect_label.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		caSelect_label.setFont(SWTResourceManager.getFont("微软雅黑", 18, SWT.BOLD));
		caSelect_label.setText("∨");
		caSelect_label	.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				showCaListAction();
			}
		});
		
		caLogin_btn = new ImageButton(ca_composite, SWT.NONE);
		caLogin_btn.setText(Messages.LoginDialog_login);
		caLogin_btn.setBackground(SWTResourceManager.getColor(124, 203, 23));
		caLogin_btn.setActiveBgColor(SWTResourceManager.getColor(255, 153, 0));
		caLogin_btn.setActiveForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		caLogin_btn.setArcWidth(6);
		caLogin_btn.setActiveForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		caLogin_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				caLoginAction();
			}
		});
		caLogin_btn.setAlignment(SWT.CENTER);
		caLogin_btn.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		caLogin_btn.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.BOLD));
		GridData gd_caLogin_btn_btn = new GridData(SWT.CENTER, SWT.TOP, false, true, 1, 1);
		gd_caLogin_btn_btn.heightHint = 40; 
		gd_caLogin_btn_btn.widthHint = 279;
		
		caLogin_btn.setLayoutData(gd_caLogin_btn_btn);
		
		composite_4 = new Composite(ca_composite, SWT.NONE);
		composite_4.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		composite_4.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1));
		GridLayout gl_composite_4 = new GridLayout(2, false);
		gl_composite_4.horizontalSpacing = 0;
		gl_composite_4.verticalSpacing = 0;
		composite_4.setLayout(gl_composite_4);
		
		
		lblusbkey = new Label(composite_4, SWT.NONE | SWT.WRAP);
		lblusbkey.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		lblusbkey.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		lblusbkey.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		lblusbkey.setText(Messages.LoginDialog_installCaDriverTips);
		new Label(composite_4, SWT.NONE);
		
		Composite composite = new Composite(shell, SWT.NONE);
		GridLayout gl_composite = new GridLayout(4, false);
		gl_composite.marginBottom = 30;
		gl_composite.horizontalSpacing = 0;
		gl_composite.marginRight = 80;
		gl_composite.marginLeft = 80;
		composite.setLayout(gl_composite);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		
		Label label_4 = new Label(composite, SWT.NONE);
		GridData gd_label_4 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_label_4.widthHint = 115;
		label_4.setLayoutData(gd_label_4);
		
		technicalSupportLabel = new Label(composite, SWT.NONE);
		technicalSupportLabel.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		technicalSupportLabel.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
		technicalSupportLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1));
		technicalSupportLabel.setText(Messages.TechnicalSupport);
		
		ImageButton cancel_btn = new ImageButton(composite, SWT.NONE);
		cancel_btn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
		cancel_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				cancelLogin();
			}
		});
		cancel_btn.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/close.png"));
		cancel_btn.setActiveBgImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/close-enter.png"));
		cancel_btn.setText("");
		
		Composite composite_8 = new Composite(composite, SWT.NONE);
		composite_8.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
		GridLayout gl_composite_8 = new GridLayout(2, false);
		gl_composite_8.verticalSpacing = 0;
		gl_composite_8.horizontalSpacing = 0;
		gl_composite_8.marginHeight = 0;
		gl_composite_8.marginWidth = 0;
		composite_8.setLayout(gl_composite_8);
		
		config_btn = new ImageButton(composite_8, SWT.NONE);
		config_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				configAction();
			}
		});
		config_btn.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/config.png"));
		config_btn.setActiveBgImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/config-enter.png"));
		config_btn.setText("");
		
		loginMenuLabel = new ImageButton(composite_8, SWT.NONE);
		loginMenuLabel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				showMoreMenu();
			}
		});
		loginMenuLabel.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/more.png"));
		loginMenuLabel.setActiveBgImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/more-enter.png"));
		loginMenuLabel.setText("");
		
		
		message_composite = new Composite(centerComposite, SWT.NONE);
		message_composite.setLayout(new GridLayout(1, false));
		GridData gd_composite_2 = new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1);
		gd_composite_2.heightHint = 59;
		message_composite.setLayoutData(gd_composite_2);
		
		product_info = new CLabel(message_composite, SWT.NONE);
		product_info.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, true, 1, 1));
		product_info.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
		product_info.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		product_info.setText("电子开评标－项目管理 V4.0");
		
		Composite composite_9 = new Composite(shell, SWT.NONE);
		composite_9.setLayout(new GridLayout(1, false));
		composite_9.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, false, 1, 1));
		
		messageLabel = new Label(composite_9, SWT.NONE);
		messageLabel.setAlignment(SWT.CENTER);
		messageLabel.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		GridData gd_label_6 = new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1);
		gd_label_6.widthHint = 500;
		messageLabel.setLayoutData(gd_label_6);
		init();
	}
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		userService = new UserService();
		userLoginRecordService = new UserLoginRecordService();
		product_info.setText(Messages.Terminal_management + " "+PropertiesUtils.getProperty(ConfigConstants.VERSION,"V4.0"));
		String productTitle = PropertiesUtils.getProperty(ConfigConstants.MANAGEMENT_TITLE,"");
		if(null != productTitle && productTitle.length() > 0) {
			product_info.setText(productTitle);
		}
		login_btn.setEnabled(false);
		String technicalSupport = PropertiesUtils.getProperty(ConfigConstants.TECHNICAL_SUPPORT, "");
		technicalSupport = technicalSupport.trim();
		if(technicalSupport.equals("gx")){
			technicalSupportLabel.setText("");
		}else if(technicalSupport.length() > 4){
			technicalSupportLabel.setText(Messages.TechnicalSupport);
		}
		String productType = PropertiesUtils.getProperty(ConfigConstants.PRODUCT_TYPE, "");
		if(ConfigConstants.PRODUCT_TYPE_FINAL.equals(productType)) {
			WidgetUtils.setControlVisible(config_btn, false);
		}else if(ConfigConstants.PRODUCT_TYPE_TEST.equals(productType)) {
			product_info.setText(product_info.getText() + "("+Messages.Config_productTest+")");
		}
		if(PropertiesUtils.getProperty("HIDE_CONFIG", "").equals("01")) {
			WidgetUtils.setControlVisible(config_btn, false);
		}
		checkSecurityCert();
		
		checkNewVersion();
		// 初始化各类监听事件
		initListener();
		
		// 检测服务连接情况
		checkConnection();
		
		if(PropertiesUtils.getProperty(ConfigConstants.USE_CA_LOGIN, "00").equals("01")){
			changeLoginType_btn.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseUp(MouseEvent e) {
					changeLoginType(!caLogin);
				}
			});
			changeLoginType_btn.setText("");
			changeLoginType_btn.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			caLogin = PropertiesUtils.getProperty(ConfigConstants.CA_LOGIN, "01").equals("01");
		}
		
		readCaTimer = new Runnable () {  
			public void run () {
				if(null == expertCaEngin){
					expertCaEngin = CAEngineFactory.getCaIngine(null);
				}
				if(null != expertCaEngin && !ca_text.isDisposed()){
					List<CACert> caList = expertCaEngin.readCaCertList();
					if(null != caList && caList.size() > 0){
						ManagementApplication.EXPERT_CERT = caList.get(0);
						ca_text.setText(ManagementApplication.EXPERT_CERT.getAuthor());
					}else {
						ManagementApplication.EXPERT_CERT = null;
						if(!"".equals(ca_text.getText())){
							ca_text.setText("");
						}
						Display.getDefault().timerExec(1500, this);
					}
				}
			}  
		}; 
		Runnable timer = new Runnable () {  
	        public void run () {
	        	changeLoginType(caLogin);
	        }  
	     }; 
	     Display.getDefault().timerExec(10,timer);  
	}
	
	private void checkSecurityCert(){

		/**
		 * 第三层验证
		 * **/
		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(MessageFormat.format(Messages.Cert_invalidTips, new Object[] {certificate.getIssuer()}));
			}
			Date nowTime = com.gx.security.NowTimeUtils.getNowDate();
			if (certificate.getExpiresDate().before(nowTime)) {
				throw new com.gx.security.SecurityRuntimeException(MessageFormat.format(Messages.Cert_expiredTips, new Object[] {certificate.getIssuer()}));
			}else {
				long times = (certificate.getExpiresDate().getTime() - nowTime.getTime()) / 1000;
				long nDay = times / 86400;
				long nHour = (times - nDay * 86400) / 3600;
				if(nHour > 1){
					nDay += 1;
				}
				if(nDay <= 10){
					Label label = new Label(message_composite, SWT.CENTER); 
					label.setForeground(SWTResourceManager.getColor(255, 0, 0));
					label.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, true, 1, 1));
					label.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
					label.setText(MessageFormat.format(Messages.Cert_expiredTips, new Object[] {nDay}));
				}
			}
			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(MessageFormat.format(Messages.Cert_unauthorizedMachine, new Object[] {certificate.getMotherBoardSN(), certificate.getIssuer()}));
				}
			}
			if (valMac && null != certificate.getMac()) {
				if (!certificate.getMac().contains(com.gx.security.CertValidator.getInstance().getMac())) {
					throw new com.gx.security.SecurityRuntimeException(MessageFormat.format(Messages.Cert_unauthorizedMachine, new Object[] {certificate.getMac(), certificate.getIssuer()}));
				}
			}
		} catch (Exception e) {
			throw new com.gx.security.SecurityRuntimeException(e);
		}
	}
	
	/**
	 * @Description: 检测新版本
	 * @author guoyr 
	 */
	private void checkNewVersion(){
		if(PropertiesUtils.getProperty(ConfigConstants.CHECK_NEW_VERSION, "01").equals("01")){
			showLoginMessage(Messages.LoginDialog_newVersionChecking);
			checkUpdateThread = new CheckUpdateThread(new CheckUpdateVersionListener(){
				public void updateVersion(final String version, final boolean forceUpdate, final String downUrl, final long fileSize, final String memo) {
					checkVersionComplate = true;
					if(null != downUrl && downUrl.length() > 0){
						showLoginMessage(Messages.LoginDialog_checkedNewVersion);
						Display.getDefault().syncExec(new Runnable(){
							public void run(){
								if(forceUpdate){
									needUpdate = true;
									MessageDialog.openInformation(shell, Messages.LoginDialog_checkedNewVersionTips);
									updateAction();
								}else {
									if(MessageDialog.openConfirm(shell, Messages.LoginDialog_updateTitle, Messages.LoginDialog_updateTips, new String[]{Messages.LoginDialog_btn_update, Messages.LoginDialog_btn_notUpdate})){
										needUpdate = true;
										updateAction();
									}
								}
							}
						});
					}
				}
			});
			checkUpdateThread.start();
		}
	}
	
	/**
	 * @Description: 连接服务器
	 * @author guoyr 
	 */
	private void checkConnection(){
		showLoginMessage(Messages.LoginDialog_serverChecking);
		connectSuccess = false;
		conntectThread = new Thread(new Runnable(){
			public void run(){
				boolean connect = NetWorkUtils.isConnNet(Constants.getServiceUrl("connection/"));
				connectionAfterAction(connect);
			}
		});
		conntectThread.start();
	
	}
	
	/**
	 * @Description: 切换登录方式
	 * @author guoyr 
	 */
	private void changeLoginType(boolean caLogin){
		this.caLogin = caLogin;
		PropertiesUtils.saveProperty(ConfigConstants.CA_LOGIN, caLogin ? "01" : "00");
		if(caLogin){
			loginFormStackLayout.topControl = ca_composite;
			loginType_label.setText(Messages.LoginDialog_caLogin);
			Display.getDefault().timerExec(0,readCaTimer);  
		}else {
			ManagementApplication.EXPERT_CERT = null;
			ca_text.setText("");
			Display.getDefault().timerExec(-1, readCaTimer);
			loginFormStackLayout.topControl = account_composite;
			loginType_label.setText(Messages.LoginDialog_accountLogin);
		}
		loginForm_composite.layout();
		
		fillBgImage();
	}
	
	/**
	 * @Description: 绘制登录界面的透明背景样式
	 * @author guoyr 
	 */
	private void fillBgImage(){
//		loginBgImage = imageResolver.getImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID,"icons/login/bg.jpg"), shell.getBounds().width, shell.getBounds().height);
		if(null != loginBgImage && !loginBgImage.isDisposed()){
			loginBgImage.dispose();
		}
		loginBgImage = new Image(null, shell.getBounds().width, shell.getBounds().height);//imageResolver.getImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID,"icons/login/bg.jpg"), shell.getBounds().width, shell.getBounds().height);
		GC gc = new GC(loginBgImage);
		Image bgCenterImage = imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/login/bgCenter.png");
		Point loginFormPoint = Display.getDefault().map(login_content, shell , 0,0);
		Image _image = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID,"icons/login/bg.jpg");
		gc.drawImage(_image, 0, 0, _image.getBounds().width, _image.getBounds().height, 0, 0, shell.getBounds().width, shell.getBounds().height);
		gc.drawImage(bgCenterImage, (shell.getBounds().width - bgCenterImage.getBounds().width)/2, loginFormPoint.y); 
		Image formBgImage = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/login/input_bg.png");
		Image changeImage = imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/login/ca-login.png");
		if(caLogin){
			Point accountFormPoint = Display.getDefault().map(ca_form, shell , 0,0);
			gc.drawImage(formBgImage, accountFormPoint.x, accountFormPoint.y);
			changeImage = imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/login/account-login.png");
		}else {
			Point accountFormPoint = Display.getDefault().map(account_form, shell , 0,0);
			Point passwordFormPoint = Display.getDefault().map(password_form, shell , 0,0);
			gc.drawImage(formBgImage, accountFormPoint.x, accountFormPoint.y);
			gc.drawImage(formBgImage, passwordFormPoint.x, passwordFormPoint.y);
			account_text.forceFocus();
		}
		if(PropertiesUtils.getProperty(ConfigConstants.USE_CA_LOGIN, "00").equals("01")){
			Point changeLoginTypePoint = Display.getDefault().map(changeLoginType_btn, shell , 0,0);
			gc.drawImage(changeImage, changeLoginTypePoint.x, changeLoginTypePoint.y);
		}
		shell.setBackgroundImage(loginBgImage);
		gc.dispose();
	}
	
	/**
	 * @Description: 初始化各类监听事件
	 * @author guoyr
	 */
	private void initListener(){
		// 加入加回车事件
		new KeyEnterListener(shell, new CallBack(){
			@Override
			public void callBack() {
				if(caLogin){
					caLoginAction();
				}else {
					loginAction();
				}
			}
		});
		SwtUtils.setMouseDragListener(sys_icon);
		SwtUtils.setMouseDragListener(centerComposite);
		sys_icon.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				shell.setMaximized(!shell.getMaximized());
			}
		});
		shell.addControlListener(new ControlAdapter() {
			@Override
			public void controlResized(ControlEvent e) {
				shell.addPaintListener(new PaintListener() {
					public void paintControl(PaintEvent arg0) {
						shell.removePaintListener(this);
						fillBgImage();
					}
				});
			}
		});
		
		final Listener keyListener = new Listener() {
			public void handleEvent(Event e) {
				if ((e.stateMask == SWT.CTRL) && e.keyCode == 'g'){
					WidgetUtils.setControlVisible(config_btn, !config_btn.getVisible());
					config_btn.getParent().layout();
					config_btn.getParent().getParent().layout();
				}
			}
		};
		config_btn.getDisplay().addFilter(SWT.KeyDown, keyListener);
		shell.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				config_btn.getDisplay().removeFilter(SWT.KeyDown, keyListener);  
			}
		});
	
	}
	
	
	/**
	 * @Description: 登录
	 * @author guoyr
	 */
	private void loginAction(){
		if(!login_btn.getEnabled())return;
		// 登录账号和密码非空验证，不弹出提示，直接光标定位
		if(account_text.getText().trim().equals("")){
			account_text.setFocus();
		}else if(pwd_text.getText().trim().equals("")){
			pwd_text.setFocus();
		}else{
			login_btn.setEnabled(false);
			new LoginThread().start();
		}
	}
	
	/**
	 * @Description: 登录
	 * @author guoyr
	 */
	private void caLoginAction(){
		if(!caLogin_btn.getEnabled())return;
		// 登录账号和密码非空验证，不弹出提示，直接光标定位
		if(ca_text.getText().trim().equals("")){
			ca_text.setFocus();
		}else{
			caLogin_btn.setEnabled(false);
			new CALoginThread().start();
		}
	}
	
	/**
	 * @Description: 验证是否已登录
	 * @author guoyr
	 * @return 
	 */
	private boolean isLogining(){
		if(null == userLoginRecordService){
			userLoginRecordService = new UserLoginRecordService();
		}
		AuthLoginRecordEntity loginRecord = userLoginRecordService.getAccountByLoginInfo(tempUser.getUserAccount(),Constants.TERMINAL_MANAGEMENT);
		SimpleDateFormat famat = new SimpleDateFormat(Messages.Format_dateTimeStr);
		if(null != loginRecord){
			String msg = MessageFormat.format(Messages.LoginDialog_alreadyLogged, new Object[] {famat.format(loginRecord.getLoginTime()), loginRecord.getIp()});
			
			// 如果登录超过24小时，则认为是异常退出，则可以直接登录
			long useTimes = NowTimeUtils.getNowDate().getTime() - loginRecord.getLoginTime().getTime();
			double result = useTimes *1.0 / (1000 * 60 * 60); 
			
			if(result>=24){ 
				userLoginRecordService.deleteAccountByLoginInfo(tempUser.getUserAccount(),Constants.TERMINAL_MANAGEMENT);
			}else if(MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.Dialog_warmTips, msg, new String[]{Messages.Button_confirm, Messages.Button_cancel})){
				userLoginRecordService.deleteAccountByLoginInfo(tempUser.getUserAccount(),Constants.TERMINAL_MANAGEMENT);
			} else {
				return false;
			}
		}
		return true;
	}
	
	private AuthRole getUserType(List<AuthRole> roleList){
		SelectUserRoleTypeDialog userRoleTypeDialog = new SelectUserRoleTypeDialog(shell, roleList);
		userRoleTypeDialog.open();
		return userRoleTypeDialog.getAuthRole();
	}
	
	/**
	 * @Description: 获得登录权限
	 * @author guoyr
	 * @return 
	 */
	private AuthRole getAuthRole(){
		AuthRole selectAuthRole = null;
		userRoleService.initUserRole(tempUser.getId(), UserEnum.ROLE_TYPE_EVALUATION_MANAGER);
		List<AuthRole> roleList = userService.getUserRoleList(Constants.TERMINAL_MANAGEMENT,tempUser.getId(),UserEnum.ROLE_TYPE_SYSTEM_MANAGER); 
		if(null != roleList && roleList.size() > 0){
			if(roleList.size() > 1){
				selectAuthRole = getUserType(roleList);
			}else {
				selectAuthRole = roleList.get(0);
			}
		}
		tempUser.setAuthRole(selectAuthRole);
		return selectAuthRole;
	}
	/**
	 * @Description: 验证登录用户
	 * @author guoyr
	 * @return 
	 */
	private boolean valLoginUser(String account, String pwd){
		UserLogin userLogin = new UserLogin();
		BooleanResultDO  booleanResultDO = userLogin.loginUser(account,  pwd);
		if(null == booleanResultDO) {
			MessageDialog.openShortMessage("登录异常！");
			return false;	
		}
		if(booleanResultDO.isStatus()) {
			tempUser = Constants.USER;
			AuthRole authRole = getAuthRole();
			if(null != authRole){
				if(ObjectUtils.equals(tempUser.getUseStatus(), CommonEnum.REAL_STATUS)){
					// 验证是否已登录
					return isLogining();
				}else{
					MessageDialog.openShortMessage(Messages.LoginDialog_accountCanceled);
					return false;
				}
			}else {
				account_text.setFocus();
				MessageDialog.openShortMessage(Messages.LoginDialog_noAuthority);
				return false;
			}
		}else {
			account_text.setFocus();
//			MessageDialog.openShortMessage(Messages.LoginDialog_passwordError +ObjectUtils.getObjString(booleanResultDO.getStrMessage()));
			MessageDialog.openShortMessage(ObjectUtils.getObjString(booleanResultDO.getStrMessage()));
			return false;
		}
	}
	
	/**
	 * @Description: 验证登录用户
	 * @author guoyr
	 * @return 
	 */
	private boolean valCaLoginUser(){
		
		if(null != expertCaEngin){
			if(!expertCaEngin.loginCa(ManagementApplication.EXPERT_CERT)){
				return false;
			}
			
			// 验证用户名和密码是否正确
			tempUser = userService.caLogin(ManagementApplication.EXPERT_CERT.getAuthor(), ManagementApplication.EXPERT_CERT.getCertId());
			// 验证成功后，判读是否有登录该终端的权限
			if(null != tempUser){
				
				boolean hasAuthority = userService.valLoginAuthority(tempUser.getId(), Constants.TERMINAL_MANAGEMENT);
				if(hasAuthority){
					
					if(ObjectUtils.equals(tempUser.getUseStatus(), CommonEnum.REAL_STATUS)){
						// 验证是否已登录
						return isLogining();
					}else {
						MessageDialog.openShortMessage(Messages.LoginDialog_userCanceled);
						return false;
					}
				}else {
					account_text.setFocus();
					MessageDialog.openShortMessage(Messages.LoginDialog_noAuthority);
				}
			}else {
				MessageDialog.openShortMessage(Messages.LoginDialog_notExistUser);
			}
		}
		
		return false;
	}
	
	
	/**
	 * @Description: 取消
	 * @author guoyr
	 */
	private void cancelLogin(){
		loginType = IApplication.EXIT_OK;
		shell.close();
	}
	

	/**
	 * @Description: 显示登录消息
	 * @author guoyr
	 * @param msg 
	 */
	private void showLoginMessage(final String msg){
		Display.getDefault().syncExec(new Runnable() {
			public void run() {
				if(!messageLabel.isDisposed() && null != msg){
					messageLabel.setText(msg);
				}
			}
		});
	}
	
	/**
	 * @Description: 显示更多菜单
	 * @author guoyr
	 */
	private void showMoreMenu(){

		final EMenu gmenu = new EMenu(this.shell);
		gmenu.addMenuItem(Messages.About, imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/btn/blue/about.png"), true, new EMenu.ClickListener() {
			public void click() {
				AboutDialog aboutDialog = new AboutDialog(shell, SWT.NONE);
				aboutDialog.open();
			}
		});
		gmenu.addMenuItem(Messages.LoginDialog_updateTitle, imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/btn/blue/update.png"), true,new EMenu.ClickListener() {
			public void click() {
				updateAction();
			}
		});
		gmenu.addMenuItem(Messages.LoginDialog_environment, imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/btn/blue/lan.png"), true, new EMenu.ClickListener() {
			public void click() { 
				 environmentalMonitoringAction();
			}
		});
		gmenu.addMenuItem(Messages.Config_setProxy, imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/btn/blue/config.png"), true,new EMenu.ClickListener() {
			public void click() {
				proxyConfigAction();
			}
		});
		gmenu.addMenuItem(Messages.Cert_importCert, imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/btn/blue/import.png"), true, new EMenu.ClickListener() {
			public void click() { 
				CertificateValidationDialog licenseValidationDialog = new CertificateValidationDialog(shell);
				licenseValidationDialog.open();
				checkSecurityCert();
			}
			
		});
		gmenu.addMenuItem(Messages.Restart, imageResolver.loadImage(IconsActivator.PLUGIN_ID,"icons/btn/blue/reStart.png"), true, new EMenu.ClickListener() {
			public void click() {
				shell.close();
				loginType = IApplication.EXIT_RESTART;
			}
			
		});
		gmenu.open(loginMenuLabel);
	}

	/**
	 * @Description: 获得窗口的状态
	 * @author guoyr
	 * @return
	 */
	public int getLoginType(){
		return loginType;
	}
	/**
	 * @Description: 释放资源
	 * @author guoyr
	 */
	private void disposite(){
		if(null != expertCaEngin){
			expertCaEngin.releaseCa();
		}
		imageResolver.disposite();
		if(null != loginBgImage && !loginBgImage.isDisposed()){
			loginBgImage.dispose();
			loginBgImage = null;
		}
	}
	
//	/**
//	 * @Description: 打开软键盘
//	 * @author guoyr
//	 */
//	private void openKeybord(){
////		passWord.setFocus();
//		new Thread(new Runnable() {
//		      public void run() {
//		    	  try {
//		  			Runtime.getRuntime().exec("cmd /c osk");
//		  		} catch (IOException e) {
//		  		}
//		      }
//		    }).start();
//	}
	
	/**
	 * @Description: 系统检查更新
	 * @author guoyr
	 */
	private void updateAction(){
		UpdateDialog dialog = new UpdateDialog(shell);
		dialog.open();
		if(dialog.getUpdateType()== UpdateDialog.UPDATE_EXIT){
			loginType = IApplication.EXIT_OK;
			shell.close();
		}if(dialog.getUpdateType()== UpdateDialog.UPDATE_RESTART){
			loginType = IApplication.EXIT_RESTART;
			shell.close();
		}
	}
	
	/**
	 * @Description: 环境检测
	 * @author wangxiang
	 */
	private void environmentalMonitoringAction(){
		EnvironmentTestDialog dialog = new EnvironmentTestDialog(shell,SWT.NO_TRIM);
		dialog.open();
	}

	/**
	 * @Description: 系统配置
	 * @author guoyr
	 */
	private void configAction(){
		ConfigDialog configDialog = new ConfigDialog(shell);
		configDialog.open();
		if(configDialog.isSaveSuccess()){
			loginType = IApplication.EXIT_RESTART;
			shell.close();
		}
	}
	/**
	 * @Description: 系统配置
	 * @author guoyr
	 */
	private void proxyConfigAction(){
		ProxyConfigDialog configDialog = new ProxyConfigDialog(shell);
		configDialog.open();
		if(configDialog.isSaveSuccess()){
			loginType = IApplication.EXIT_RESTART;
			shell.close();
		}
	}
	
	/**
	 * @Description: 
	 * @author guoyr
	 * @param connectonSuccess
	 */
	private void connectionAfterAction(boolean connectonSuccess){
		this.connectSuccess = connectonSuccess;
		if(connectonSuccess){
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					if(null != login_btn && !login_btn.isDisposed()){
						login_btn.setEnabled(true);
						showLoginMessage("");
						if(StringUtils.isEmpty(PropertiesUtils.getProperty("ENVIRONMENT", ""))){
							environmentalMonitoringAction();
						}
					}
				}
			});
			// 标记该机位使用
//			new MachineThread(false, Constants.TERMINAL_MANAGER).start();
			
			// 验正该机位是否允许使用
			valEvalBidRoomMachine = new Thread(new ValEvalBidRoomMachine());
			valEvalBidRoomMachine.start();
		}else {
			if(null != checkUpdateThread){
				checkUpdateThread.join();
			}
			if(needUpdate){
				return;
			}
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					if(null != messageLabel && !messageLabel.isDisposed()){
						showLoginMessage(Messages.LoginDialog_connectionFail);
						MessageDialog.openWarning(shell, Messages.Dialog_warmTips, Messages.LoginDialog_connectionFail);
						shell.close();
					
					}
				}
			});
		}
	}
	
	/**
	 * @Description: 验证评标室机位
	 * @author guoyr
	 */
	private class ValEvalBidRoomMachine implements Runnable {
		public void run() {
			valMachineSuccess = false;
			final String machineSequence = CertValidator.getInstance().getSequence();
			final String ipAddress = SystemTool.getIp();
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					if(null != macLabel && !macLabel.isDisposed()){
						macLabel.setText(Messages.LoginDialog_machineCode +"："+ machineSequence);
						ipLabel.setText(Messages.LoginDialog_machineIP+"："+ ipAddress);
					}
				}
			});
			
			
			boolean needValMach = PropertiesUtils.getProperty(ConfigConstants.VERIFY_EVAL_MACHINE_MANAGER, "00").equals(CommonEnum.YES);
			// 验证是否是在评标室中设置的机位
			if(needValMach){
				final MachineService machineService = new MachineService();
				List<String> machineList = machineService.getEvalRoomIdByMachineMacAndUseStatus(machineSequence,CommonEnum.REAL_STATUS);
				if(null != machineList && machineList.size() > 0){
					valMachineSuccess = true;
					Constants.CUR_EVALUATION_ROOM_ID = machineList.get(0);
				}else {
					
					// 目前必须要验证机位，因为只有通过机位信息，才能反推出当前处于哪个评标室
					if(PropertiesUtils.getProperty(ConfigConstants.USE_MACHINE_LOCK, "01").equals(CommonEnum.YES)){
						valMachineSuccess = false;
						Display.getDefault().asyncExec(new Runnable() {
							public void run() {
								if(null != messageLabel &&!messageLabel.isDisposed()){
//									messageLabel.setText("评标室机位中不存在该机位信息，不允许使用该机位！");
//									messageLabel.getParent().layout();
									Clipboard clipboard = new Clipboard(Display.getDefault()); 
									TextTransfer textTransfer = TextTransfer.getInstance(); 
									// 剪贴板内容不能随便修改，在添加机位时，会自动检查剪贴板中是否存在机位信息，如果有，会自动解析
									clipboard.setContents(new String[]{Messages.LoginDialog_machineCode+"："+machineSequence+"\r\n"+Messages.LoginDialog_machineIP+"："+ipAddress}, new Transfer[]{textTransfer}); 
									clipboard.dispose(); 
									
									StringBuilder macInfo = new StringBuilder();
									macInfo.append(Messages.LoginDialog_machineCode + "：");
									macInfo.append(machineSequence);
									macInfo.append("\r\n"+Messages.LoginDialog_machineIP+"：");
									macInfo.append(ipAddress);
									macInfo.append("\r\n\r\n " + Messages.LoginDialog_notAllowed);
									if(MessageDialog.openConfirm(shell, Messages.Dialog_warmTips, macInfo.toString(), Messages.Cert_applyCert, Messages.Dialog_close)){
										new ApplyMachineThread(machineSequence, ipAddress).start();
									}
								}
							}
						});
					}else {
						valMachineSuccess = true;
					}
				}
			}else {
				valMachineSuccess = true;
			}
		}
	}

	/**
	 * @Description: 登录线程
	 * @author guoyr
	 */
	private class LoginThread extends Thread {
		public void run() {
			try {
				conntectThread.join();
			} catch (InterruptedException e) {
			}
			if(!connectSuccess){
				return;
			}
			if(null != checkUpdateThread && !checkVersionComplate){
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(!messageLabel.isDisposed()){
							showLoginMessage(Messages.LoginDialog_newVersionChecking);
						}
					}
				});
				checkUpdateThread.join();
			}
			try {
				valEvalBidRoomMachine.join();
			} catch (InterruptedException e) {
			}
			// 如果机位验证失败，则重新启动线程去验证
			if(!valMachineSuccess){
				valEvalBidRoomMachine = null;
				valEvalBidRoomMachine = new Thread(new ValEvalBidRoomMachine());
				valEvalBidRoomMachine.start();
				try {
					valEvalBidRoomMachine.join();
				} catch (InterruptedException e) {
				}
			}
			if(valMachineSuccess){
				if(null == userService){
					userService = new UserService();
				}
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(!login_btn.isDisposed()){
							
							// 设置不能重复登录
							login_btn.setEnabled(false);
							
							if(!valLoginUser(account_text.getText().trim(), pwd_text.getText().trim())){
								login_btn.setEnabled(true);
								return;
							}
							Constants.USER = tempUser;
							Constants.USER.setEncodePassWord(StringUtil.encodeString(pwd_text.getText().trim()));
							loginType = SWT.OK;
							shell.close();
						}
					}
				});
				if(loginType == SWT.OK){
					RefreshTokenTask.getRefreshTokenTask().startTask();
					new LoginCacheThread(tempUser, true).start();
					new UpoladTerminalInfoThread().start();
				}
			}
		}
	}
	
	/**
	 * @Description: ca登录线程
	 * @author guoyr
	 */
	private class CALoginThread extends Thread {
		public void run() {
			try {
				conntectThread.join();
			} catch (InterruptedException e) {
			}
			if(!connectSuccess){
				return;
			}
			if(null != checkUpdateThread && !checkVersionComplate){
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(!messageLabel.isDisposed()){
							showLoginMessage(Messages.LoginDialog_newVersionChecking);
						}
					}
				});
				checkUpdateThread.join();
			}
			try {
				valEvalBidRoomMachine.join();
			} catch (InterruptedException e) {
			}
			// 如果机位验证失败，则重新启动线程去验证
			if(!valMachineSuccess){
				valEvalBidRoomMachine = null;
				valEvalBidRoomMachine = new Thread(new ValEvalBidRoomMachine());
				valEvalBidRoomMachine.start();
				try {
					valEvalBidRoomMachine.join();
				} catch (InterruptedException e) {
				}
			}
			if(valMachineSuccess){
				if(null == userService){
					userService = new UserService();
				}
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(!caLogin_btn.isDisposed()){
							
							// 设置不能重复登录
							caLogin_btn.setEnabled(false);
							if(!valCaLoginUser()){
								caLogin_btn.setEnabled(true);
								return;
							}
							Constants.USER = tempUser;
							loginType = SWT.OK;
							shell.close();
						}
					}
				});
				if(loginType == SWT.OK){
					new LoginCacheThread(tempUser, true).start();
					new UpoladTerminalInfoThread().start();
				}
			}
		}
	}
	
	/**
	 * @Description: 加载登录记录
	 * @author guoyr
	 */
	private void showLoginHistoryAction(){
		Point userNamePoint = account_text.getParent().toDisplay(new Point(0,0));
		Rectangle parentRectangle = account_text.getParent().getBounds();
		if(null == userCacheShell || userCacheShell.isDisposed()){
			userCacheShell = new LoginCacheListShell(shell, new CallBack(){

				@Override
				public void callBackString(String msg) {
					account_text.setText(msg);
					pwd_text.setFocus();
				}
				
			});
			userCacheShell.setBackgroundImage(imageResolver.getImage(shell.getBackgroundImage(), parentRectangle.width, 200));
		}else {
			return;
		}
		userCacheShell.listUserCache();
		userCacheShell.setLocation(userNamePoint.x -1, userNamePoint.y + parentRectangle.height);
		userCacheShell.setAlpha(220);
		int height = userCacheShell.computeSize(parentRectangle.width, SWT.DEFAULT).y;
		userCacheShell.setSize(parentRectangle.width + 2, Math.max(height, 50));
		userCacheShell.open();
	}
	/**
	 * @Description: 加载登录记录
	 * @author guoyr
	 */
	private void showCaListAction(){
		Point userNamePoint = ca_text.getParent().toDisplay(new Point(0,0));
		Rectangle parentRectangle = ca_text.getParent().getBounds();
		if(null == caListShell || caListShell.isDisposed()){
			caListShell = new LoginCaListShell(shell, new CallBack(){
				@Override
				public void callBackObject(Object caObj) {
					ManagementApplication.EXPERT_CERT = null;
					if(null != caObj){
						ManagementApplication.EXPERT_CERT = (CACert)caObj;
						ca_text.setText(ManagementApplication.EXPERT_CERT.getAuthor());
					}
				}
				
			});
			caListShell.setBackgroundImage(imageResolver.getImage(shell.getBackgroundImage(), parentRectangle.width, 200));
		}else {
			return;
		}
//		if(null == expertCaEngin){
//			expertCaEngin = CAEngineFactory.getCaIngine(null);
//		}
		List<CACert> caCertList = null;
		if(null != expertCaEngin){
			caCertList = expertCaEngin.readCaCertList();
		}
		caListShell.listCACert(caCertList);
		caListShell.setLocation(userNamePoint.x -1, userNamePoint.y + parentRectangle.height);
		caListShell.setAlpha(220);
		int height = caListShell.computeSize(parentRectangle.width, SWT.DEFAULT).y;
		caListShell.setSize(parentRectangle.width + 2, height);
		caListShell.open();
	}
	
	/**
	 * @Description: 设置CA
	 * @author guoyr 
	 */
	private void configCaAction(){
		if(!connectSuccess){
			return;
		}
		final String caType = PropertiesUtils.getProperty(ConfigConstants.CA_ENGINE, "");
		DictionaryValueSelectShell dicShell = new DictionaryValueSelectShell(shell, new DictionaryValueSelectShell.DictionaryValueSelected(){

			public void selected(DictionaryValue dictionaryValue) {
				if(null != dictionaryValue){
					if(null == configProperties){
						configProperties = PropertiesUtils.getProperties("config.properties");
					}
					// 如果切换了CA类型，则重新加载
					if(!caType.equals(dictionaryValue.getDictValueCode())){
						if(null != expertCaEngin){
							expertCaEngin.releaseCa();
							expertCaEngin = null;
						} 
						ca_text.setText("");
						Display.getDefault().timerExec(0,readCaTimer); 
						PropertiesUtils.setPropertyValue(ConfigConstants.CA_ENGINE, dictionaryValue.getDictValueCode());
						configProperties.setProperty(ConfigConstants.CA_ENGINE, dictionaryValue.getDictValueCode());
						PropertiesUtils.saveProperties(configProperties);
					}
				}
			}
		});
		dicShell.listDicValue(DictEnum.DIC_CA_TYPE, caType);
		dicShell.setTitle(Messages.LoginDialog_selectCaType);
		dicShell.setLocation(SwtUtils.getFittingPoint(ca_img.toDisplay(-5,ca_img.getBounds().height + 5), dicShell.getSize()));
		dicShell.open();
	}
}
