#coding:utf-8
'''
Created on Sep 3, 2014

@author: root
'''
from PyQt4.QtCore import SIGNAL, Qt, QString
from PyQt4.QtGui import QCheckBox, QHeaderView, QAbstractItemView
from PyQt4.QtGui import QComboBox
from PyQt4.QtGui import QGridLayout, QMenu, QTableWidget, QTableWidgetItem, QDialog
from PyQt4.QtGui import QGroupBox
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QPushButton, QAction, QCursor
from PyQt4.QtGui import QWidget, QLabel, QHBoxLayout, QVBoxLayout

from base.infohintdialog import InfoHintDialog
from base.messagebox import MessageBox
from base.storeinfoparser import StoreInfoParser
from hostop import Hostop
from setting.centerapi import CenterApi
from setting.centeredit import CenterEditDialog
from setting.getnetinfo import NetCtl
import setting.globalfunc
from setting.logrecord import LogRecord
from setting.netSwitchThread import NetSwitchTd
from setting.ttyusb import NetSwitch
from setting.waitdlg import WaitingWidget


class CentreSetting(QWidget):
       
    def __init__(self,parent = None):
        super(CentreSetting,self).__init__(parent)
        self.waitDlg = WaitingWidget()
        self.editDlg = CenterEditDialog()
        self.infoHint = InfoHintDialog()
        self.netSwitch = NetSwitch()
        self.hostop = Hostop()
        
        self.cbNetworkAuto = QCheckBox()
        self.cbNetworkAuto.setText(u"启动自动获取平台网络")
        
        self.sslCheckBox = QCheckBox()
        self.sslCheckBox.setText(u"SSL")
        self.sslCheckBox.setChecked(True)
              
        self.twNetwork = QTableWidget()
        self.twNetwork.setFixedHeight(165)
        
        self.addCentreGroup = QGroupBox()
        self.addCentreGroup.setTitle(u"添加平台")
        
        self.nameLabel = QLabel(u"名称")
        self.nameLabel.setFixedWidth(70)
        self.centreLabel = QLabel(u"IP地址")
        self.centreLabel.setFixedWidth(70)
        self.portLabel = QLabel(u"端口")
        self.portLabel.setFixedWidth(70)
        self.netLabel = QLabel(u"网络")
        self.netLabel.setFixedWidth(70)
        
        self.lineEditName = QLineEdit()
        self.lineEditName.setFixedWidth(270)

        self.lineEditCentre = QLineEdit(self)
        self.lineEditCentre.setFixedWidth(270)
        
        self.lineEditPort = QLineEdit()
        self.lineEditPort.setFixedWidth(270)
        
        self.netComboBox = QComboBox()
        self.netComboBox.setFixedWidth(270)
        
        self.deleteButton = QPushButton(u"删除")
        self.deleteButton.setFixedSize(75,27)
        self.deleteButton.setFlat(True)
        self.deleteButton.setObjectName("settingDlgBtn")
        self.editButton = QPushButton(u"编辑")
        self.editButton.setFixedSize(75,27)
        self.editButton.setFlat(True)
        self.editButton.setObjectName("settingDlgBtn")
        self.addButton = QPushButton(u"添加")
        self.addButton.setFixedSize(75,27)
        self.addButton.setFlat(True)
        self.addButton.setObjectName("settingDlgBtn")
        self.closeButton = QPushButton(u"关闭")
        self.closeButton.setFixedSize(75,27)
        self.closeButton.setFlat(True)
        self.closeButton.setObjectName("settingDlgBtn")
        
        self.netSwitchLabel = QLabel(u"网口")
        netSwitchList = ["1", "2", "3", "4"]
        self.netSwitchCombo = QComboBox()
        self.netSwitchCombo.setFixedWidth(270)
        self.netSwitchCombo.addItems(netSwitchList)
        
        self.netSwitchCheck = QCheckBox(u"网络切换器")
        
        groupLayout = QGridLayout()
        groupLayout.addWidget(self.nameLabel,0,0)
        groupLayout.addWidget(self.lineEditName,0,1)
        groupLayout.addWidget(self.centreLabel,1,0)
        groupLayout.addWidget(self.lineEditCentre,1,1)
        groupLayout.addWidget(self.sslCheckBox,1,2)
        groupLayout.addWidget(self.portLabel,2,0)
        groupLayout.addWidget(self.lineEditPort,2,1)
        groupLayout.addWidget(self.netLabel,3,0)
        groupLayout.addWidget(self.netComboBox,3,1)
        groupLayout.addWidget(self.netSwitchLabel,4,0)
        groupLayout.addWidget(self.netSwitchCombo,4,1)
        groupLayout.addWidget(self.netSwitchCheck,4,2,1,2)
        
        addLayout = QHBoxLayout()
        addLayout.addStretch()
        addLayout.addWidget(self.addButton)
        
        mLayout = QHBoxLayout()
        mLayout.addSpacing(30)
        mLayout.addLayout(groupLayout)
        mLayout.addSpacing(30)
        
        gLayout = QVBoxLayout()
        gLayout.addLayout(mLayout)
        gLayout.addSpacing(20)
        gLayout.addLayout(addLayout)
        
        self.addCentreGroup.setLayout(gLayout)
        
        deleteButtonLayout = QHBoxLayout()
        deleteButtonLayout.addStretch()
        deleteButtonLayout.addWidget(self.editButton)
        deleteButtonLayout.addWidget(self.deleteButton)
        
        closeButtonLayout = QHBoxLayout()
        closeButtonLayout.addStretch()
        closeButtonLayout.addWidget(self.closeButton)
        
        miniWidget = QWidget()
        vLayout = QVBoxLayout()
        vLayout.setMargin(0)
        vLayout.addWidget(self.cbNetworkAuto)
        vLayout.addWidget(self.twNetwork)
        vLayout.addLayout(deleteButtonLayout)
        vLayout.addWidget(self.addCentreGroup)
        vLayout.addLayout(closeButtonLayout)
        miniWidget.setLayout(vLayout)
        
        self.mainLayout = QHBoxLayout(self)
        self.mainLayout.addSpacing(30)
        self.mainLayout.addWidget(miniWidget)
        self.mainLayout.addSpacing(30)

        self.centerTableMenu = QMenu(self.twNetwork)
        self.delCenterAction = QAction(u"删 除", self)
        self.editCenterAction = QAction(u"编 辑", self)
        self.connect(self.delCenterAction, SIGNAL("triggered()"), self.on_pushButtonDelete_clicked)
        self.connect(self.editCenterAction, SIGNAL("triggered()"), self.slotEdit)
        
        self.refreshAutoNet()
        
        self.twNetwork.clear()
        self.twNetwork.setColumnCount(7)
        self.twNetwork.hideColumn(3)
        self.twNetwork.hideColumn(4)
        
        self.headList = [u"名称",u"IP地址",u"端口",u"ssl",u"证书名称",u"网络",u"网口"]
        self.twNetwork.setHorizontalHeaderLabels(self.headList)
        self.twNetwork.setAlternatingRowColors(1)
        self.twNetwork.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.twNetwork.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.twNetwork.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.twNetwork.setSelectionMode(QAbstractItemView.SingleSelection)
        self.twNetwork.setContextMenuPolicy(Qt.CustomContextMenu)
        self.twNetwork.customContextMenuRequested.connect(self.on_tableWidgetHost_customContextMenuRequested)
        headerView = self.twNetwork.verticalHeader()
        headerView.setHidden(True)
        self.refreshNetworkTable()
        
        self.netCtl = NetCtl()
        LogRecord.instance().logger.info(u"开始获取本地网络列表，并且将这个列表显示在combo框中，进入getnetinfo的getNetAddressList函数")
        self.netAddressList = self.netCtl.getNetAddressList()
        print (self.netAddressList)
        if self.netAddressList < 0:
            LogRecord.instance().logger.info(u"本地网络为空")
            self.num = 0
        else:
            self.num = len(self.netAddressList)
        self.twIPList = QTableWidget()
        self.twIPList.setRowCount(self.num)
        
        #得到当前的网络信息
        self.refreshComboNet()
        
        #端口默认设置为80
        self.lineEditPort.setText("443")
        self.netSwitchCombo.setEnabled(False)
        
        self.switchThread = NetSwitchTd()
        
        self.connect(self.cbNetworkAuto,SIGNAL("toggled(bool)"),self.on_cbNetworkAuto_clicked)
        self.connect(self.netSwitchCheck, SIGNAL("clicked()"),self.on_netSwitchCheck_clicked)
        self.connect(self.closeButton, SIGNAL("clicked()"),self.closeTabWidget)
        self.connect(self.editButton, SIGNAL("clicked()"),self.slotEdit)
        self.connect(self.editDlg, SIGNAL("editupdatecenter"),self.slotUpdateCenter)
        self.connect(self.deleteButton, SIGNAL("clicked()"),self.on_pushButtonDelete_clicked)
        self.connect(self.addButton, SIGNAL("clicked()"),self.on_pushButtonAdd_clicked)
        self.connect(self.sslCheckBox, SIGNAL("clicked()"),self.on_checkBox_clicked)
        self.connect(self.netComboBox, SIGNAL('activated(int)'),self.on_comboBoxNetName_activated)
        self.connect(self.netSwitchCombo, SIGNAL("activated(int)"),self.slotSwitchNet)
        self.connect(self.switchThread, SIGNAL("networkSwitchSignal"),self.showNetworkSwitchInfo)
        self.connect(self.switchThread, SIGNAL("addNetworkItemSignal"),self.showAddNetworkItemInfo)
        self.connect(self.switchThread, SIGNAL("authCertificateSignal"),self.showAuthCertificateInfo)
        self.connect(self.switchThread, SIGNAL("restartNetworkSignal"),self.showRestartNetworkInfo)
        self.connect(self.netSwitch, SIGNAL("setswitchover"),self.showNetSwitchInfo)
        
    def showNetSwitchInfo(self,result):
        self.waitDlg.close()
        if result == 0:
            InfoHintDialog(u"切换成功").exec_()
        elif result == 1:
            InfoHintDialog(u"切换失败").exec_()
    def slotSwitchNet(self,index):
        #print index
        self.netSwitch.setNetNum(index+1)
        self.netSwitch.start()
        self.waitDlg.setTip(u"切换网口中...")
        self.waitDlg.show()
        self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
        #pass
    def on_netSwitchCheck_clicked(self):
        usbList = self.netSwitch.getUsbList()
        if usbList == []:
            InfoHintDialog(u"没有网络切换设备").exec_()
            self.netSwitchCheck.setChecked(False)
            self.netSwitchCombo.setEnabled(False)
        else:
            if self.netSwitchCombo.isEnabled():
                self.netSwitchCheck.setChecked(False)
                self.netSwitchCombo.setEnabled(False)
            else:
                self.netSwitchCheck.setChecked(True)
                self.netSwitchCombo.setEnabled(True)
    def refreshAutoNet(self):
        self.centerApi = CenterApi(self)
        autoNetWork = self.centerApi.getAutoConfNetFlag()
        LogRecord.instance().logger.info(u"初始化平台的自动获取按钮的状态")
        if (autoNetWork == "true"):
            LogRecord.instance().logger.info(u"初始化平台的自动获取按钮的状态为真")
           
            self.cbNetworkAuto.setChecked(True)
            self.twNetwork.setEnabled(False)
            self.deleteButton.setEnabled(False)
            self.editButton.setEnabled(False)
    def refreshComboNet(self):
        LogRecord.instance().logger.info(u"开始获取本地网络列表，并且将这个列表显示在combo框中，进入getnetinfo的getNetAddressList函数")
        netAddressList = self.netCtl.getNetAddressList()
        num = len(netAddressList)
        LogRecord.instance().logger.info(u"获得当前使用的本地网络，进入函数getnetinfo的getCurrentNetworkInfo")
        curNetInfo = self.netCtl.getCurrentNetworkInfo()
        self.netComboBox.clear()
        self.sslCheckBox.setChecked(True)
        self.lineEditPort.setText("443")
        index = -1
        #刷新表格内容
        for i in range(num):
            if (not curNetInfo == ""):
                netName = netAddressList[i]["netName"]
                if (netName == curNetInfo.split(":")[0]):
                    index = i
    
            self.netComboBox.addItem(netAddressList[i]["netName"])
            self.netComboBox.setItemData(i, netAddressList[i]["addressID"], Qt.UserRole + 1)
    
        self.netComboBox.setCurrentIndex(index)
        self.currentNetIndex = index
    def slotUpdateCenter(self):
        
        self.refreshNetworkTable()
        self.emit(SIGNAL("editupdatecenter"))
    def on_tableWidgetHost_customContextMenuRequested(self,pos):
        item = self.twNetwork.itemAt(pos)
        if (item != None):
            self.centerTableMenu.clear()
            self.centerTableMenu.addAction(self.delCenterAction)
            self.centerTableMenu.addAction(self.editCenterAction)
            self.centerTableMenu.exec_(QCursor.pos())   
    def slotEdit(self):
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的平台！").exec_()
            return
        self.editNetWork()
    def editNetWork(self):
    
        currentRow = self.twNetwork.currentRow()
        netNameItem = self.twNetwork.item(currentRow, 0)
        netName = netNameItem.text()
        netIPItem = self.twNetwork.item(currentRow, 1)
        netIP = netIPItem.text()
        netPortItem = self.twNetwork.item(currentRow, 2)
        netPort = netPortItem.text()
        netSslItem = self.twNetwork.item(currentRow, 3)
        netSsl = netSslItem.text()
        netCardItem = self.twNetwork.item(currentRow, 4)
        netCA = netCardItem.text()
        
        netLocalItem = self.twNetwork.item(currentRow, 5)
        netLocal = netLocalItem.text()
    
    
        centerEditItem = {}
        centerEditItem["netName"] = netName
        centerEditItem["netIp"] = netIP
        centerEditItem["netPort"] = netPort
        centerEditItem["netLocal"] = netLocal
        centerEditItem["netSsl"] = netSsl
        centerEditItem["netCard"] = netCA
    
        
        self.editDlg.setCenterInfo(centerEditItem)
        self.editDlg.show()
        self.editDlg.move(setting.globalfunc.moveToCenter(self.editDlg.width(), self.editDlg.height()))
        
    
    def on_cbNetworkAuto_clicked(self, isCheck):
        self.centerApi.setAutoConfNetFlag(isCheck)
        self.twNetwork.setEnabled(not isCheck)
        self.deleteButton.setEnabled(not isCheck)
        self.editButton.setEnabled(not isCheck)
        self.emit(SIGNAL("updatecenter"),"true")
        
    def showAddNetworkItemInfo(self,result):
        LogRecord.instance().logger.info(u"添加平台返回信息")
        if (result == 0):
            #刷新表格的内容
            self.refreshNetworkTable()
            #清空输入的信息
            self.lineEditName.setText("")
            self.lineEditCentre.clear()
            self.lineEditPort.setText("443")
    
            #表格选中新加的信息的行
            self.twNetwork.selectRow(self.twNetwork.rowCount()-1)
            
            self.emit(SIGNAL("updatecenter"),"true")
            self.waitDlg.close()
            self.infoHint.setHintInfo(u"添加平台成功!")
            self.infoHint.show()
            self.infoHint.move(setting.globalfunc.moveToCenter(self.infoHint.width(),self.infoHint.height()))
            return
        
        elif(result == 2):
            self.waitDlg.close()
            self.waitDlg.setTip(u"证书获取中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
            return
        
        elif(result == -1):
            self.waitDlg.close()
            InfoHintDialog(u"打开配置文件失败！").exec_()
            return
        elif(result == -2):
            self.waitDlg.close()
            InfoHintDialog(u"创建证书目录失败！").exec_()
            return
        
        elif(result == -3):
            self.waitDlg.close()
            InfoHintDialog(u"保存对应证书失败！").exec_()
            return
        elif(result == -4):
            self.waitDlg.close()
            InfoHintDialog(u"该名称的网络已存在！").exec_()
            return
        elif(result == -5):
            self.waitDlg.close()
            InfoHintDialog(u"证书比较发生错误！").exec_()
            return
        elif(result == -6):
            self.waitDlg.close()
            InfoHintDialog(u"当前网络中的证书已存在！").exec_()
            return
        elif(result == -7):
            self.waitDlg.close()
            InfoHintDialog(u"删除临时证书失败！").exec_()
            return 
        elif(result == -9):
            self.waitDlg.close()
            InfoHintDialog(u"下载授权文件失败!").exec_()
            return
        elif(result == 1):
            self.waitDlg.setTip(u"重启网络中....")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
            return
        
        #域获取
        elif (result == 3):
            self.waitDlg.setTip(u"正在获取域...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
            return
        elif(result == -10):
            self.waitDlg.close()
            InfoHintDialog(u"获取域失败，请勾选ssl复选框!").exec_()
            return
        elif(result == -11):
            self.waitDlg.close()
            InfoHintDialog(u"获取域失败，请勾选ssl复选框!").exec_()
            return
        elif(result == -8):
            self.waitDlg.close()
            InfoHintDialog(u"重启网络服务失败!").exec_()
            return
        
        
        else:
            return
    def showAuthCertificateInfo(self,result):
        LogRecord.instance().logger.info(u"授权返回信息")
        
        if (result == 0):
            self.emit(SIGNAL("updatedomain"))
            """
            bool issucc = QDBusConnection.sessionBus().send(msg);
            if (!issucc)
                qDebug("error send msg false");
            """
            self.waitDlg.close()
            self.infoHint.setHintInfo(u"授权成功!")
            self.infoHint.show()
            self.infoHint.move(setting.globalfunc.moveToCenter(self.infoHint.width(),self.infoHint.height()))
            return
        elif(result == 1):
            self.waitDlg.setTip(u"重启网络中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
            return
        elif(result == -1):
            self.waitDlg.close()
            self.infoHint.setHintInfo(u"下载授权文件失败!")
            self.infoHint.show()
            self.infoHint.move(setting.globalfunc.moveToCenter(self.infoHint.width(),self.infoHint.height()))
            return
        elif(result == 2):
            self.waitDlg.close()
            self.waitDlg.setTip(u"获取证书中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
            return
        elif(result == -2):
            self.waitDlg.close()
            InfoHintDialog(u"授权失败：写文件失败").exec_()
            return
        elif(result == -3):
            ###waitDlg.close();
            self.waitDlg.close()
            InfoHintDialog(u"证书不一致!").exec_()
            return
        elif(result == -4):
            self.waitDlg.close()
            InfoHintDialog(u"授权失败：未知错误").exec_()
            return
        elif(result == -5):
            self.waitDlg.close()
            self.infoHint.setHintInfo(u"重启网络失败!")
            self.infoHint.show()
            self.infoHint.move(setting.globalfunc.moveToCenter(self.infoHint.width(),self.infoHint.height()))
            return
        else:
            return

    def showNetworkSwitchInfo(self,result):
        if (result == 0):
            self.emit(SIGNAL("updatedomain"))
            """
            bool issucc = QDBusConnection.sessionBus().send(msg);
            if (!issucc)
                qDebug("error send msg false");
            """
            self.waitDlg.close()
            InfoHintDialog(u"授权成功!").exec_()
            self.infoHint.setHintInfo(u"授权成功!")
            self.infoHint.show()
            self.infoHint.move(setting.globalfunc.moveToCenter(self.infoHint.width(),self.infoHint.height()))
            return
        
        elif(result == 1):
            self.waitDlg.setTip(u"启动网络中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
            return
        
        elif(result == -1):
            self.waitDlg.close()
            self.infoHint.setHintInfo(u"重启网络失败!")
            self.infoHint.show()
            self.infoHint.move(setting.globalfunc.moveToCenter(self.infoHint.width(),self.infoHint.height()))
            return
        elif(result == 2):
            self.waitDlg.setTip(u"获取网络中...")
            self.waitDlg.show()
            self.waitDlg.move(setting.globalfunc.moveToCenter(self.waitDlg.width(), self.waitDlg.height()))
            return
        elif(result == -2):
            self.waitDlg.close()
            self.infoHint.setHintInfo(u"下载授权文件失败!")
            self.infoHint.show()
            self.infoHint.move(setting.globalfunc.moveToCenter(self.infoHint.width(),self.infoHint.height()))
            return
        else:
            return
    def showRestartNetworkInfo(self,result):
        LogRecord.instance().logger.info(u"重启网络返回信息，发送信号更新另外界面的显示信息")
        self.emit(SIGNAL("centerRestartNetworkSignal"),result)
        self.emit(SIGNAL("updatecenter"),"true")
     
    def addNetworkItem(self,num):
        if num == 0:
            self.refreshNetworkTable()
    
    def on_comboBoxNetName_activated(self,index):
        LogRecord.instance().logger.info(u"网络切换combo")
        if (index == self.currentNetIndex):
            return
        else:
            self.currentNetIndex = index
            id = self.netComboBox.itemData(index, Qt.UserRole + 1).toString()
            #重启网络
            self.switchThread.setNetID(id)
            LogRecord.instance().logger.info(u"重启网络，进入netswitch的RESTART_NET_SERVERS")
            self.switchThread.setFunType("RESTART_NET_SERVERS")
            self.switchThread.start()
            self.emit(SIGNAL("centerRestartNetworkSignal"),1000)
    
    def on_pushButtonAdd_clicked(self):
        LogRecord.instance().logger.info(u"点击添加按钮")
        #判断输入的信息是否有效
        centerName = self.lineEditName.text().trimmed()
        centerIp = self.lineEditCentre.text().trimmed()
        centerPort = self.lineEditPort.text().trimmed()
        centerNetWork = self.netComboBox.currentText()
        if self.netSwitchCheck.isChecked():
            centerNetSwitch = self.netSwitchCombo.currentText()
        else:
            centerNetSwitch = "None"
    
        # if (centerNetWork == ""):
        #     InfoHintDialog(u"请选择或配置相应的网络!").exec_()
        #     return
        
        curIndex = int(self.netComboBox.currentIndex())
        netId = self.netComboBox.itemData(curIndex, Qt.UserRole + 1).toString()

        ipl=centerIp.split(" ",QString.SkipEmptyParts)
        centerIp=""
        for i in range(len(ipl)):
            centerIp=centerIp+ipl[i]
        
        #端口去空格
        pol=centerPort.split(" ",QString.SkipEmptyParts)
        centerPort=""
        for i in range(len(pol)):
            centerPort=centerPort+pol[i]
        
        if( centerName == "" or centerPort == "" or centerIp == "" or centerIp == "..."):
            InfoHintDialog(u"名称，平台或端口号不得为空!").exec_()
            return

        #获得临时证书
        if(self.cbNetworkAuto.isChecked()):
            ssl = "false"
        else:
            ssl = "true"
        
        info = {}
        info["netName"] = centerName
        info["netIp"] = centerIp
        info["netPort"] = centerPort
        info["netSsl"] = ssl
        info["netId"] = netId
        info["networkName"] = centerNetWork
        info["netSwitch"] = centerNetSwitch
        
        self.switchThread.setNetInfo(info)
        registerid = self.switchThread.registerTerminalInfo()
                
        temp = str(registerid).find("cannot be modified")
        if temp != -1:
            try:
                ipaddr = registerid.split("(")[1].split(")")[0]
                infostr = u"该终端IP已与MAC绑定请修改ip为:" + ipaddr 
                InfoHintDialog(infostr).exec_()
                return 
            except:
                InfoHintDialog(u"该终端IP已与MAC绑定，不能修改IP！").exec_()
                return 
        
        if len(registerid.split("-")) == 5 and len(registerid) == 36:
            LogRecord.instance().logger.info("注册成功！")
            self.switchThread.setTerminalId(registerid)
        else:
            InfoHintDialog(u"注册失败！").exec_()
            return 
        
        self.switchThread.setFunType("ADD_NETWORK_ITEM")
        self.switchThread.start()
        
        LogRecord.instance().logger.info(u"添加平台的同时注册，注册ID")
        LogRecord.instance().logger.info(registerid)
        self.emit(SIGNAL("registerterminal"),registerid)  #?????
        
    def on_pushButtonDelete_clicked(self):
        LogRecord.instance().logger.info(u"点击删除按钮")
        itemsList = self.twNetwork.selectedItems()
        if (len(itemsList) == 0):
            InfoHintDialog(u"请选择相应的平台！").exec_()
            return
        LogRecord.instance().logger.info(u"进入自身函数deleteNetwork")
        self.deleteNetwork()
    def deleteNetwork(self):
        
        if (MessageBox(u"确定删除该平台吗?").exec_() == QDialog.Rejected):
            return
        currentRow = self.twNetwork.currentRow()
        item = QTableWidgetItem(self.twNetwork.item(currentRow, 4))
        centerName = QTableWidgetItem(self.twNetwork.item(currentRow, 0)).text()
        if (item != ""):
            caName = item.text()
            LogRecord.instance().logger.info(u"进入centerapi的delNetWorkSwitchItem函数，删除证书和平台")
            result = self.centerApi.delNetWorkSwitchItem(caName)
            if (result == -1):
                InfoHintDialog(u"删除网络失败!").exec_()
                return
            elif (result == -2):
                InfoHintDialog(u"打开证书比较文件失败!").exec_()
                return
            elif (result == -3):
                InfoHintDialog(u"删除证书失败!").exec_()
                return
            elif (result == -4):
                InfoHintDialog(u"打开平台配置文件失败!").exec_()
                return
            else:
                    #刷新表格内容
                self.refreshNetworkTable()
                
                    #删除该平台自动登录的用户记录
                content = StoreInfoParser.instance().getLoginSet()
                if content:
                    autoLoginCenter = content.split(",")[3]
                    if centerName == autoLoginCenter:
                        StoreInfoParser.instance().removeLoginSet()
                        
                StoreInfoParser.instance().removeLoginSet()
                InfoHintDialog(u"删除平台成功！").exec_()
                LogRecord.instance().logger.info(u"发送信号更新平台和域")
                self.emit(SIGNAL("updatedomain"))
                self.emit(SIGNAL("updatecenter"),"true")
        
        
    def settwNetWorkRowData(self,row,netSwitch):
        print (netSwitch)
        pTWItemNetName = QTableWidgetItem(netSwitch["netName"])
        pTWItemNetName.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 0, pTWItemNetName)
    
        pTWItemNetIp = QTableWidgetItem(netSwitch["netIp"])
        pTWItemNetIp.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 1, pTWItemNetIp)
    
        pTWItemNetPort = QTableWidgetItem(netSwitch["netPort"])
        pTWItemNetPort.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 2, pTWItemNetPort)
    
        pTWItemNetSsl = QTableWidgetItem(netSwitch["netSsl"]);
        pTWItemNetSsl.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 3, pTWItemNetSsl)
    
        pTWItemNetCaName = QTableWidgetItem(netSwitch["netCaName"])
        pTWItemNetCaName.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 4, pTWItemNetCaName)
    
        pTWItemNetWorkName = QTableWidgetItem(netSwitch["networkName"])
        pTWItemNetWorkName.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 5, pTWItemNetWorkName)
        
        pTWItemNetWorkName = QTableWidgetItem(netSwitch["netSwitch"])
        pTWItemNetWorkName.setTextAlignment(Qt.AlignCenter)
        self.twNetwork.setItem(row, 6, pTWItemNetWorkName)


    def refreshNetworkTable(self):
        LogRecord.instance().logger.info(u"更新平台的列表的界面化显示，开始获取平台列表")
        netSwitchlist = self.centerApi.getNetSwitchList()
        if netSwitchlist < 0 :
            LogRecord.instance().logger.info(u"获取平台列表为空")
            num = 0
        else:
            num = len(netSwitchlist)
        if( 0 == num ):
            self.twNetwork.setRowCount(num)
            self.deleteButton.setEnabled(False)
            self.editButton.setEnabled(False)
            return
        
        self.deleteButton.setEnabled(self.twNetwork.isEnabled())
        self.editButton.setEnabled(self.twNetwork.isEnabled())
        self.twNetwork.setRowCount(num)
        print (netSwitchlist) 
        LogRecord.instance().logger.info(u"开始将列表显示在表格中")
        for i in range(num):
            self.settwNetWorkRowData(i,netSwitchlist[i])
            
    def closeTabWidget(self):
        LogRecord.instance().logger.info(u"点击关闭按钮，发送信号")
        self.emit(SIGNAL("closetabwidget"))
        
    def on_checkBox_clicked(self):
        LogRecord.instance().logger.info(u"点击ssl选项按钮更新端口号")
        
        if (self.sslCheckBox.isChecked()):
            self.lineEditPort.setText("443")
        else:
            self.lineEditPort.setText("80")
            
            
         
