#coding:utf-8
from PyQt4 import QtCore
from PyQt4 import QtGui
import time
import os
from logger.logrecord import LogRecord

from userInfoConfFile.userInfoConf import UserInfoConfFile
from des import Des



class LockScreen(QtGui.QDialog):
    """
    锁屏界面
    """
    week2chinese={0:'周一'.decode('utf-8'),
                  1:'周二'.decode('utf-8'),
                  2:'周三'.decode('utf-8'),
                  3:'周四'.decode('utf-8'),
                  4:'周五'.decode('utf-8'),
                  5:'周六'.decode('utf-8'),
                  6:'周日'.decode('utf-8'),
                  }
    def __init__(self,parent=None):
        QtGui.QDialog.__init__(self,parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setModal(True)
        self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowStaysOnTopHint)

        self.showRDPSignal=QtCore.pyqtSignal()

        self.__imagePath=os.getenv('WIN_UI_IMAGES_PATH')
        self.timer=QtCore.QTimer(self)
        self.hintTimer=QtCore.QTimer(self)

        self.refresh()

        self.connect(self.loginButton,QtCore.SIGNAL('clicked()'),self,QtCore.SLOT('verification()'))
        self.connect(self.timer,QtCore.SIGNAL('timeout()'),self,QtCore.SLOT('timerTimeOut()'))
        self.connect(self.hintTimer,QtCore.SIGNAL('timeout()'),self,QtCore.SLOT('hintTimeOut()'))

    def refresh(self):
        self.userName=''
        self.password=''
        try:
            self.conf=UserInfoConfFile()
            self.userName,self.password=self.conf.getUserLoginInfoTmp()
            if (self.userName == None) or (self.userName == ''):
                LogRecord.instance().logger.info("用户未登录!")
            elif (self.password == None) or (self.password == ''):
                LogRecord.instance().logger.warn("没有有效的密码!")
        except Exception,err:
            LogRecord.instance().logger.exception("锁屏界面获取用户名和密码异常！")
        self.setStyleSheet("QDialog{background-color:rgb(9,26,35);}")
        #设置控件尺寸
        self.desktop=QtGui.QApplication.desktop()
        self.__height=self.desktop.height()
        self.__width=self.desktop.width()
        self.__rightBlank=self.__width//7
        self.__leftBlank=self.__width//7
        self.__loginHeight=self.__height//15
        self.__loginWidth=self.__loginHeight
        self.__inputWidth=self.__width//2-self.__width//20-self.__loginWidth*3//2-self.__rightBlank
        self.__inputHeight=self.__loginHeight
        self.__userNameWidth=self.__inputWidth
        self.__userNameHeight=self.__inputHeight
        self.__timeWidth=self.__width//4
        self.__timeHeight=self.__height//5
        self.__dayWidth=self.__timeWidth
        self.__dayHeight=self.__timeHeight//4
        #设置登录密码验证按钮样式
        self.loginButton=QtGui.QPushButton(self)
        # self.loginButton.setText('登录'.decode('utf-8'))
        self.loginButton.setFlat(True)
        self.loginButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.loginButton.setGeometry(self.__width-self.__rightBlank-self.__loginWidth,
                                     (self.__height-self.__loginHeight)//2,
                                     self.__loginWidth,
                                     self.__loginHeight)
        self.loginButton.setStyleSheet("QPushButton{border-image:url(%s/settingWindow/login1.png);background:transparent;}"%self.__imagePath+
                                                    "QPushButton:hover{border-image:url(%s/settingWindow/login2.png);background:transparent;}"%self.__imagePath+
                                                   "QPushButton:pressed{border-image:url(%s/settingWindow/login3.png);background:transparent;}"%self.__imagePath)
        self.loginButton.installEventFilter(self)

        self.inputLabel=QtGui.QLabel(self)
        self.inputLabel.setGeometry(self.__width//2+self.__width//20,
                                     (self.__height-self.__loginHeight)//2,
                                     self.__inputWidth,
                                     self.__inputHeight)
        self.inputLabel.setObjectName('inputLabel')
        self.inputLabel.setStyleSheet("#inputLabel{background:transparent;}")
        self.inputEdit=QtGui.QLineEdit(self.inputLabel)
        self.inputEdit.setGeometry(2,2,self.__inputWidth-4,self.__inputHeight-4)
        self.inputEdit.setPlaceholderText('请输入密码'.decode('utf-8'))
        self.inputEdit.setObjectName('inputEdit')
        self.inputEdit.setStyleSheet("#inputEdit{border-image:url(%s/settingWindow/passwd.png);background:transparent;}"%self.__imagePath)
        inputFont=QtGui.QFont()
        # inputFont.setPixelSize(18)
        inputFont.setPointSize(self.resizeFont(18))
        self.inputEdit.setFont(inputFont)
        self.inputEdit.setEchoMode(QtGui.QLineEdit.Password)
        #设置登录用户名Label
        self.userNameLabel=QtGui.QLabel(self)
        self.userNameLabel.setGeometry(self.__width//2+self.__width//20,
                                     (self.__height-self.__loginHeight)//2-self.__userNameHeight,
                                     self.__userNameWidth,
                                     self.__userNameHeight)
        if (self.userName != '') and (self.userName != None):
            self.userNameLabel.setText(self.userName)
            self.inputEdit.setEnabled(True)
        else:
            self.userNameLabel.setText('尚未登录'.decode('utf-8'))
            self.inputEdit.setEnabled(False)
        self.userNameLabel.setFont(inputFont)
        self.userNameLabel.setStyleSheet('QLabel{color:rgb(255,255,255);}')
        #提示信息Label
        self.hintLabel=QtGui.QLabel(self)
        self.hintLabel.setGeometry(self.__width//2+self.__width//20,
                                     (self.__height+self.__loginHeight)//2,
                                     self.__userNameWidth,
                                     self.__userNameHeight)
        self.hintLabel.setFont(inputFont)
        self.hintLabel.setStyleSheet('QLabel{color:rgb(255,0,0);}')
        # self.hintLabel.setText('请输入密码！'.decode('utf-8'))
        #当前时间显示
        self.timeLabel=QtGui.QLabel(self)
        self.timeLabel.setGeometry(self.__leftBlank,
                                   (self.__height//2-self.__timeHeight),
                                   self.__timeWidth,
                                   self.__timeHeight)
        timeFont=QtGui.QFont()
        timeFont.setPointSize(self.resizeFont(100))
        # timeFont.setBold(True)
        self.timeLabel.setFont(timeFont)
        self.timeLabel.setText('%02d:%02d'%(time.localtime().tm_hour,time.localtime().tm_min))
        self.timeLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.timeLabel.setStyleSheet('QLabel{color:rgb(255,255,255);}')
        #当前日期
        self.dayLabel=QtGui.QLabel(self)
        self.dayLabel.setGeometry(self.__leftBlank,
                                  self.__height//2,
                                  self.__dayWidth,
                                  self.__dayHeight)
        dayFont=QtGui.QFont()
        dayFont.setPointSize(self.resizeFont(25))
        # dayFont.setBold(True)
        self.dayLabel.setFont(dayFont)
        self.dayLabel.setText('%04d-%02d-%02d    %s'%(time.localtime().tm_year,time.localtime().tm_mon,time.localtime().tm_mday,LockScreen.week2chinese[time.localtime().tm_wday]))
        self.dayLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.dayLabel.setStyleSheet('QLabel{color:rgb(255,255,255);}')

        self.timer.start(1000)

        self.showFullScreen()

    def resizeFont(self,fontSize):
        return fontSize*self.__width/1440

    def eventFilter(self, obj, event):
        eve=QtCore.QEvent.HoverEnter
        if event.type() == eve:
            QtGui.QToolTip.showText(QtGui.QCursor().pos(),'进入'.decode('utf-8'))
        return QtGui.QLabel.eventFilter(self,obj,event)

    def keyPressEvent(self,event):
        if (event.key() == QtCore.Qt.Key_Enter) or (event.key() == QtCore.Qt.Key_Return):
            self.verification()

    @QtCore.pyqtSlot()
    def timerTimeOut(self):
        self.timeLabel.setText('%02d:%02d'%(time.localtime().tm_hour,time.localtime().tm_min))
        self.dayLabel.setText('%04d-%02d-%02d    %s'%(time.localtime().tm_year,time.localtime().tm_mon,time.localtime().tm_mday,LockScreen.week2chinese[time.localtime().tm_wday]))

    @QtCore.pyqtSlot()
    def hintTimeOut(self):
        self.hintLabel.setText(''.decode('utf-8'))
        self.hintTimer.stop()

    @QtCore.pyqtSlot()
    def verification(self):
        if (self.userName == '') or (self.userName == None):
            self.timer.stop()
            self.close()
            return
        inPasswd=self.inputEdit.text()
        if (inPasswd != None) and (inPasswd != ''):
            passwd=Des.Encrypt(str(inPasswd))
            if passwd == self.password:
                self.timer.stop()
                # self.emit(QtCore.SIGNAL('showRDPSignal'))
                self.close()
                return
            else:
                self.inputEdit.setText('')
                self.inputEdit.setFocus()
                self.hintLabel.setText('密码错误！请重新输入密码！'.decode('utf-8'))
                self.hintTimer.start(3000)
        else:
            self.inputEdit.setText('')
            self.hintLabel.setText('请输入密码！'.decode('utf-8'))
            self.hintTimer.start(3000)

if __name__ == "__main__":
    import sys
    os.environ["WIN_UI_IMAGES_PATH"]="../../images"
    app = QtGui.QApplication(sys.argv)
    lockDialog=LockScreen()
    lockDialog.show()
    print time.localtime()
    sys.exit(app.exec_())

