try:from pymxs import runtime as rt 
except:pass
if (rt.maxversion())[7] < 2026:
    from PySide2 import QtWidgets, QtCore, QtGui
else:
    from PySide6 import QtWidgets, QtCore, QtGui
import os
import mimetypes
import http.client
from functools import partial


def encode(string):
    return string.encode("utf-8")

PREVIEW_NAMES1 = [  #sunucuya gonderilen isimler
    "main",
    "appearance",
    "structure",
    "linedrawing",
    "official",
    "hole_site"
]
PREVIEW_NAMES = [ # pencerede gorunen isimler
    "外观图",
    "外观尺寸图",
    "结构图",
    "结构尺寸图",
    "正视图",
    "孔位透视图"
]
MAX_BLUE = "#646464"

class ScaledLabel(QtWidgets.QLabel):
    def __init__(self):
        super().__init__()
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setStyleSheet("border: 1px solid gray; background-color: #eee")
        self._pixmap = None

    def setPixmap(self, pixmap):
        self._pixmap = pixmap
        self.updateScaled()

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.updateScaled()

    def updateScaled(self):
        if self._pixmap:
            scaled = self._pixmap.scaled(self.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
            super().setPixmap(scaled)
        else:
            super().setPixmap(QtGui.QPixmap())

class HoverListWidget(QtWidgets.QListWidget):
    hovered = QtCore.Signal(str)

    def __init__(self):
        super().__init__()
        self.setMouseTracking(True)

    def mouseMoveEvent(self, event):
        item = self.itemAt(event.pos())
        if item:
            self.hovered.emit(item.text())
        super().mouseMoveEvent(event)

class FileBrowserUI(QtWidgets.QWidget):
    def __init__(self):
        super(FileBrowserUI, self).__init__()
        self.setWindowTitle("Upload Product Images")
        self.setMinimumSize(1000, 700)
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)

        main_layout = QtWidgets.QVBoxLayout(self)

        top_splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)

        # Sol panel
        left_panel = QtWidgets.QWidget()
        left_layout = QtWidgets.QVBoxLayout(left_panel)

        self.select_folder_btn = QtWidgets.QPushButton("选择文件夹")
        self.select_folder_btn.clicked.connect(self.select_folder)
        left_layout.addWidget(self.select_folder_btn)
        yatayduzen = QtWidgets.QHBoxLayout(left_panel)
        left_layout.addLayout(yatayduzen)
        for i, name in enumerate(PREVIEW_NAMES):
            assign_btn = QtWidgets.QPushButton(name.upper())
            assign_btn.clicked.connect(partial(self.assign_preview_to_index, i))
            yatayduzen.addWidget(assign_btn)

        self.file_list = HoverListWidget()
        self.file_list.hovered.connect(self.show_hover_preview)
        left_layout.addWidget(self.file_list)
        #~ left_layout.addStretch()
        top_splitter.addWidget(left_panel)

        # Sag panel
        right_panel = QtWidgets.QWidget()
        right_layout = QtWidgets.QVBoxLayout(right_panel)

        grid_layout = QtWidgets.QGridLayout()
        self.preview_labels = []
        self.assign_buttons = []
        self.preview_titles = []

        for i, name in enumerate(PREVIEW_NAMES):
            container = QtWidgets.QVBoxLayout()

            title = QtWidgets.QLabel(name.upper())
            title.setAlignment(QtCore.Qt.AlignCenter)
            title.setStyleSheet("font-weight: bold;")
            title.setFixedHeight(20)
            
            image_label = ScaledLabel()
            image_label.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)

            assign_btn = QtWidgets.QPushButton("添加 / 删除")

            # assign_btn tiklandiginda resim varsa kaldirilir yoksa listedeki secili resim eklenir
            assign_btn.clicked.connect(partial(self.assign_or_clear_preview, i))

            container.addWidget(title)
            container.addWidget(image_label)
            container.addWidget(assign_btn)

            self.preview_labels.append(image_label)
            self.assign_buttons.append(assign_btn)
            self.preview_titles.append(title)  # title'lari da takip etmek icin
            grid_layout.addLayout(container, i // 2, i % 2)
            
            
        right_layout.addLayout(grid_layout)

        bottom_layout = QtWidgets.QHBoxLayout()
        product_label = QtWidgets.QLabel("  ID: ")
        product_label.setStyleSheet("font-weight: bold; font-size: 14px;")

        self.product_id_input = QtWidgets.QLineEdit()
        self.product_id_input.setValidator(QtGui.QIntValidator())
        self.product_id_input.setStyleSheet("padding: 6px; font-size: 14px;")

        self.upload_button = QtWidgets.QPushButton("上传")

        self.upload_button.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
        self.upload_button.setFixedHeight(50)
       
        self.upload_button.clicked.connect(self.upload_all_previews)
    
        bottom_layout.addWidget(product_label)
        bottom_layout.addWidget(self.product_id_input)
        bottom_layout.addWidget(self.upload_button)

        right_layout.addLayout(bottom_layout)

        self.progress_bar = QtWidgets.QProgressBar()
        right_layout.addWidget(self.progress_bar)

        top_splitter.addWidget(right_panel)
        left_panel.setMinimumWidth(200)
        right_panel.setMinimumWidth(200)
        main_layout.addWidget(top_splitter)
        self.file_list.itemDoubleClicked.connect(self.assign_preview_from_double_click)
        
        top_splitter.setSizes([1,1])

    def select_folder(self):
        folder = QtWidgets.QFileDialog.getExistingDirectory(self, "选择文件夹")
        if folder:
            self.file_list.clear()
            for file_name in os.listdir(folder):
                if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
                    self.file_list.addItem(os.path.join(folder, file_name))

    def assign_preview_to_index(self, index):
        selected_items = self.file_list.selectedItems()
        if not selected_items:
            QtWidgets.QMessageBox.warning(self, "警告", "请从列表中选择一张图片。")
            return
        image_path = selected_items[0].text()
        pixmap = QtGui.QPixmap(image_path)
        label = self.preview_labels[index]
        label.setPixmap(pixmap)
        label.setProperty("image_path", image_path)
        self.preview_titles[index].setText(PREVIEW_NAMES[index].upper())  # Tik veya carpi sifirlanir
    def assign_or_clear_preview(self, index):
        label = self.preview_labels[index]
        btn = self.assign_buttons[index]

        # Eger onizlemede resim varsa kaldir
        if label.property("image_path"):
            label.setPixmap(QtGui.QPixmap())  # resmi temizle
            label.setProperty("image_path", None)
            btn.setText("从列表中选择")
            self.preview_titles[index].setText(PREVIEW_NAMES[index].upper())  # Basligi varsayilan yap
        else:
            # Resim yoksa listeden secme fonksiyonunu cagir (mevcut assign_preview_to_index ile ayni islev)
            self.assign_preview_to_index(index)

    def update_assign_buttons_text(self):
        # Butonlarin metinlerini onizleme durumuna gore gunceller
        for i, label in enumerate(self.preview_labels):
            btn = self.assign_buttons[i]
            if label.property("image_path"):
                btn.setText("消除")
            else:
                btn.setText("从列表中选择")
    def show_hover_preview(self, image_path):
        pixmap = QtGui.QPixmap(image_path)
        if not pixmap.isNull():
            for label in self.preview_labels:
                if not label.property("image_path"):
                    label.setPixmap(pixmap)
                    break
    def assign_preview_from_double_click(self, item):
        image_path = item.text()
        pixmap = QtGui.QPixmap(image_path)
        if pixmap.isNull():
            QtWidgets.QMessageBox.warning(self, "文件损坏","无法加载图像。")
            return

        for i, label in enumerate(self.preview_labels):
            if not label.property("image_path"):
                label.setPixmap(pixmap)
                label.setProperty("image_path", image_path)
                self.preview_titles[i].setText(PREVIEW_NAMES[i].upper())  # onceki isaretleri sil
                break

    def upload_all_previews(self):
        product_id = self.product_id_input.text().strip()
        if not product_id:
            QtWidgets.QMessageBox.warning(self, "警告", "请输入产品编号。")
            return

        total = len(PREVIEW_NAMES)
        completed_count = 0

        for i, label in enumerate(self.preview_labels):
            image_path = label.property("image_path")
            preview_name = PREVIEW_NAMES1[i]

            if not image_path or not os.path.isfile(image_path):
                self.update_title_label_status(i, None)
                continue

            try:
                response = self.upload_single_image(image_path, preview_name, product_id)
                if response == True:
                    self.update_title_label_status(i, True)
                else:
                    self.update_title_label_status(i, False)
                completed_count += 1
                self.progress_bar.setValue(int((completed_count / total) * 100))
                QtWidgets.QApplication.processEvents()
            except Exception as e:
                self.update_title_label_status(i, False)
                QtWidgets.QMessageBox.critical(self, "Hata", f"{preview_name} yuklenirken hata:\n{str(e)}")

        QtWidgets.QMessageBox.information(self, "完成","安装过程已完成。")
        self.progress_bar.setValue(100)
        for i, label in enumerate(self.preview_labels):
            self.update_title_label_status(i, None)
        self.progress_bar.setValue(0)

    def upload_single_image(self, file_path, preview, product_id):
        conn = http.client.HTTPSConnection("shu.yesno.vip")
        boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
        dataList = []

        dataList.append(encode('--' + boundary))
        dataList.append(encode(f'Content-Disposition: form-data; name="file"; filename="{os.path.basename(file_path)}"'))
        fileType = mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
        dataList.append(encode(f'Content-Type: {fileType}'))
        dataList.append(encode(''))
        with open(file_path, 'rb') as f:
            dataList.append(f.read())

        dataList.append(encode('--' + boundary))
        dataList.append(encode('Content-Disposition: form-data; name="type"'))
        dataList.append(encode('Content-Type: text/plain'))
        dataList.append(encode(''))
        dataList.append(encode(preview))

        dataList.append(encode('--' + boundary))
        dataList.append(encode('Content-Disposition: form-data; name="product_id"'))
        dataList.append(encode('Content-Type: text/plain'))
        dataList.append(encode(''))
        dataList.append(encode(product_id))

        dataList.append(encode('--' + boundary + '--'))
        dataList.append(encode(''))

        body = b'\r\n'.join(dataList)
        headers = {'Content-type': f'multipart/form-data; boundary={boundary}'}

        conn.request("POST", "/api/jiaju/porduct-image-upload", body, headers)
        res = conn.getresponse()
        data = res.read()
        text = data.decode('utf-8')
        #~ print(f"{preview} -> {res.status}: {text}")
        return text[:9] == '{"code":0' #sunucudan donen verinin ilk 9 harfine gore sonuc tespiti yap
            
    def update_title_label_status(self, index, success):
        name = PREVIEW_NAMES[index].upper()
        if success is None:
            self.preview_titles[index].setText(name)
        elif success is True:
            self.preview_titles[index].setText(f"{name} - OK")
        else:
            self.preview_titles[index].setText(f"{name} - ERROR")
       
if __name__ == "__main__":
    file_browser_window = FileBrowserUI()
    app = QtWidgets.QApplication.instance()
    screen = app.primaryScreen()
    size = screen.size() # masaustu ekran cozunurlugu
    file_browser_window.resize(size.width()/2,size.height()/1.5)
    file_browser_window.show()
