#!/usr/bin/python
# coding=utf8

from PyQt4.QtGui import QWidget, QDesktopWidget
from PyQt4.QtCore import Qt, SIGNAL, pyqtSlot

from sendCmd.operatorVMCmd import OperatorVMCmd
from ui_qss.changePasswordQss import ChangePasswordQss
from des import Des
from messageDialog import MessageDialog
from time import sleep
from common.info_dialog import InfoDialog
from userInfoConfFile.userInfoConf import UserInfoConfFile
from sendCmd.validate.userValidate import UserValidate
from logger.logrecord import LogRecord

class ChangePassword(ChangePasswordQss):
    def __init__(self, userInfo=None, center_ip_port=None, parent=None):
        super(ChangePassword, self).__init__(parent)
        self.__userInfo = userInfo
        self.__center_ip_port = center_ip_port

        self.connect(self.btn_cancel, SIGNAL("clicked()"), self.close)
        self.connect(self.btn_close, SIGNAL("clicked()"), self.close)
        self.connect(self.btn_ok, SIGNAL("clicked()"), self.__changePasswdSlot)
        self.infoChPasswd.setText("")
        self.lineEdit_newPasswd_1.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit_newPasswd_2.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit_oldPasswd.setContextMenuPolicy(Qt.NoContextMenu)

    def __changePasswdSlot(self):
        self.btn_ok.setEnabled(False)
        #-------------------
        def __resetlabel_info():
            self.infoChPasswd.setText("")
        from threading import Timer
        t = Timer(0.7, __resetlabel_info)
        #-------------------------

        try:
            res = self.__changePasswd()
            if res[1] == True: # 需改 密码 成功
                self.close()
            else:
                self.infoChPasswd.setText(res[1])
                # self.infoChPasswd.setAlignment(Qt.AlignVCenter)
                t.start()

        except Exception as e:
            LogRecord.instance().logger.exception("修改密码异常！")
            # print e.message
        finally:
            self.btn_ok.setEnabled(True)

    # @pyqtSlot()
    def __changePasswd(self):

        # 获取用户输入
        oldpasswd = str(self.lineEdit_oldPasswd.text())
        newpasswd1 = str(self.lineEdit_newPasswd_1.text())
        newpasswd2 = str(self.lineEdit_newPasswd_2.text())

        # 输入密码不能为空
        if oldpasswd == "":
            # self.hide()
            # InfoDialog.instance().Information(u'提示', u'旧密码输入不能为空')  # 仅仅 提示信息
            # self.show()
            self.lineEdit_oldPasswd.setFocus()
            return False,'原密码不能为空'

        if newpasswd1 == "":
            self.lineEdit_newPasswd_1.setFocus()
            return False,'新密码不能为空'
        # 输入密码不能为空
        if  newpasswd2 == "":
            # self.hide()
            # InfoDialog.instance().Information(u'提示', u'新密码/确认密码 输入不能为空')  # 仅仅 提示信息
            # self.show()
            self.lineEdit_newPasswd_2.setFocus()
            return False,'确认密码不能为空'

        #
        if (newpasswd1 != newpasswd2):
            # self.hide()
            # InfoDialog.instance().Information(u'提示', u'新密码与确认密码 不相等')  # 仅仅 提示信息
            # self.show()
            self.lineEdit_newPasswd_2.setFocus()
            return False,'新密码与确认密码不一致'

        # 新密码不能等于,旧密码
        if (oldpasswd == newpasswd1):
            # self.hide()
            # InfoDialog.instance().Information(u'提示', u'旧密码和新密码不能相同')  # 仅仅 提示信息
            # self.show()
            return True,'旧密码和新密码相同'

        oldpasswdDes = Des.Encrypt(oldpasswd)  # 加密
        newpasswdDes = Des.Encrypt(newpasswd1)  # 加密

        userPasswd = UserValidate(self.__userInfo, self.__center_ip_port)
        res = userPasswd.getPasswdLevel()  # 获取密码等级
        # print res[1]
        # 密码规则检查

        # 修改密码
        res = userPasswd.changeVMPasswd(oldpasswdDes, newpasswdDes)
        # print res[1]
        flag, result = res

        if flag == True:
            self.hide()
            InfoDialog.instance().Information(u'提示', u"修改密码成功")  # 仅仅 提示信息
            #self.show()
            # 修改配置文件,存储
            userConf = UserInfoConfFile()
            if userConf.isRememberUserInfo() == True:  # 配置了记住 用户名密码
                # 修改用户 密码  保存到　文件
                # userConf.setUserLoginInfo(self.__userInfo["userName"], newpasswdDes)
                pass

            # 设置 临时 用户名密码
            userConf.setUserLoginInfoTmp(self.__userInfo["userName"], newpasswdDes)
            # self.close()
            self.lineEdit_oldPasswd.setText("")
            self.lineEdit_newPasswd_1.setText("")
            self.lineEdit_newPasswd_2.setText("")
            return  True,""
        else:
            # self.hide()
            # InfoDialog.instance().Information(u'提示', result)  # 仅仅 提示信息
            # self.show()

            return False,str(result)

    def show(self):
        """
        显示对话框前清空原有内容
        :return:
        """
        self.infoChPasswd.setText("")
        self.lineEdit_oldPasswd.setText('')
        self.lineEdit_newPasswd_1.setText('')
        self.lineEdit_newPasswd_2.setText('')
        self.lineEdit_oldPasswd.setFocus()
        super(ChangePassword,self).show()

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


# test
if __name__ == "__main__":
    userName = "jxm"
    passWd = "Pass1234"

    passWd = Des.Encrypt(passWd)

    userInfo = {

        "userName": userName,
        "userPassword": passWd,
        "centerIp": "192.168.102.33:8080"
    }

    from PyQt4 import QtGui
    from os import environ

    environ["WIN_UI_IMAGES_PATH"] = "../../images"

    app = QtGui.QApplication([])
    from PyQt4.QtCore import QTextCodec

    QTextCodec.setCodecForCStrings(QTextCodec.codecForLocale())  # 支持中文
    win = ChangePassword(userInfo, "192.168.102.33:8080")
    win.show()
    app.exec_()
