#coding=utf-8
from PyQt4.QtGui import QDialog, QLineEdit, QKeyEvent
from PyQt4.QtCore import Qt, QString, SIGNAL
from view.desktop.loginview import Ui_Form
from common.globalfun import moveWidgetToScreenCenter
from common.infohintdialog import InfoHintDialog
from model.infomodel.userinfo import UserBaseInfo,LoginUserInfo
import threading
from model.request.utilityrequestoperationwrap import UtilityRequestOperationWrap
from common.commondata import EXE_FILEPATH
from controller.setting.setting import Setting
from common import globalfun
from model.cfg.storeinfoparser import StoreInfoParser
from controller.terminaltool.terminalset import TerminalTools
from common.logrecord import LogRecord
import json
 
class LoginDlg(QDialog, Ui_Form):
    def __init__(self, parent=None):
        super(LoginDlg,self).__init__(parent)
        
        #--------------界面初始化-top
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)
        image_login_path=EXE_FILEPATH
        self.setStyleSheet(QString("QWidget#Form{background-image: url(%1/../images/login.png);}").arg(image_login_path))
        self.lineEditPassword.setEchoMode(QLineEdit.Password)
        self.pushButtonLogin.setObjectName("loginBtn")
        self.pushButtonLogin.setFlat(True)
        self.pushButtonHelp.setHidden(True)
        self.pushButtonTermai.setHidden(True)
        self.mousePressed = False
        #--------------界面初始化-end
        
        self.initSubWidgetInfo()
        self.bandSignalSlot()
        self.setMouseTracking(True)

    def initSubWidgetInfo(self):
        self.initCenterList()
        self.initVersionInfo()
        self.initAutoLoginUserInfo()
        
        #登录框移动到屏幕中心
        moveWidgetToScreenCenter(self, checkMulMonitor=False)
        
    def initVersionInfo(self):
        version = globalfun.getVersionAndReleaseDate().trimmed()
        if version:
            self.labelVerName.setText(u"%s" % version)
            
    def setAutoLoginUserInfo(self):
        autoLoginInfo = StoreInfoParser.instance().getAutoLoginInfo()
        if autoLoginInfo is not None:
            self.checkBoxRemberUsername.setChecked(True)
            self.checkBoxAutoLogin.setChecked(True)
            autoLoginInfoDict = json.loads(autoLoginInfo)
            self.lineEditUserName.setText(autoLoginInfoDict["userName"])
            self.lineEditPassword.setText(autoLoginInfoDict["password"])
            centerName = autoLoginInfoDict["centerName"]
            num = self.comboBoxCenter.count()
            for i in range(num):
                subCenterName = self.getCenterComboxText(i)
                if subCenterName == centerName:
                    self.comboBoxCenter.setCurrentIndex(i)
                    break
        return
            
    def checkHasAutoLoginUser(self):
        return True if StoreInfoParser.instance().getAutoLoginInfo() is not None else False
    
    
    def checkRememberUserName(self):
        return True if StoreInfoParser.instance().getLoginUserName() is not None else False
    
    
    def setRemeberUserName(self):
        loginUserInfo = StoreInfoParser.instance().getLoginUserName()
        if loginUserInfo is not None:
            self.lineEditUserName.setText(loginUserInfo)
            self.checkBoxRemberUsername.setChecked(True)
    
    
    def initAutoLoginUserInfo(self):
        if self.checkHasAutoLoginUser():
            self.setAutoLoginUserInfo()
            return
        
        if self.checkRememberUserName():
            self.setRemeberUserName()
            
        return
        
        
    def initCenterList(self):
        self.comboBoxCenter.clear()
        centerContent = StoreInfoParser.instance().getNetworkSwitch()
        if centerContent is None:
            return
         
        preCenterName = StoreInfoParser.instance().getLoginCenterName()
        preIndex = -1
        contentDict = json.loads(centerContent)
        for index, center in enumerate(contentDict.keys()):
            self.comboBoxCenter.addItem(center)
            self.comboBoxCenter.setItemData(index, contentDict[center]["centerIp"], Qt.UserRole)
            self.comboBoxCenter.setItemData(index, contentDict[center]["networkName"], Qt.UserRole + 1)
            if center == preCenterName:
                preIndex = index
                
        if preIndex != -1:
            self.comboBoxCenter.setCurrentIndex(preIndex)
            
    def updateCenterList(self):
        self.comboBoxCenter.clear()
        centerContent = StoreInfoParser.instance().getNetworkSwitch()
        if centerContent is None:
            return
         
        contentDict = json.loads(centerContent)
        for index, center in enumerate(contentDict.keys()):
            self.comboBoxCenter.addItem(center)
            self.comboBoxCenter.setItemData(index, contentDict[center]["centerIp"], Qt.UserRole)
            self.comboBoxCenter.setItemData(index, contentDict[center]["networkName"], Qt.UserRole + 1)
            
        
    def bandSignalSlot(self):
        self.connect(self.pushButtonLogin, SIGNAL("clicked()"),self.slotLogin)
        self.connect(self.pushButtonLoginSet, SIGNAL("clicked()"),self.slotPopSettingDlg)
        self.connect(self.pushButtonTermai, SIGNAL("clicked()"),self.slotPopTerminalToolDlg)
        # self.connect(self.pushButtonHelp, SIGNAL("clicked()"),self.slotPopHelpDlg)
        self.connect(self, SIGNAL("authFailed"),self.slotLoginFailed)
        self.connect(self, SIGNAL("authSuccess"),self.changeLoginBack)
        self.connect(self.pushButtonShowMin,SIGNAL("clicked()"),self.selfShowMin)
        self.connect(self.pushButtonClose,SIGNAL("clicked()"),self.selfClose)

    def selfClose(self):
        self.close()

    def selfShowMin(self):
        self.showMinimized()
        
    def slotLoginFailed(self, checkValue):
        self.changeLoginBack()
        
        if checkValue is None:
            InfoHintDialog(u"登录失败，请查看用户名和密码是否正确！").exec_()
        elif checkValue == "ConnectionError":
            InfoHintDialog(u"登录失败，请查看网络连接是否正常！").exec_()
        
    def slotPopTerminalToolDlg(self):
        toolDlg = TerminalTools()
        toolDlg.exec_()
        
    # def slotPopHelpDlg(self):
    #     helpDlg = HelpDialog()
    #     helpDlg.exec_()
        
    def slotPopSettingDlg(self):
        # passwordDialog = PasswordDialog()
        # if passwordDialog.exec_() == QDialog.Accepted:
        setWidget = Setting()
        self.connect(setWidget, SIGNAL("updateCenterDateS"), self.updateCenterList)
        self.connect(setWidget, SIGNAL("setscreenover"), self.adjustPosition)
        setWidget.exec_()
            
            
    def adjustPosition(self):
        self.emit(SIGNAL("moveWidgetToScreenCenter"))
        
        
    def checkIsRecordLoginUserInfo(self):
        LogRecord.instance().recordLog(u"进入 checkIsRecordLoginUserInfo 函数")
        if self.checkBoxRemberUsername.isChecked():
            StoreInfoParser.instance().setLoginUserName(self.getLoginUserName())
        else:
            StoreInfoParser.instance().deleteLoginUserName()
                
        StoreInfoParser.instance().setLoginCenterName(self.getLoginCenterName())
                
        if self.checkBoxAutoLogin.isChecked():
            autoLoginInfo = { "userName": self.getLoginUserName(),
                              "password": self.getPassword(),
                              "serverIp": self.getLoginCenterIP(),
                              "centerName": self.getLoginCenterName(),
                                    }
            StoreInfoParser.instance().setAutoLoginInfo(json.dumps(autoLoginInfo, ensure_ascii=False))
        else:
            StoreInfoParser.instance().deleteAutoLoginInfo()
            
            
    def slotLogin(self):
        LogRecord.instance().recordLog(u"点击登录按钮")
        if not self.checkLoginInfo():
            LogRecord.instance().recordLog(u"进入checkLoginInfo函数")
            return
        
        self.setLoginUserInfo()
        self.changeLoginDisplay()

        def authHttpRequest():
            LogRecord.instance().recordLog(u"进入 authHttpRequest 函数")
            utility = UtilityRequestOperationWrap()
            vmBaseInfoList = utility.checkloginAuth()
            LogRecord.instance().recordLog(u"得到 vmBaseInfoList 数值")
            LogRecord.instance().recordLog(vmBaseInfoList)
            if vmBaseInfoList == None or vmBaseInfoList == "ConnectionError":
                self.emit(SIGNAL("authFailed"), vmBaseInfoList)
                return
            self.checkIsRecordLoginUserInfo()
            self.emit(SIGNAL("authSuccess"), vmBaseInfoList)
        
        tContext = threading.Thread(target=authHttpRequest)
        tContext.start()
        
        
    def setLoginUserInfo(self):
        LogRecord.instance().recordLog(u"进入setLoginUserInfo函数")
        userBaseInfo = UserBaseInfo()
        userBaseInfo.name, userBaseInfo.password, userBaseInfo.serverIp = self.getLoginInfo()
        LoginUserInfo.instance().setUserInfo(userBaseInfo)
    
    def resetWidgetInfo(self):
        if not self.checkBoxRemberUsername.isChecked():
            self.lineEditUserName.clear()
        self.lineEditPassword.clear()
    
    def checkLoginInfo(self):
        userName, password, centerIP = self.getLoginInfo()

        if not userName or not password:
            InfoHintDialog(u"用户名或密码不能为空！").exec_()
            return False
        
        if not centerIP:
            InfoHintDialog(u"请选择相应的中心！").exec_()
            return False
        
        return True
    
    def getLoginInfo(self):
        userName = self.getLoginUserName()
        password = self.getPassword()
        centerIP = self.getLoginCenterIP()
        return userName, password, centerIP
    
    def getLoginUserName(self):
        return unicode(str(self.lineEditUserName.text().trimmed()), "utf-8")
    
    def getLoginCenterIP(self):
        index = self.comboBoxCenter.currentIndex()
        return str(self.comboBoxCenter.itemData(index, Qt.UserRole).toString()) 
    
    def getLoginCenterName(self):
        return unicode(str(self.comboBoxCenter.currentText().trimmed()), "utf-8")
    
    def getCenterComboxText(self, index):
        return unicode(str(self.comboBoxCenter.itemText(index).trimmed()), "utf-8")
    
    def getPassword(self):
        return str(self.lineEditPassword.text())

    def mouseMoveEvent(self,event):
        if self.mousePressed:
            self.move(self.pos() + event.pos() - self.currentPos)
        self.default = QString()
    def mousePressEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.currentPos = event.pos()
            self.mousePressed = True
    def mouseReleaseEvent(self,event):
        self.mousePressed = False
    
    def keyPressEvent(self, event):
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
            self.slotLogin()
        
    def changeLoginDisplay(self):
        LogRecord.instance().recordLog(u"进入changeLoginDisplay函数")
        self.pushButtonLogin.setEnabled(False)
        self.pushButtonLogin.setText(u"登录中...")
        
   
    def changeLoginBack(self):
        self.pushButtonLogin.setEnabled(True)
        self.pushButtonLogin.setText(u"登  录")
 
