from PySide6.QtWidgets import (QMainWindow, QWidget, QGridLayout, QMessageBox,
                              QPushButton, QSizePolicy, QSplitter, QToolBar)
from PySide6.QtGui import QFontDatabase
from PySide6.QtCore import Signal, Qt

import os
from info_core.defines import *
from info_core.MyQtClass import (ConfigComboBoxGroup, FolderDropWidget, 
                                 OutputDirSelector, FolderBrowser)

class ReportGeneratorUI(QMainWindow):
    send_baogao_choose_info = Signal(list[str])
    
    def __init__(self):
        super().__init__()
        # 加载字体
        self.load_font()
        
        # 设置窗口属性
        self.setWindowTitle("报告生成器")
        self.setMinimumSize(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGHT)
        
        # 主窗口部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 主布局
        self.main_layout = QGridLayout(self.central_widget)
        self.main_layout.setSpacing(MAIN_LAYOUT_SPACING)
        self.main_layout.setContentsMargins(*MAIN_LAYOUT_MARGINS)
        
        # 初始化UI
        self.init_ui()
        
    
    def load_font(self):
        """加载自定义字体"""
        if os.path.exists(FONT_PATH):
            font_id = QFontDatabase.addApplicationFont(FONT_PATH)
            if font_id == -1:
                print("字体加载失败，将使用系统默认字体")
        else:
            print(f"字体文件未找到: {FONT_PATH}，将使用系统默认字体")
        
    def init_ui(self):
        """初始化所有UI组件"""
        # 第一行：项目信息和人员配置
        self.project_group = ConfigComboBoxGroup("项目基本信息")
        self.staff_group = ConfigComboBoxGroup("单次检查配置信息", is_project=False)
        # 第二行：导入图片路径、填写机组信息
        self.picture_group = FolderDropWidget()
        # 第三行：生成报告按钮（跨两列）
        self.fill_turbine_info_button()
        self.fill_btn.clicked.connect(self.on_fill_clicked)
        
        # 创建一个垂直分割器
        self.splitter = QSplitter(Qt.Vertical)
        self.splitter.setStyleSheet(SPLITTER_STYLE)
        # 创建顶部和底部容器
        top_container = QWidget()
        top_container.setLayout(QGridLayout())
        top_container.layout().addWidget(self.project_group, 0, 0)
        top_container.layout().addWidget(self.staff_group, 0, 1)

        middle_container = QWidget()
        middle_container.setLayout(QGridLayout())
        middle_container.layout().addWidget(self.picture_group, 0, 0)

        # 添加部件到分割器
        self.splitter.addWidget(top_container)
        self.splitter.addWidget(middle_container)

        # 设置主布局
        self.main_layout.addWidget(self.splitter, 0, 0, 2, 2)  # 占据前两行两列
        self.main_layout.addWidget(self.fill_btn, 2, 0, 1, 2)

        # 设置分割器初始比例
        self.splitter.setStretchFactor(0, 1)
        self.splitter.setStretchFactor(1, 4)

        self.init_toolbar()
        self.create_warning_box()
        self.create_info_fill_widget()
    
    def init_toolbar(self):
        self.toolbar = QToolBar()
        self.addToolBar(self.toolbar)
        self.toolbar.setMovable(False)
        self.toolbar.setFloatable(False)
        new_action = self.toolbar.addAction("重置布局比例")

        self.output_dir_selector = OutputDirSelector()
        if not os.path.exists(os.getcwd() + "/output"):
            os.mkdir(os.getcwd() + "/output")
        self.output_dir_selector.set_output_dir(os.getcwd() + "/output")
        output_dir_choose_action = self.toolbar.addAction("选择输出目录")

        self.toolbar.addSeparator()

        new_action.triggered.connect(self.reset_splitter)
        output_dir_choose_action.triggered.connect(self.choose_output_dir)

    def reset_splitter(self):
        """重置分割器的比例"""
        total_size = sum(self.splitter.sizes())  # 获取当前总大小
        self.splitter.setSizes([
            int(total_size * 0.2),  # 第一部分占 20%（比例 1:4）
            int(total_size * 0.8)   # 第二部分占 80%
        ])

    def choose_output_dir(self):
        """选择输出目录"""
        self.output_dir_selector.show()

    def create_info_fill_widget(self):
        self.info_fill_widget = FolderBrowser()

    def create_warning_box(self):
        self.warning_box = QMessageBox(self)
        self.warning_box.setWindowTitle("警告")
        self.warning_box.setIcon(QMessageBox.Warning)
        self.warning_box.setStyleSheet(WARNING_MESSAGE_BOX_STYLE + MESSAGE_BOX_BUTTON_STYLE)

    def on_fill_clicked(self):
        """填写信息"""
        # 读取各个配置信息
        if len(self.picture_group.get_selected_folders()) <= 0:
            self.warning_box.setText("请先选择机组目录")
            self.warning_box.exec()
            return 
        if self.project_group.get_current_config_file() is None:
            self.warning_box.setText("请先选择/添加项目配置信息")
            self.warning_box.exec()
            return 
        if self.staff_group.get_current_config_file() is None:
            self.warning_box.setText("请先选择/添加人员配置信息")
            self.warning_box.exec()
            return 
        
        self.info_fill_widget.set_output_path(self.get_output_path())
        self.info_fill_widget.set_initial_folders(self.get_choosen_files())
        self.info_fill_widget.show()
    # search_file_list = []
    # if self.image_analysis.check_is_waibu:
    #     search_file_list.append("外汇总")
    # if self.image_analysis.check_is_neibu:
    #     search_file_list.append("内汇总")
    # if self.image_analysis.check_is_fanglei:
    #     search_file_list.append("防汇总")
    # self.send_baogao_choose_info.emit(search_file_list)
    
    def get_choosen_files(self):
        return self.picture_group.get_selected_folders()
    
    def get_output_path(self):
        return self.output_dir_selector.get_output_dir()

    def create_button(self, text):
        """创建统一风格的按钮"""
        btn = QPushButton(text)
        btn.setStyleSheet(BUTTON_STYLE)
        btn.setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT)
        return btn
    
    def fill_turbine_info_button(self):
        """创建生成报告按钮"""
        self.fill_btn = QPushButton("开始填写各个机组信息")
        self.fill_btn.setStyleSheet(PRIMARY_BUTTON_STYLE)
        self.fill_btn.setFixedHeight(50)
        self.fill_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
    