import sys
import os
import subprocess
import pyperclip
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QMenu, QAction, \
    QLineEdit, QHeaderView
from PyQt5.QtCore import Qt
from win import EverythingApi


class ResultWindow(QWidget):
    def __init__(self, data):
        super().__init__()
        self.title = "搜索结果"
        self.left = 200
        self.top = 200
        self.width = 980
        self.height = 800

        self.data = data
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # 创建搜索框
        self.searchInput = QLineEdit(self)
        self.searchInput.setPlaceholderText("Search...")
        self.searchInput.returnPressed.connect(self.searchFiles)

        # 创建表格
        self.createTable()

        # 设置窗口的布局
        layout = QVBoxLayout()
        layout.addWidget(self.searchInput)
        layout.addWidget(self.tableWidget)
        self.setLayout(layout)

        # 显示窗口
        # self.show()

    def createTable(self):
        # 创建一个QTableWidget
        self.tableWidget = QTableWidget()

        # 设置列数
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setHorizontalHeaderLabels(["名称", "路径", "大小", "修改时间"])

        # 添加数据到表格
        self.tableWidget.setRowCount(len(self.data))
        for row_index, row_data in enumerate(self.data):
            self.tableWidget.setItem(row_index, 0, QTableWidgetItem(row_data['file_name']))
            self.tableWidget.setItem(row_index, 1, QTableWidgetItem(row_data['file_path']))
            self.tableWidget.setItem(row_index, 2, QTableWidgetItem(row_data['file_size']))
            self.tableWidget.setItem(row_index, 3, QTableWidgetItem(row_data['modified_time']))

        # 设置列宽比例
        total_width = self.width
        self.tableWidget.setColumnWidth(0, int(total_width * 0.30))  # 30% for File Name
        self.tableWidget.setColumnWidth(1, int(total_width * 0.35))  # 35% for Path
        self.tableWidget.setColumnWidth(2, int(total_width * 0.10))  # 15% for Size
        self.tableWidget.setColumnWidth(3, int(total_width * 0.25))  # 20% for Modified Time

        # 设置列宽为用户可调整
        header = self.tableWidget.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Interactive)
        header.setSectionResizeMode(3, QHeaderView.Stretch)

        # 允许排序并设置默认不排序
        self.tableWidget.setSortingEnabled(True)
        self.tableWidget.sortByColumn(-1, Qt.AscendingOrder)  # 初始化时不排序任何列

        # 为表格添加右键菜单支持
        self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tableWidget.customContextMenuRequested.connect(self.showContextMenu)

    def showContextMenu(self, pos):
        contextMenu = QMenu(self)
        openFileAction = QAction("打开文件", self)
        openPathAction = QAction("打开文件路径", self)
        copyPathAction = QAction("复制文件路径和名称", self)
        contextMenu.addAction(openFileAction)
        contextMenu.addAction(openPathAction)
        contextMenu.addAction(copyPathAction)
        action = contextMenu.exec_(self.mapToGlobal(pos))

        if action == openFileAction:
            self.openFile()
        elif action == openPathAction:
            self.openPath()
        elif action == copyPathAction:
            self.copyPathAndFilename()

    def openFile(self):
        row = self.tableWidget.currentRow()
        if row >= 0:
            path = os.path.join(self.tableWidget.item(row, 1).text(), self.tableWidget.item(row, 0).text())
            subprocess.Popen(['explorer', path])

    def openPath(self):
        row = self.tableWidget.currentRow()
        if row >= 0:
            path = self.tableWidget.item(row, 1).text()
            subprocess.Popen(['explorer', '/select,', path])

    def copyPathAndFilename(self):
        row = self.tableWidget.currentRow()
        if row >= 0:
            full_path = os.path.join(self.tableWidget.item(row, 1).text(), self.tableWidget.item(row, 0).text())
            pyperclip.copy(full_path)

    def searchFiles(self):
        search_text = self.searchInput.text().strip()
        if search_text:  # 确保搜索框不为空
            # 使用Everything API进行搜索
            e_api = EverythingApi.Everything()
            new_data = e_api.searchfile(search_text)
            self.updateTable(new_data)

    def searchIatFiles(self, search_text):
        if search_text:  # 确保搜索框不为空
            self.searchInput.setText(search_text)
            # 使用Everything API进行搜索
            e_api = EverythingApi.Everything()
            new_data = e_api.searchfile(search_text)
            self.updateTable(new_data)

    def updateTable(self, data):
        self.tableWidget.setRowCount(len(data))
        for row_index, row_data in enumerate(data):
            self.tableWidget.setItem(row_index, 0, QTableWidgetItem(row_data['file_name']))
            self.tableWidget.setItem(row_index, 1, QTableWidgetItem(row_data['file_path']))
            self.tableWidget.setItem(row_index, 2, QTableWidgetItem(row_data['file_size']))
            self.tableWidget.setItem(row_index, 3, QTableWidgetItem(row_data['modified_time']))

        self.tableWidget.sortByColumn(-1, Qt.AscendingOrder)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    data = []  # Placeholder for data
    ex = ResultWindow(data)
    ex.show()
    sys.exit(app.exec_())
