#!/usr/bin/python
# coding=utf-8
"""
    登录窗口
"""
from time import sleep

from PyQt4.QtCore import SIGNAL, pyqtSlot, QString, QEventLoop, Qt, QVariant, pyqtSignal,QEvent
from PyQt4 import QtGui
from threading import Thread
from PyQt4.QtGui import QApplication, QDialog
from ui_qss.winLoginQss import WinLoginQss
from winVirturlList import WinVirturlList
from setting import SettingDlg
from winDebug import WinDebug  # 调试设置窗口

from sendCmd.operatorVMCmd import OperatorVMCmd
from logger.logrecord import LogRecord
from WaitingDialog import WaitingDialog
from common.info_dialog import InfoDialog


_encoding = QApplication.UnicodeUTF8


def _translate(context, text, disambig):
    return QApplication.translate(context, text, disambig, _encoding)


# ----------------------------------------------------
# import os, sys
# if __name__ == "__main__":
#     _dirs = os.path.abspath(__file__)  # 当前文件路径
#     _dirs = os.path.dirname(_dirs)     # 当前文件目录
#     sys.path.append(_dirs)             #


from userInfoConfFile.userInfoConf import UserInfoConfFile
from des import Des

from uiWindow.PowerOffDialog import powerListen, PowerOffDialog
from sendCmd.validate.getCenterName import CenterName
from uiWindow.ForeSetting import ForeSetting
from logger.logrecord import LogRecord


# ======================================================

###########################################
# 登 录 窗 口
###########################################
class WinLoginDlg(WinLoginQss):
    '''WinLoginDlg : '''

    def __init__(self, autologinAllow = None ,parent=None):
        super(WinLoginDlg, self).__init__(parent)

        # 登录等待窗口 实例化
        self.__waitingdlg = WaitingDialog()

        # 启动电源键按下事件
        self.powerDialog = PowerOffDialog(login=self)
        self.connect(self.powerDialog, SIGNAL("LOGOUT"), self.clientLogout)
        self.connect(self, SIGNAL("LOGOUT_OVER"), self.powerDialog.logout_over)

        # 电源键监听
        self.powerListen = powerListen(self.powerPressed)
        self.shutDownSignal = pyqtSignal()
        powerListenTh = Thread(target=self.powerListen.listen)
        powerListenTh.setDaemon(True)
        powerListenTh.start()

        self.connect(self, SIGNAL('shutDownSignal'), self.__powerOffShow)
        self.showRDPSignal = pyqtSignal()
        self.hideRDPSignal = pyqtSignal()
        # self.connect(self.powerDialog,SIGNAL('showRDPSignal'),self,SIGNAL('showRDPSignal'))
        # 默认中心序号
        self.defaultIndex = 0
        # 配置网络及平台
        self.foreSetting = ForeSetting()
        self.__checkDefaultCenter()

        self.__band_signal_slot()  # 绑定信号和槽

        self.__button_rememeber_password_clicked = False
        self.__button_auto_login_clicked = False

        # 当前版本 号
        self.curVersion = "4.5.0.20160725"
        self.currentVersion.setText(_translate("Form", "<html><head/><body><p align=\"center\">"
                                                       "当前版本 V%s"
                                                       "</p></body></html>" % self.curVersion, None))

        self.currentCent_ip_port = None
        self.__choose_default_center()  # 更新平台名称列表，并 选择默认平台
        self.setstylesheet_2()          # 记住密码 自动登录 初始化


    # 检查 自动 登录
    def checkAutoLogin(self,autologinAllow):

        #------ 判断 自动  登录
        conf = UserInfoConfFile()       # 实例化配置文件 对象
        # if autologinAllow == None:      #  autologinAllow  == None 允许自动登陆
        if autologinAllow != "Disable":  # autologinAllow  == None 允许自动登陆
            if conf.isAutoLogin():      # 判断是否是 自动登录
                self.auto_login()  # 自动登录
        else:
            print "升级 重启"

    def setstylesheet_2(self): # 分辨率样式改变
        super(WinLoginDlg,self).setstylesheet_2()

        #------------------------------------------------------------
        # 如果 读取 配置 文件 用户名或密码 为空, 清除 记住 用户名 密码  及显示
        # ----------------------------------------------------------
        conf = UserInfoConfFile()      # 实例化配置文件 对象

        if conf.isAutoLogin():  # 判断是否是 自动登录
            self.set_autologin_checked_img()
            self.__button_auto_login_clicked = True     # 设置自动登录标志 标志位
        else:
            self.set_autologin_notchecked_img()
            self.__button_auto_login_clicked = False     # 设置自动登录标志 标志位

        if conf.isRememberUserInfo():  # 如果配置文件，是记住用户信息（用户名/密码）
            userName, passWd = conf.getUserLoginInfo()  # 读取 配置文件用户名 密码
            if userName == "" or passWd == "":
                self.set_rembername_notchecked_img()  #
                self.set_autologin_notchecked_img()  #
                conf.setRememberUserInfoFlag(False)
                conf.setAutoLoginFlag(False)
                self.__button_rememeber_password_clicked = False     # 复位 记住密码标志
                self.__button_auto_login_clicked = False             # 复位  自动登陆标志
            else:  # 记住密码
                self.set_rembername_checked_img()
                self.__button_rememeber_password_clicked = True     # 置 位 记住密码标志

                self.lineEditUserName.setText(userName)
                self.lineEditPassword.setText(Des.Decrypt(passWd))
        else:
            self.set_rembername_notchecked_img()  # 清空配置显示
            self.__button_rememeber_password_clicked = False     # 置 位 记住密码标志
            self.lineEditUserName.setText("")
            self.lineEditPassword.setText("")

        del conf

        #按钮提示
        self.btn_setting.installEventFilter(self)
        #--------------------------------------------------
    #按钮提示
    def eventFilter(self, obj, event):
        eve=QEvent.HoverEnter
        if event.type() == eve:
            objName=str(obj.objectName())
            if (objName == 'btn_setting'):
                QtGui.QToolTip.showText(QtGui.QCursor().pos(),u'设置')
        return QtGui.QWidget.eventFilter(self,obj,event)

    def __checkDefaultCenter(self):
        conf = UserInfoConfFile()
        default = conf.getDefaultCenter()
        if default == "请选择平台":
            LogRecord.instance().logger.info("没有默认平台，启动设置平台及网络窗口！")
            self.foreSetting.showFullScreen()
        else:
            centerName = CenterName(default)
            validate = centerName.getCenterName()
            if not validate[0]:
                LogRecord.instance().logger.info("默认平台无效，启动设置平台及网络窗口！")
                self.foreSetting.showFullScreen()

    # 设置登录中文字显示  绿色
    def label_info_setText(self, v):
        __temp_value = "<html><head/><body><p align=\"center\"><span style=\" color:#ff0000;\">" + v + "</p></body></html>"
        self.label_info.setText(_translate("Form", __temp_value, None))

    # 设置 登录失败文字提示 信息显示 红色
    def label_login_info_setText(self, v):
        __temp_value = "<html><head/><body><p align=\"center\"><span style=\" color:#00ff00;\">" + v + "</p></body></html>"
        self.label_info.setText(_translate("Form", __temp_value, None))
        # self.label_info.setText(_translate("<html><head/><body><p align=\"center\"><span style=\" color:#ff0000;\">"++"</span></p></body></html>", None))

    @pyqtSlot()
    def clientLogout(self):
        try:
            res = None
            if WinVirturlList.userloged == True:
                res = self.__winVirturlList.logout()
                if res[0] == True:
                    self.emit(SIGNAL("LOGOUT_OVER"), True)
                else:
                    self.emit(SIGNAL("LOGOUT_OVER"), False)
            else:
                self.emit(SIGNAL("LOGOUT_OVER"), True)

            LogRecord.instance().logger.debug("关机或重启触发注销！")

        except Exception as e:
            LogRecord.instance().logger.exception("clientLogout Err！")
            self.emit(SIGNAL("LOGOUT_OVER"), False)
            # LogRecord.instance().logger.debug("clientLogout Err！")

    def __band_signal_slot(self):
        # self.connect(self.pushButtonclose, SIGNAL("clicked()"), self.close)       # 关闭登录窗口
        self.connect(self.pushButtonLogin, SIGNAL("clicked()"), self.__on_login)  # 登录按钮
        self.connect(self.pushButtonrem, SIGNAL("clicked()"), self.clicked_remember_password_style)  # 记住密码
        self.connect(self.pushButtonauto, SIGNAL("clicked()"), self.clicked_auto_login_style)  # 自动登录
        self.connect(self.btn_setting, SIGNAL("clicked()"), self.__setting_show)  # 显示设置窗口
        self.connect(self, SIGNAL("printLoginlog"), self.printLog)
        self.connect(self,SIGNAL('updateDefaultCenter'),self.__choose_default_center)


    def __powerOffShow(self):
        """
        显示关机界面
        :return:
        """

        self.powerDialog.update_geometry()
        from common import common_run
        self.powerDialog.move((common_run.getScreenWidth() - self.powerDialog.width())/2,  (common_run.getScreenHeight() - self.powerDialog.height())/2)
        self.powerDialog.show()

        try:
            import virtkey
            v = virtkey.virtkey()
            v.press_keysym(65507)#ctrl-l
            v.press_keysym(65513)#Alt_L
            v.release_keysym(65513)
            v.release_keysym(65507)
        except Exception,err:
            LogRecord.instance().logger.exception('ctrl+alt')


    def powerPressed(self):
        """
        发送关机信号
        :return:
        """
        self.emit(SIGNAL('shutDownSignal'))
        # self.emit(SIGNAL('hideRDPSignal'))

    #  设置 自动 登陆
    def __set__auto_login(self,status):

        conf = UserInfoConfFile()                       # 实例化 UserInfoConfFile
        if status == True:
            self.set_autologin_checked_img()            # 设置自动登录 选中状态
            conf.setAutoLoginFlag(True)
        else:
            self.set_autologin_notchecked_img()
            conf.setAutoLoginFlag(False)
        del conf

    # 设置 记住密码
    def __rememeber_password(self,status):

        conf = UserInfoConfFile()                               # 实例化 UserInfoConfFile
        if status == True:
            self.set_rembername_checked_img()                   # 记住密码 状态
            conf.setRememberUserInfoFlag(True)                  # 写配置文件记住密码
        else:
            self.set_rembername_notchecked_img()                # 不记住 记住密码 状态
            self.__button_rememeber_password_clicked = False
            conf.setRememberUserInfoFlag(False)

        del conf

    # 鼠标 点击 记住/取消 密码
    def clicked_remember_password_style(self):  # 选择 记住用户名和密码
        # 设置 记住用户名密码 状态位
        if self.__button_rememeber_password_clicked == False:   # 如果记住用户名密码状态 为 False
            self.__rememeber_password(True)                     # 记住密码
            self.__button_rememeber_password_clicked = True     # 置 位 记住密码标志

        else:
            self.__rememeber_password(False)      # 取消记住密码
            self.__set__auto_login(False)              # 取消自动登录
            self.__button_auto_login_clicked = False

    # 鼠标 点击 记住/取消 自动登陆
    def clicked_auto_login_style(self):
        if self.__button_auto_login_clicked == False:
            self.__set__auto_login(True)                     # 设置自动登录
            self.__rememeber_password(True)             # 设置记住用户名密码
            self.__button_rememeber_password_clicked = True     # 置 位 记住密码标志
            self.__button_auto_login_clicked = True     # 设置自动登录标志 标志位

        else:
            self.__set__auto_login(False)
            self.__button_auto_login_clicked = False
    #-----------------------------------------------------------------------------

    # 检查版本升级
    def __checkupgrade(self):

        ip_port = self.currentCent_ip_port         #  获取 平台 ip

        if ip_port == "请选择平台" or ip_port == "" or ip_port == None:
            LogRecord.instance().logger.info("-------check upgrade , ip_port == Null-------")
            return False, ""
        else:
            try:
                # 检查版本 是否升级
                LogRecord.instance().logger.info("-------check upgrade---------")
                versionUpgradeInfo = {
                    "centerIp": str(ip_port),
                    "curVersion": str(self.curVersion)
                }

                from winCheckUpgrade import WinCheckUpgrade
                winCheckUpgrade = WinCheckUpgrade(versionUpgradeInfo)
                status = winCheckUpgrade.checkUpgradeFunc()  # 如果 检查 升级 失败

                if status == False: # 如果 不需要 升级
                    LogRecord.instance().logger.info("-------check upgrade False---------")
                    return True,"不需要升级"  # 检查升级 失败 ,跳过升级程序

                # self.__waitingdlg.hide()
                # self.__waitingdlg.movie.stop()

                result = winCheckUpgrade.exec_()
                if result == QDialog.Accepted:
                    LogRecord.instance().logger.info("------- upgrade---------")
                    return False,""
                elif result == QDialog.Rejected:
                    rejectInfo = winCheckUpgrade.getRejectInfo()
                    if rejectInfo == 'cancel':
                        LogRecord.instance().logger.info("-------cancle upgrade---------")
                        return True,""  #  取消 升级,跳过升级程序
                    elif rejectInfo == 'downloadfailed':
                        LogRecord.instance().logger.info("-------download failed---------")
                        return False,rejectInfo  #  取消 升级,跳过升级程序
                    elif rejectInfo == 'downloading':
                        LogRecord.instance().logger.info("-------download running---------")
                        return False,rejectInfo  #  取消 升级,跳过升级程序
                    else:
                        LogRecord.instance().logger.info("-------download error---------")
                        return False,rejectInfo  #  取消 升级,跳过升级程序

            except Exception as e:
                info = "upgrade Err : " + str(e.message)
                LogRecord.instance().logger.error(info)
                return False,""

    # ------------------------------------------------------------
    #  功能 ： 获取用户输入 用户名/密码/平台IP
    #  返回 ： userInpuInfo  ["username“，”password“，”center ip“]
    #  异常 ： Exception  提示 username  password input
    def __getInputInfo(self):

        userName = str(self.lineEditUserName.text())  # 读取 用户名 输入
        passwd = str(self.lineEditPassword.text())    # 读取 密码输入

        # indext = self.comboBoxCenter.currentIndex()
        # 获取平台
        # center_ip_port = str(self.comboBoxCenter.itemData(indext).toString())
        center_ip_port = self.currentCent_ip_port         #  获取 平台 ip

        LogRecord.instance().logger.info("user login input ,userName = [%s]" % userName)  # 日志
        LogRecord.instance().logger.info("user login input ,passWorld = [%s]" % passwd)  # 日志
        LogRecord.instance().logger.info("user login input ,center_ip_port = [%s]" % center_ip_port)  # 日志

        userInpuInfo = ["", "", ""]

        if userName == "" or passwd == "":
            LogRecord.instance().logger.error("user login input ,userName or passwd is Null")  # 日志
            # InfoDialog.instance().Information(u'登录提示',u'用户名和密码,不能为空')# 登陆 提示
            return  False,"用户名和密码,不能为空"
            # raise Exception(str(' 用户名和密码,不能为空 '))

        if  center_ip_port == "请选择平台" or center_ip_port == None or center_ip_port == "":
            LogRecord.instance().logger.error("user login input ,center_ip_port  is Null")  # 日志
            # InfoDialog.instance().Information(u'登录提示',u'请选择平台')# 登陆 提示
            return  False, "请选择平台"

        userInpuInfo[0] = userName
        passwdDes = Des.Encrypt(passwd)  # 加密
        userInpuInfo[1] = passwdDes
        userInpuInfo[2] = center_ip_port
        #
        return True,userInpuInfo

    # ===================================================================
    #   点 击 登 录 按 钮
    def __on_login(self):
        try:
            #  1. 读取 用户 输入
            res = self.__getInputInfo()
            if res[0] == False:

                def __resetlabel_info():
                    self.label_info_setText("")

                from threading import Timer
                t = Timer(2.0, __resetlabel_info)
                t.start()
                self.label_info_setText(str(res[1]))

                return None
            else:
                # LogRecord.instance().logger.debug("get input info ok:" + str(res[1]))  # 日志
                userInputInfo = res[1]
                self.__login(userInputInfo)

        except Exception as e :
            LogRecord.instance().logger.error(str(e.message))  # 日志
        finally:
            pass

    def __updateCenterName(self):
        """
        更新平台名
        :return:
        """
        try:
            conf = UserInfoConfFile()
            centerList = conf.getCenterList()
            for centerInfo in centerList:
                center_ip = centerInfo["centerIp"]
                validate,info = CenterName(center_ip).getCenterName()
                if validate:
                   conf.deleteCenter(center_ip)
                   conf.addCenter(center_ip,info.encode('utf-8'))
                if centerInfo["centerIp"] == self.currentCent_ip_port:
                    conf.setDefaultCenter(self.currentCent_ip_port)
                    self.emit(SIGNAL('updateDefaultCenter'))

        except Exception,err:
            LogRecord.instance().logger.exception('获取服务平台名称异常！')


    @pyqtSlot()
    def __login(self,userInputInfo):

        try:
            #  失能 登陆 按钮
            self.pushButtonLogin.setEnabled(False)

            #  更新服务平台
            updateCenterThread=Thread(target=self.__updateCenterName)
            updateCenterThread.setDaemon(True)
            updateCenterThread.start()

            #  检查 更新
            res = self.__checkupgrade()
            if res[0]  == True: # 升级取消
                LogRecord.instance().logger.debug("client upgrade cancle!")  # 日志
            else:
                self.pushButtonLogin.setEnabled(True)
                def __resetlabel_info():
                    self.label_info_setText("")

                from threading import Timer
                t = Timer(4.0, __resetlabel_info)
                t.start()

                if res[1] == 'downloading':
                    self.label_info_setText("正在下载升级包！")
                elif res[1] == 'downloadfailed':
                    self.label_info_setText("下载升级包失败！")
                elif res[1] == "":
                    self.label_info_setText("")
                    return None
                else:
                    self.label_info_setText("升级异常！")

                return None

            #  登陆 等待 窗口  显示
            self.__waitingdlg.showFullScreen()
            self.__waitingdlg.showMsg("登录中...")
            #  登陆 等待 窗口  显示


            LogRecord.instance().logger.info("press login button...")  # 日志
            mcosWidget = self.__sendLoginRequest(userInputInfo,True)

            LogRecord.instance().logger.info("send Login Request seccess ")  # 日志

            # 配置文件，设置 临时,记住用户名，和密码
            userInfo = {
                "userName": userInputInfo[0],
                "userPassword": userInputInfo[1]
            }
            conf = UserInfoConfFile()
            conf.setUserLoginInfoTmp(userInfo["userName"], userInfo["userPassword"])

            # 判断 是否是 记住 用户名/密码
            if conf.isRememberUserInfo():
                # 写配置文件，设置，记住用户名密码
                conf.setUserLoginInfo(userInfo["userName"], userInfo["userPassword"])
            else:
                # 写配置文件 清空用户名密码
                conf.setUserLoginInfo("", "")

            if mcosWidget != None:
                #add by pbc for usb 透传使用方法 -top

                #add by pbc for usb 透传使用方法 -end

                self.connect(self, SIGNAL('showRDPSignal'), mcosWidget, SIGNAL('showRDPSignal'))
                self.connect(self, SIGNAL('hideRDPSignal'), mcosWidget, SIGNAL('hideRDPSignal'))

                # self.init_act_size()
                # self.setstylesheet_2()
                # self.show_full_screen()
                mcosWidget.showFullScreen()


                if conf.isRememberUserInfo() == False:  # 如果配置文件，是记住用户信息（用户名/密码）
                    # 登录成功后,清空用户名/密码 显示
                    self.lineEditUserName.setText("")
                    self.lineEditPassword.setText("")

            self.label_info_setText("")
            self.__waitingdlg.hide()

            self.pushButtonLogin.setEnabled(True)

        except Exception as e:  # 处理登录异常

            LogRecord.instance().logger.error("登陆异常:" + str(e.message))  # 记录 异常 日志

            def __resetlabel_info():
                self.label_info_setText("")
                self.pushButtonLogin.setEnabled(True)

            from threading import Timer
            t = Timer(4.0, __resetlabel_info)
            t.start()
            self.label_info_setText(str(e.message))
            self.__waitingdlg.hide()
            # t.join() #  等待 刷新状态 定时器 结束,防止 连续点击 状态刷新
            # InfoDialog.instance().Information(u'登录提示',str(e.message))# 登陆 提示
        finally:
            # self.pushButtonLogin.setEnabled(True)
            LogRecord.instance().logger.info("登录按钮点击，fianlly")
            # self.__waitingdlg.hide()
            self.__waitingdlg.movie.stop()

    def update_login_ui(self):
        #  更新服务平台
        updateCenterThread=Thread(target=self.__updateCenterName)
        updateCenterThread.setDaemon(True)
        updateCenterThread.start()

        self.init_act_size()
        self.setstylesheet_2()
        self.show_full_screen()

    def update_screen_show(self):
        self.update_login_ui()

        # if SettingDlg.isApply:
        #     _SettingDlg = SettingDlg(None, "winlogin")
        #     self.connect(_SettingDlg,SIGNAL("screen_change"),self.update_screen_show)
        #     _SettingDlg.stackedWidget.setCurrentIndex(2)
        #     _SettingDlg.exec_()

    ####################################
    #  鼠 标 点 击 设 置 按 钮
    ####################################
    @pyqtSlot()
    def __setting_show(self):

        _SettingDlg = SettingDlg(None, "winlogin")
        _SettingDlg.update_current_button_style()
        # add by pbc for screenR -top
        self.connect(_SettingDlg,SIGNAL("screen_change"),self.update_screen_show)
        # add by pbc for screenR -end
        _SettingDlg.exec_()

        # self.comboBoxCenter.clear()  # 清空

        self.__choose_default_center()  # 更新 平台名称列表

    #======================================
    # 继承自 父对象 重新实现, 选择平台时 调用
    #====================================
    def setcentName(self,name,index):
        super(WinLoginDlg,self).setcentName(name,index)
        print "子对象打印: " , type(name), name,index
        self.defaultIndex = index

        # print self.centerNameList
        ind = 0
        for centerInfo in self.centerInfoList:
            if centerInfo["centerName"] == str(name):
                if ind != index:
                    ind += 1
                    continue
                print "当前平台 ：%s  : %s %d" % (centerInfo["centerName"],centerInfo["centerIp"],index)
                self.currentCent_ip_port = str(centerInfo["centerIp"])

                #设置默认平台保存
                conf = UserInfoConfFile()
                conf.setDefaultCenter(self.currentCent_ip_port)
            ind += 1

    def getCenterName(self,ip_port):
        for centerInfo in self.centerInfoList:
            if centerInfo["centerIp"] == str(ip_port):
                print "当前平台 ：%s  : %s " % (centerInfo["centerName"],centerInfo["centerIp"])
                return centerInfo["centerName"]

        return None
    #=================================================

    # 更新平台名称列表，并 选择默认平台
    def __choose_default_center(self):

        # self.comboBoxCenter.clear()      # 清空
        conf = UserInfoConfFile()        # 实例化 UserInfoConfFile
        centList = conf.getCenterList()  # 获取当前平台配置

        # print centList, "++++++++++++++++++++++++++++++++++++++++"

        #-----------------------
        self.centerInfoList = []         # 清空
        self.centerInfoList = centList
        #--------------------------------
        self.centerNameList = []
        for centerInfo in centList:
            self.centerNameList.append(centerInfo["centerName"])
        #--------------------------------
        # print centList


        if len(centList) > 0:
            for i in range(len(centList)):  # 添加到 comboBoxCenter
                pass
                # self.comboBoxCenter.addItem(centList[i]["centerName"], centList[i]["centerIp"])

            str_center = conf.getDefaultCenter()  # 获取当前默认 平台

            if str_center == "请选择平台":
                # self.comboBoxCenter.addItem("请选择平台", "请选择平台")
                self.lineEdit_domain.setText("请选择平台")
                self.currentCent_ip_port = None
            else:
                self.currentCent_ip_port = str(str_center)
                index = 0
                for centerInfo in centList:
                    if centerInfo["centerIp"] == self.currentCent_ip_port:
                        LogRecord.instance().logger.debug("self.defaultIndex %d\n"%index+
                                                          "self.currentCent_ip_port %s\n"%self.currentCent_ip_port)
                        self.defaultIndex = index
                    index += 1
                name = self.getCenterName(str_center)
                if name == None:
                    self.lineEdit_domain.setText("请选择平台")
                else:
                    self.lineEdit_domain.setText(name)

            # p_int = self.comboBoxCenter.findData(str_center)  # 获取当前匹配默认平台 index
            # if p_int == -1:
            #     pass
            # else:
            #     pass
                # self.comboBoxCenter.setCurrentIndex(p_int)
        else:
            # self.comboBoxCenter.addItem("请选择平台", "请选择平台")
            self.lineEdit_domain.setText("请选择平台")
            self.currentCent_ip_port = None

    def printLog(self, log):
        ''' [ INFO ]'''
        print "[ INFO ]", " : ", log

    # -------------------------------------------------------------------------
    #  功能 ： 请求登录
    #  参数 ： userInputInfo  userInpuInfo  ["username“，”password“，”center ip“]
    #  返回 ： 展示示窗口
    #  异常 ： Exception
    # --------------------------------------------------------------------------

    # def for_screen_changed(self):
    #     pass
        # try:
        #     from common import common_run
        #     self.__winVirturlList.close()
        #     del self.__winVirturlList
        #     self.__winVirturlList = WinVirturlList(common_run.s_userInfo, common_run.s_CenterIP, common_run.s_vmInfoList, common_run.s_agentInfo, common_run.s_appInfoList)
        #     self.connect(self.__winVirturlList,SIGNAL("winVirturlListClosed"),self.update_login_ui)
        #     self.connect(self.__winVirturlList,SIGNAL("for_screen_changed"),self.for_screen_changed)
        #     self.__winVirturlList.showFullScreen()
        # except:
        #     print "error for init screen change uiwindown"

    def __sendLoginRequest(self, userInputInfo, autoLogin=False):
        ''' send login Resquest'''
        userInfo = {
            "userName": userInputInfo[0],
            "userPassword": userInputInfo[1],
        }

        userName = userInputInfo[0]
        userPassword = userInputInfo[1]
        CenterIP = userInputInfo[2]

        print "userName     : ", userName
        print "userPassword : ", userPassword
        print "CenterIp     : ", CenterIP

        # 登录验证
        try:
            vmInfoList, agentInfo, appInfoList = OperatorVMCmd.loginCenterCmd(userName, userPassword, CenterIP)
        except Exception as e:
            print e.message
            raise e

        # 初始化　桌面　资源　展示　窗口
        self.__winVirturlList = WinVirturlList(userInfo, CenterIP, vmInfoList, agentInfo, appInfoList)  # 实例化
        self.connect(self.__winVirturlList,SIGNAL("winVirturlListClosed"),self.update_login_ui)
        # self.connect(self.__winVirturlList,SIGNAL("for_screen_changed"),self.for_screen_changed)

        if autoLogin == False:
            return self.__winVirturlList
        else:
            conf = UserInfoConfFile()
            defaultVmId = conf.getDefaultVM()
            if defaultVmId != None or defaultVmId != "":
                LogRecord.instance().logger.info("send singnal enter vm : " + str(defaultVmId) )
                self.__winVirturlList.enterDefaultVm(defaultVmId) # 调用 发送 进入  默认虚拟机信号
            return self.__winVirturlList

            # vmInfo = self.__getDefaultVmInfo(vmInfoList) # 获取默认 虚拟机 信息
            #
            # #print "自动登录---- 进入虚拟机",vmInfo
            # if vmInfo == None:
            #     return self.__winVirturlList
            # else:
            #     self.__autoLogin(vmInfo, userInfo, CenterIP)# 进入 默认 桌面
            #     return self.__winVirturlList

    # # 获取 默认 虚拟机 信息
    # def __getDefaultVmInfo(self, vmInfoList):
    #     conf = UserInfoConfFile()
    #     defaultVmId = conf.getDefaultVM()
    #     for i in range(len(vmInfoList)):
    #         if vmInfoList[i]["vmId"] == defaultVmId:
    #             return vmInfoList[i]
    #     return None
    # 进入 虚拟机
    # def __autoLogin(self, userInfo, vmInfo, ip_port):
    #     from sendCmd.validate.virtMachine import VirtMachine
    #     print "自动登录：--------------- "
    #     print userInfo, vmInfo, ip_port
    #     vm = VirtMachine(userInfo, vmInfo, ip_port)
    #     print "自动登录---- 进入虚拟机"
    #     print vm.enterVM()  # 进入虚拟机

    def __readConfigInfo(self):  #
        conf = UserInfoConfFile()
        center_ip_port = conf.getDefaultCenter()
        userName, passwd = conf.getUserLoginInfo()

        if userName == "" :
            LogRecord.instance().logger.error("auto login ,read configInfo,userName is null")  # 日志
            return None
        elif passwd == "" :
            LogRecord.instance().logger.error("auto login ,read configInfo,passwd is null")  # 日志
            return None
        elif center_ip_port == "请选择平台" or center_ip_port == None or center_ip_port == "":
            LogRecord.instance().logger.error("auto login ,read configInfo,centerIp is null")  # 日志
            return None

        if userName == "" or passwd == "" or center_ip_port == "请选择平台" or \
                        center_ip_port == None or center_ip_port == "":

            return None
        userInputInfo = [userName, passwd, center_ip_port]
        return userInputInfo

    def auto_login(self):  # 自动登录
        try:

            LogRecord.instance().logger.info("auto login ....")

            # self.pushButtonLogin.setEnabled(False)
            # 从配置文件 获取用户名, 密码，平台  输入
            userInputInfo = self.__readConfigInfo()

            if userInputInfo == None:
                # 日志
                LogRecord.instance().logger.error("auto login ,read configInfo is null")  # 日志
                return None
            #
            # mcosWidget = self.__sendLoginRequest(userInputInfo, True)
            # if mcosWidget != None:
            #     mcosWidget.showFullScreen()
            self.__login(userInputInfo)

                # 自动进入虚拟机
        except Exception as e:  # 处理登录异常
            print e.message
            # MessageDialog(str(e.message)).exec_()
        finally:
            # self.pushButtonLogin.setEnabled(True)
            pass

    # 快捷键 ctrl+ shelf + d  显示 调试窗口
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Enter or e.key() == Qt.Key_Return:
            #添加回车键默认登陆功能 add by pbc
            self.__on_login()

        if (e.modifiers() == Qt.ShiftModifier | Qt.ControlModifier) and (e.key() == Qt.Key_D):
            WinDebug().exec_()


###########################################
##      测   试   用   例
###########################################
if __name__ == "__main__":

    import os
    import sys

    # _dirs = os.path.abspath(__file__)   # 当前文件路径
    # _dirs = os.path.dirname(_dirs)      # 当前文件目录
    # _dirs = os.path.dirname(_dirs)      # 上级文件路径
    # sys.path.append(_dirs)  #

    from Queue import Queue, Empty  # 消息队列

    reload(sys)
    from PyQt4 import QtGui
    from PyQt4.QtCore import QTextCodec

    # sys.setdefaultencoding('utf-8')

    QTextCodec.setCodecForCStrings(QTextCodec.codecForLocale())  # 支持中文

    app = QtGui.QApplication([])

    from os import environ  # 环境变量

    environ["WIN_UI_IMAGES_PATH"] = "../../images"  # 图片路径
    environ["MCOS_APP_ICON_PATH"] = "../../images/appIcon"  # 图片路径
    environ["MCOS_DESKTOP_RDP_DEBUG"] = "DESKTOP_RDP_DEBUG_ON"
    environ["MCOS_CONFIG_FILE"] = "./userInfoConfFile/centerset.conf"  # 配置文件路径

    request_queue = Queue(1)
    respond_queue = Queue(1)
    logout_queue = Queue(1)

    logindlg = None
    try:
        logindlg = WinLoginDlg(request_queue, respond_queue)
    except Exception:
        print "xxx"
    logindlg.showFullScreen()
    app.exec_()
