from PyQt6.QtCore import pyqtSlot
from PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox
import sys
import os
from Authorization import Ui_Authorization
from Registration import Ui_Registration
from MainWindow import Ui_MainWindow

DATA_FILE = "user_data.txt"

class AuthorizationWindow(QMainWindow, Ui_Authorization):
    def __init__(self):
        super(AuthorizationWindow, self).__init__()
        self.setupUi(self)
        
        # Handle "Зарегистрироваться" button click
        self.pushButton_3.clicked.connect(self.open_registration)

        # Handle "Войти" button click
        self.pushButton.clicked.connect(self.login)

        self.user_data = self.load_user_data()

    def load_user_data(self):
        """Load user data from a file."""
        if not os.path.exists(DATA_FILE):
            return {}
        
        user_data = {}
        with open(DATA_FILE, "r") as file:
            for line in file:
                parts = line.strip().split(",")
                if len(parts) == 2:  # Старый формат, только имя пользователя и пароль
                    username, password = parts
                    email = ""  # Email отсутствует в старом формате
                elif len(parts) == 3:  # Новый формат, включает email
                    username, password, email = parts
                else:
                    continue  # Неправильный формат строки, пропускаем
                
                user_data[username] = {"password": password, "email": email}
        return user_data

    def save_user_data(self):
        """Save user data to a file."""
        with open(DATA_FILE, "w") as file:
            for username, data in self.user_data.items():
                file.write(f"{username},{data['password']},{data['email']}\n")
    
    @pyqtSlot()
    def open_registration(self):
        self.registration_window = RegistrationWindow(self)
        self.registration_window.show()

    @pyqtSlot()
    def login(self):
        username = self.lineEdit.text()
        password = self.lineEdit_2.text()

        msg_box = QMessageBox(self)
        msg_box.setStyleSheet("background-color: white;")

        if username in self.user_data and self.user_data[username]["password"] == password:
            msg_box.setText("Вы успешно вошли в систему!")
            msg_box.setIcon(QMessageBox.Icon.Information)

            # Открываем главного главное окно и закрываем окно авторизации
            self.main_window = MainWindowWindow(self)
            self.main_window.show()
            self.close()

        else:
            msg_box.setText("Неверный логин или пароль!")
            msg_box.setIcon(QMessageBox.Icon.Warning)
            
        msg_box.exec()

class RegistrationWindow(QMainWindow, Ui_Registration):
    def __init__(self, auth_window):
        super(RegistrationWindow, self).__init__()
        self.setupUi(self)

        # Reference to the authorization window to store user data
        self.auth_window = auth_window

        # Handle "Сохранить" button click
        self.pushButton.clicked.connect(self.save_registration)

    @pyqtSlot()
    def save_registration(self):
        email = self.lineEdit_3.text()
        username = self.lineEdit.text()
        password = self.lineEdit_2.text()
        confirm_password = self.lineEdit_4.text()

        msg_box = QMessageBox(self)
        msg_box.setStyleSheet("background-color: white;")

        if password != confirm_password:
            msg_box.setText("Пароли не совпадают!")
            msg_box.setIcon(QMessageBox.Icon.Warning)
            msg_box.exec()
            return

        self.auth_window.user_data[username] = {"password": password, "email": email}
        self.auth_window.save_user_data()
        msg_box.setText("Регистрация успешна!")
        msg_box.setIcon(QMessageBox.Icon.Information)
        msg_box.exec()

        self.close()

class MainWindowWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, auth_window):
        super(MainWindowWindow, self).__init__()
        self.setupUi(self)
        self.auth_window = auth_window
        self.initialize_signals()

        # You can add more initialization code here if necessary
        # Открытие приложения с первым отображаемым tab
        self.tabWidget.setCurrentIndex(0)  # Установите индекс нужного вкладки (например, 0 для первой вкладки)
#*************************************************
    def initialize_signals(self):
        # Connect comboBox signals to methods
        self.comboBox_3.currentIndexChanged.connect(self.handle_comboBox_3_change)
        self.comboBox_6.currentIndexChanged.connect(self.handle_comboBox_6_change)
        
        # Connect pushButton signals to methods
        self.pushButton_2.clicked.connect(self.handle_push_button_2)
        self.pushButton_3.clicked.connect(self.handle_push_button_3)

        self.pushButton_2.clicked.connect(self.switch_to_tab8)
        self.pushButton_3.clicked.connect(self.switch_to_tab7)

        self.pushButton_4.clicked.connect(self.handle_addition)


    def handle_comboBox_3_change(self, index):
        if index == 0:  # Index for "1"
            self.tabWidget.setCurrentIndex(0)  # Set to tab3
        elif index == 1:  # Index for "2"
            self.tabWidget.setCurrentIndex(1)  # Set to tab4

    def handle_comboBox_6_change(self, index):
         if index == 0:  # Index for "3"
            self.tabWidget.setCurrentIndex(2)  # Set to tab5

    def handle_push_button_2(self):
        # Set tabWidget to tab2
        self.tabWidget_3.setCurrentIndex(1)

    def handle_push_button_3(self):
        # Set tabWidget to tab (initial tab)
        self.tabWidget_3.setCurrentIndex(0)

    def switch_to_tab8(self):
        # Change the active tab in tabWidget3 to tab7
        self.tabWidget_2.setCurrentIndex(1)

    def switch_to_tab7(self):
        # Change the active tab in tabWidget3 to tab6
        self.tabWidget_2.setCurrentIndex(0)
    
    #************************************************* 
    #Анализ показателей финансовой устойчивости
    def handle_addition(self):
    #1 год   
        try:
            num1 = float(self.lineEdit_110.text())
            num2 = float(self.lineEdit_126.text())
            num3 = float(self.lineEdit_86.text())

            result = (num1 + num2)/num3
            self.label_156.setText(str(result))
        except ValueError:
            self.label_156.setText("Ошибка ввода")
        
        try:
            num3 = float(self.lineEdit_86.text())
            num4 = float(self.lineEdit_29.text())
            num5 = float(self.lineEdit_23.text())

            result2 = (num3 - num4)/num5
            self.label_172.setText(str(result2))
        except ValueError:
            self.label_172.setText("Ошибка ввода")


        try:
            num3 = float(self.lineEdit_86.text())
            num6 = float(self.lineEdit_127.text())

            result3 = num3/num6
            self.label_180.setText(str(result3))
        except ValueError:
            self.label_180.setText("Ошибка ввода")

        try:
            num3 = float(self.lineEdit_86.text())
            num1 = float(self.lineEdit_110.text())
            num2 = float(self.lineEdit_126.text())

            result4 = num3/(num1+num2)
            self.label_164.setText(str(result4))
        except ValueError:
            self.label_164.setText("Ошибка ввода")

        try:
            num3 = float(self.lineEdit_86.text())
            num1 = float(self.lineEdit_110.text())
            num6 = float(self.lineEdit_127.text())

            result5 = (num3+num1)/(num6)
            self.label_148.setText(str(result5))
        except ValueError:
            self.label_148.setText("Ошибка ввода")

        #2 год   
        try:
            num21 = float(self.lineEdit_116.text())
            num22 = float(self.lineEdit_146.text())
            num23 = float(self.lineEdit_93.text())

            result21 = (num21 + num22)/num23
            self.label_158.setText(str(result21))
        except ValueError:
            self.label_158.setText("Ошибка ввода")
        
        try:
            num23 = float(self.lineEdit_93.text())
            num24 = float(self.lineEdit_47.text())
            num25 = float(self.lineEdit_66.text())

            result22 = (num23 - num24)/num25
            self.label_173.setText(str(result22))
        except ValueError:
            self.label_173.setText("Ошибка ввода")


        try:
            num23 = float(self.lineEdit_93.text())
            num26 = float(self.lineEdit_147.text())

            result23 = num23/num26
            self.label_181.setText(str(result23))
        except ValueError:
            self.label_181.setText("Ошибка ввода")

        try:
            num23 = float(self.lineEdit_93.text())
            num21 = float(self.lineEdit_116.text())
            num22 = float(self.lineEdit_146.text())

            result24 = num23/(num21+num22)
            self.label_165.setText(str(result24))
        except ValueError:
            self.label_165.setText("Ошибка ввода")

        try:
            num23 = float(self.lineEdit_93.text())
            num21 = float(self.lineEdit_116.text())
            num26 = float(self.lineEdit_147.text())

            result25 = (num23+num21)/(num26)
            self.label_149.setText(str(result25))
        except ValueError:
            self.label_149.setText("Ошибка ввода")

        #3 год   
        try:
            num31 = float(self.lineEdit_117.text())
            num32 = float(self.lineEdit_145.text())
            num33 = float(self.lineEdit_100.text())

            result31 = (num31 + num32)/num33
            self.label_157.setText(str(result31))
        except ValueError:
            self.label_157.setText("Ошибка ввода")
        
        try:
            num33 = float(self.lineEdit_100.text())
            num34 = float(self.lineEdit_48.text())
            num35 = float(self.lineEdit_71.text())

            result32 = (num33 - num34)/num35
            self.label_174.setText(str(result32))
        except ValueError:
            self.label_174.setText("Ошибка ввода")


        try:
            num33 = float(self.lineEdit_100.text())
            num36 = float(self.lineEdit_148.text())

            result33 = num33/num36
            self.label_182.setText(str(result33))
        except ValueError:
            self.label_182.setText("Ошибка ввода")

        try:
            num33 = float(self.lineEdit_100.text())
            num31 = float(self.lineEdit_117.text())
            num32 = float(self.lineEdit_145.text())

            result34 = num33/(num31+num32)
            self.label_166.setText(str(result34))
        except ValueError:
            self.label_166.setText("Ошибка ввода")

        try:
            num33 = float(self.lineEdit_100.text())
            num31 = float(self.lineEdit_117.text())
            num36 = float(self.lineEdit_148.text())

            result35 = (num33+num31)/(num36)
            self.label_150.setText(str(result35))
        except ValueError:
            self.label_150.setText("Ошибка ввода")


    #*************************************************
def main():
    app = QApplication(sys.argv)

    auth_window = AuthorizationWindow()
    auth_window.show()

    sys.exit(app.exec())

if __name__ == "__main__":
    main()


Как добавить Chat GPT который бы анализировал получившиеся расчёты и выводил вывод в Label_139