# from import_qt_mode import *
# from UI.auto_deal_pics_ui.temp_item import Ui_Form as UI_temp_item
import os
from PIL import Image
import threading
from io import BytesIO


# 详情itme模板组件
class TempItem():
    # select_sign = Signal(str)

    def __init__(self, parent, _id, image_path):
        super().__init__(parent)
        # self.ui = UI_temp_item()
        # self.ui.setupUi(self)
        self.temp_name = _id
        self.image_path = image_path
        self.id = _id
        self.is_select = False
        self.init()
        # self.show()

    def init(self):
        # self.ui.label.mousePressEvent = self.pic_show
        # self.ui.radioButton.clicked.connect(self.select)
        self.set_label_image()
        # self.label_temp_name = QLabel(self)
        # self.label_temp_name.setText(str(self.temp_name))
        # self.label_temp_name.move(5, self.height() - self.label_temp_name.height())

    def cancel_select(self, *args):
        self.is_select = False
        # self.ui.radioButton.setChecked(False)

    def select(self, *args):
        self.is_select = True
        # self.ui.radioButton.setChecked(True)
        # self.select_sign.emit(self.id)

    def pic_show(self, *args, **kwargs):
        if os.path.exists(self.image_path):
            im = Image.open(self.image_path)
            threading.Thread(target=im.show, args=()).start()

    def set_label_image(self):
        if not os.path.exists(self.image_path):
            return
        # try:
        #     bytes_io = BytesIO()
        #     w, h = self.ui.image_show.width(), self.ui.image_show.height()
        #     _img_raw = Image.open(self.image_path)
        #     _img_raw = self.to_resize(_img_raw, width=w * 2)
        #     _img_raw = _img_raw.crop(box=(0, 0, w * 2, h * 2))
        #     # _img_raw.thumbnail((w * 2, int(_img_raw.height * w * 2 / _img_raw.width)))
        #     # img_raw = _img_raw.resize(size=(w, h))
        #     _img_raw.save(bytes_io, "JPEG")
        #     icon = QPixmap()
        #     # icon.loadFromData(img)
        #     icon.loadFromData(bytes_io.getvalue())
        #     icon = icon.scaled(
        #         self.ui.image_show.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation
        #     )
        #     self.ui.image_show.setPixmap(icon)
        #     # self.mousePressEvent = lambda x: self.show_one_data(row)
        # except:
        pass

    def to_resize(self, _im, width=None, high=None):
        _im_x, _im_y = _im.size
        if width and high:
            if _im_x >= _im_y:
                high = None
            else:
                width = None
        if width:
            re_x = int(width)
            re_y = int(_im_y * re_x / _im_x)
        else:
            re_y = int(high)
            re_x = int(_im_x * re_y / _im_y)
        _im = _im.resize((re_x, re_y))
        return _im

