import sys

from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import QMessageBox, QMainWindow
import os

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(CURRENT_DIR)
if PROJECT_ROOT not in sys.path:
    sys.path.insert(0, PROJECT_ROOT)

from window.Login import Ui_LoginWindow
from bsphp.main import BsPhp
try:
    from .Main import Main
except ImportError:
    from Main import Main


class Login(QMainWindow, Ui_LoginWindow):
    def __init__(self):
        super(Login, self).__init__()
        self.setupUi(self)


        #初始化配置参数
        self.bsPhp = BsPhp(
            #初始化接口地址
            "https://demo.bsphp.com/AppEn.php?appid=8888888&m=95e87faf2f6e41babddaef60273489e1&lang=0",
            #通信KEY
            "6600cfcd5ac01b9bb3f2460eb416daa8",
            #服务器私钥
            "MIIEqAIBADANBgkqhkiG9w0BAQEFAASCBJIwggSOAgEAAoH+DEr7H5BhMwRA9ZWXVftcCWHznBdl0gQBu5617qSe9in+uloF1sC64Ybdc8Q0JwQkGQANC5PnMqPLgXXIfnl7/LpnQ/BvghQI5cr/4DEezRKrmQaXgYfXHL3woVw7JIsLpPTGa7Ar9S6SEH8RcPIbZjlPVRZPwV3RgWgox2/4lkXsmopqD+mEtOI/ntvti147nEpK2c7cdtCU5M2hQSlIXsTWvri88RTYJ/CtopBOXarUkNBfpWGImiYGsmbZI+YZ6uU0wSYlq8huu+pkTseUUiymzmv8Rpg3coi7YU+pszvB9wnQ1Rz6Z/B6Z3WN7d6OP7f9w0Q0WvgrsKcEJhMCAwEAAQKB/gHa5t6yiRiL0cm902K0VgVMdNjfZww0cpZ/svDaguqfF8PDhhIMb6dNFOo9d6lTpKbpLQ7MOR2ZPkLBJYqAhsdy0dac2BcHMviKk+afQwirgp3LMt3nQ/0gZMnVA0/Wc+Fm1vK1WUzcxEodAuLKhnv8tg4fGdYSdGVU9KJ0MU1bKQZXv0CAIhJYWsiCa5y5bFO7K+ia+UIVBHcvITQLzlgEm+Z/X6ye5cws4pWbk8+spsBDvweb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0KFSmqAPtLbrl6p5Sp+ZUSYEYQhSxAajE5qRCd3k0r/MIQQanBaOALkP71/u6U2SZhrTXd05n1wQo6ojMH/xVunBOFOa/Eon/Y5FVh6GiJpwwDkFzTlnecmff7Y+VDqRhZ7vu2CQjApOx23N6DiFEmVZYEb/efyASngoZ+3A/DSB5cwbaYVZ21EhPe/GNcwtUleFHn+d4vb0cvolO3Gyw6ObceOT/Q7E3k8ejIml6vPKzmRdtw0FXGOJTclx1CjShRDfXoUjFGyXHy3sZs9VLAgMBAAE=",
        )

        #设置验证码链接地址
        self.bsPhp.code_url = "https://demo.bsphp.com/index.php?m=coode&sessl="





        if not self.bsPhp.connect():
            self.message_box('初始化失败！')
            sys.exit(0)
        if not self.bsPhp.get_se_ssl():
            self.message_box('获取BSphpSeSsL失败!')
            sys.exit(0)
        code = self.bsPhp.code_is_open('INGES_LOGIN|INGES_RE|INGES_MACK|INGES_SAY')
        if not code:
            self.message_box('系统错误！')
            sys.exit(0)
        self.frame_login_code.show() if 'INGES_LOGIN' in code else self.frame_login_code.hide()  # 登录
        self.frame_reg_code.show() if 'INGES_RE' in code else self.frame_reg_code.hide()  # 注册
        self.frame_forgot_code.show() if 'INGES_MACK' in code else self.frame_forgot_code.hide()  # 找回密码
        self.frame_edit_code.show() if 'INGES_MACK' in code else self.frame_edit_code.hide()  # 修改密码
        self.frame_feedback_code.show() if 'INGES_SAY' in code else self.frame_feedback_code.hide()  # 意见反馈
        self.label_notice.setText(self.bsPhp.get_notice())  # 获取公告
        self.init_event()
        self.show()

    def init_event(self):
        self.label_login_code.mouseReleaseEvent = self.onCode
        self.label_reg_code.mouseReleaseEvent = self.onCode
        self.label_back_code.mouseReleaseEvent = self.onCode
        self.label_edit_code.mouseReleaseEvent = self.onCode
        self.label_feedback_code.mouseReleaseEvent = self.onCode

    def get_code(self, index: int):
        """获取验证码"""
        photo = QPixmap()
        photo.loadFromData(self.bsPhp.get_code())
        if index == 0:
            self.label_login_code.setPixmap(photo)
            self.label_login_code.setScaledContents(True)
        elif index == 1:
            self.label_reg_code.setPixmap(photo)
            self.label_reg_code.setScaledContents(True)
        elif index == 4:
            self.label_back_code.setPixmap(photo)
            self.label_back_code.setScaledContents(True)
        elif index == 5:
            self.label_edit_code.setPixmap(photo)
            self.label_edit_code.setScaledContents(True)
        elif index == 6:
            self.label_feedback_code.setPixmap(photo)
            self.label_feedback_code.setScaledContents(True)

    def onCode(self, QMouseEvent):
        """获取验证码单击事件"""
        self.get_code(self.tabWidget.currentIndex())

    def onTestConnect(self):
        """测试网络按钮事件"""
        if self.bsPhp.connect():
            self.message_box('测试连接成功！')
        else:
            self.message_box('测试连接失败！')

    def onCheckVersion(self):
        """检测版本"""
        result = self.bsPhp.get_version()
        if not result:
            self.message_box('检测版本失败')
        else:
            if result != '1.0':
                code = self.message_box('你的软件不是最新版本是否要更新', QMessageBox.Yes | QMessageBox.No)
                if code == QMessageBox.Yes:
                    os.system('start ' + self.bsPhp.get_url())

    def onLogin(self):
        """账号登录事件"""

        result = self.bsPhp.login(self.lineEdit_login_user.text(), self.lineEdit_login_pass.text(),
                                  self.lineEdit_login_code.text(), "123213", "213123")
        if isinstance(result, str):
            self.message_box(result)
            return
        Main(self, self.bsPhp, result[4])

    def onReg(self):
        """账号注册"""
        result = self.bsPhp.reg(
            self.lineEdit_reg_user.text(),
            self.lineEdit_reg_pass.text(),
            self.lineEdit_reg_passd.text(),
            self.lineEdit_reg_code.text(),
            self.lineEdit_reg_phone.text(),
            self.comboBox_reg_wenti.currentText(),
            self.lineEdit__reg_daan.text(),
            self.lineEdit__reg_qq.text(),
            self.lineEdit_reg_email.text(),
        )
        self.message_box(result)

    def onUnbind(self):
        """解绑事件"""
        result = self.bsPhp.unbind(self.lineEdit__unbind_user.text(), self.lineEdit_unbind_pass.text())
        self.message_box(result)

    def onPay(self):
        """充值事件"""
        result = self.bsPhp.pay(self.lineEdit_pay_user.text(), self.lineEdit_pay_pass.text(),
                                self.checkBox_pay_pass.checkState(), self.lineEdit_pay_card.text(),
                                self.lineEdit_pay_cardpass.text())
        self.message_box(result)

    def onBack(self):
        """找回密码事件"""
        result = self.bsPhp.back_pass(self.lineEdit_back_user.text(), self.lineEdit__back_pass.text(),
                                      self.lineEdit_back_passd.text(), self.comboBox_back_wenti.currentText(),
                                      self.lineEdit_back_daan.text(), self.lineEdit_back_code.text())
        self.message_box(result)

    def onEdit(self):
        """修改密码事件"""
        result = self.bsPhp.edit_pass(
            self.lineEdit_edit_user.text(),
            self.lineEdit_edit_pass.text(),
            self.lineEdit_edit_newpass.text(),
            self.lineEdit_edit_newpassd.text(),
            self.lineEdit_edit_code.text()
        )
        self.message_box(result)

    def onFeedback(self):
        """意见反馈事件"""
        result = self.bsPhp.edit_pass(
            self.lineEdit_feedback_user.text(),
            self.lineEdit_feedback_pass.text(),
            self.lineEdit_feedback_title.text(),
            self.lineEdit_feedback_info.text(),
            self.comboBox_feedback_type.currentText(),
            self.textEdit_feedback_content.toPlainText(),
            self.lineEdit_feedback_code.text()
        )
        self.message_box(result)

    def message_box(self, info: str, button=QMessageBox.Yes):
        """
        信息框
        :param info: 内容
        :param button: 按钮
        :return:
        """
        return QMessageBox.information(None, "", info, button, QMessageBox.Yes)
