from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QTableWidget, QTableWidgetItem, \
    QHeaderView, QDialog, QLabel, QLineEdit, QCheckBox, QComboBox, QSizePolicy, QDialogButtonBox, QButtonGroup
from DatabaseManager import DatabaseManager
import config


class AddInstructionDialog(QDialog):
    def __init__(self, instruction_data=None):
        super().__init__()
        self.setWindowTitle("指令")
        self.setFixedSize(400, 300)

        layout = QVBoxLayout()

        # 指令名称行
        self.name_layout = QHBoxLayout()
        self.name_label = QLabel("指令名称:")
        self.name_edit = QLineEdit()
        self.name_layout.addWidget(self.name_label)
        self.name_layout.addWidget(self.name_edit)
        layout.addLayout(self.name_layout)

        # 指令类型行
        self.type_layout = QHBoxLayout()
        self.type_label = QLabel("指令类型:")
        self.type_combobox = QComboBox()
        self.type_combobox.addItems(["打开文件", "打开网址", "翻页控制", "窗口切换"])
        # 设置下拉框的大小策略，使其水平方向和文本输入框一样长
        self.type_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.type_layout.addWidget(self.type_label)
        self.type_layout.addWidget(self.type_combobox)
        layout.addLayout(self.type_layout)

        # 关键字行
        self.keyword_layout = QHBoxLayout()
        self.keyword_label = QLabel("  关键字:")
        self.keyword_edit = QLineEdit()
        self.keyword_layout.addWidget(self.keyword_label)
        self.keyword_layout.addWidget(self.keyword_edit)
        layout.addLayout(self.keyword_layout)

        # 执行动作行
        self.action_layout = QHBoxLayout()
        self.action_label = QLabel("执行动作:")
        self.action_edit = QLineEdit()
        self.action_layout.addWidget(self.action_label)
        self.action_layout.addWidget(self.action_edit)
        layout.addLayout(self.action_layout)

        # 确定和取消按钮
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        self.button_box.button(QDialogButtonBox.Ok).setText("确定")
        self.button_box.button(QDialogButtonBox.Cancel).setText("取消")
        layout.addWidget(self.button_box)

        self.setLayout(layout)

        # 如果有指令数据，则填充到输入框中
        if instruction_data:
            self.name_edit.setText(instruction_data["name"])
            self.keyword_edit.setText(instruction_data["keyword"])
            self.action_edit.setText(instruction_data["action"])
            # 选中对应的指令类型
            index = self.type_combobox.findText(instruction_data["type"])
            if index != -1:
                self.type_combobox.setCurrentIndex(index)

    def get_instruction_data(self):
        return {
            "name": self.name_edit.text(),
            "type": self.type_combobox.currentIndex(),
            "keyword": self.keyword_edit.text(),
            "action": self.action_edit.text()
        }


class FileSettingPage(QWidget):
    def __init__(self, c_datas):
        super().__init__()
        # 总布局
        self.layout = QVBoxLayout()

        # 顶部按钮布局
        self.top_layout = QHBoxLayout()
        self.btnAdd = QPushButton("添加")
        self.btnModify = QPushButton("修改")
        self.btnDelete = QPushButton("删除")
        self.top_layout.addWidget(self.btnAdd)
        self.top_layout.addWidget(self.btnModify)
        self.top_layout.addWidget(self.btnDelete)
        self.top_layout.addStretch()  # 使按钮靠左排列

        # 设置表格
        self.tableWidget = QTableWidget()
        self.tableWidget.setColumnCount(6)  # 设置列数，多加一列放置选择框和ID
        self.tableWidget.setHorizontalHeaderLabels(["", "ID", "指令名称", "指令类型", "关键字", "执行动作"])
        # self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 列宽度平均分配
        self.tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直表头

        # 获取表格总宽度
        total_width = self.tableWidget.width()
        self.tableWidget.setColumnWidth(0, int(total_width * 0.05))
        self.tableWidget.setColumnWidth(1, int(total_width * 0.08))
        self.tableWidget.setColumnWidth(2, int(total_width * 0.15))
        self.tableWidget.setColumnWidth(3, int(total_width * 0.15))
        self.tableWidget.setColumnWidth(4, int(total_width * 0.27))
        self.tableWidget.setColumnWidth(5, int(total_width * 0.30))

        # 添加按钮点击事件
        self.btnAdd.clicked.connect(self.add_instruction)
        self.btnModify.clicked.connect(self.modify_instruction)
        self.btnDelete.clicked.connect(self.delete_instruction)

        # 创建单选按钮组
        self.checkbox_group = QButtonGroup()

        self.show_table(c_datas)

        # 将布局添加到主布局
        self.layout.addLayout(self.top_layout)
        self.layout.addWidget(self.tableWidget)
        self.setLayout(self.layout)

    def show_table(self, c_datas):
        # 将数据显示到表格中
        for row_index, row_data in enumerate(c_datas):
            self.tableWidget.insertRow(row_index)
            checkbox = QCheckBox()
            self.checkbox_group.addButton(checkbox)  # 将复选框添加到单选按钮组

            self.tableWidget.setCellWidget(row_index, 0, checkbox)
            self.tableWidget.setItem(row_index, 1, QTableWidgetItem(str(row_data[0])))
            self.tableWidget.setItem(row_index, 2, QTableWidgetItem(row_data[1]))
            if row_data[2] == 0:
                action_type = "打开文件"
            elif row_data[2] == 1:
                action_type = "打开网址"
            elif row_data[2] == 2:
                action_type = "翻页控制"
            else:
                action_type = "窗口切换"
            self.tableWidget.setItem(row_index, 3, QTableWidgetItem(action_type))
            self.tableWidget.setItem(row_index, 4, QTableWidgetItem(row_data[3]))
            self.tableWidget.setItem(row_index, 5, QTableWidgetItem(row_data[4]))

    def add_instruction(self):
        dialog = AddInstructionDialog(None)
        if dialog.exec_() == QDialog.Accepted:
            instruction_data = dialog.get_instruction_data()
            # 在这里你应该将instruction_data修改到数据库并刷新表格
            db = DatabaseManager()
            db.insert_command(instruction_data["name"], instruction_data["type"], instruction_data["keyword"],
                              instruction_data["action"])
            c_datas = db.fetch_all_commands()
            db.__del__()
            # 先清空数据，再显示新数据
            self.tableWidget.setRowCount(0)
            self.show_table(c_datas)
            config.local_commands = c_datas

    def modify_instruction(self):
        """获取选中的行索引"""
        row_index = self.tableWidget.currentRow()
        if row_index == -1:  # 没有选中任何复选框
            return None

        # 获取选中行的数据
        data = {
            "name": self.tableWidget.item(row_index, 2).text(),
            "type": self.tableWidget.item(row_index, 3).text(),
            "keyword": self.tableWidget.item(row_index, 4).text(),
            "action": self.tableWidget.item(row_index, 5).text()
        }
        dialog = AddInstructionDialog(data)
        if dialog.exec_() == QDialog.Accepted:
            instruction_data = dialog.get_instruction_data()
            # 在这里你应该将instruction_data修改到数据库并刷新表格
            db = DatabaseManager()
            db.update_command(instruction_data["name"], instruction_data["type"], instruction_data["keyword"],
                              instruction_data["action"],
                              self.tableWidget.item(row_index, 1).text())
            c_datas = db.fetch_all_commands()
            db.__del__()
            # 先清空数据，再显示新数据
            self.tableWidget.setRowCount(0)
            self.show_table(c_datas)
            config.local_commands = c_datas

    def delete_instruction(self):
        """获取选中的行索引"""
        row_index = self.tableWidget.currentRow()
        if row_index == -1:  # 没有选中任何复选框
            return None

        db = DatabaseManager()
        db.delete_command(self.tableWidget.item(row_index, 1).text())
        c_datas = db.fetch_all_commands()
        db.__del__()
        # 先清空数据，再显示新数据
        self.tableWidget.setRowCount(0)
        self.show_table(c_datas)
        config.local_commands = c_datas
