# from UI.generate_goods_art_no_table.generate_goods_art_no_table_ui import (
#     Ui_Form as generate_goods_art_no_table_Ui_Form,
# )
# from import_qt_mode import *
import os
import time
import threading
import xlsxwriter
import shutil
from ..pic_deal import Picture
from PIL import Image
# from module.view_control.MineQWidget import MineQWidget
# from module.base_mode.excel_base_func import *


class GenerateGoodsArtNoTable():
    # 货号表生成
    # progress_sign = Signal(dict)
    # info_sign = Signal(str)

    def __init__(self):
        super().__init__()
        self.is_del = False
        self.setupUi(self)
        # 0禁用  1进行中  2已结束
        self.state = 2
        self.init()
        self.show()

    def init(self):
        self.label_4.setText("请选择需要生成货号表的文件夹路径")
        self.label_3.setText("请选择目录")
        self.label_3.mousePressEvent = self.get_img_dir
        self.textBrowser_2.hide()

        self.progressBar.setValue(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.progressBar.hide()
        self.label_5.setText("")

        self.progress_sign.connect(self.show_progress)
        self.pushButton.clicked.connect(self.run)
        self.textBrowser_2.hide()

    def get_img_dir(self, *args):
        folder = QFileDialog.getExistingDirectory(self, "选取文件夹", "./")
        self.label_4.setText(folder)

    def show_progress(self, data):
        progress_bar_value = data["progress_bar_value"]
        self.label_5.setText(data["type"])
        self.progressBar.setValue(progress_bar_value)
        pass

    def check(self):
        _path = self.image_dir + "/历史"
        if not os.path.exists(_path):
            os.mkdir(_path)
        return True

    def set_state(self, state_value: int):
        # 0禁用  1进行中  2已结束
        if state_value not in [0, 1, 2]:
            return
        self.state = state_value
        if self.state == 0:
            self.pushButton.setText("执行中")
            self.pushButton.setEnabled(False)
        if self.state == 1:
            self.progressBar.show()
            self.textBrowser_2.show()
            self.pushButton.setText("执行中")
            self.pushButton.setEnabled(False)
            self.textBrowser_2.clear()
        if self.state == 2:
            self.pushButton.setText("执行完毕")
            self.pushButton.setEnabled(True)
            self.progressBar.hide()

    def run(self):
        self.set_state(state_value=1)
        self.t = threading.Thread(target=self.run_by_thread, args=())
        self.t.start()

    def show_progress_detail(self, text):
        self.textBrowser_2.append(text)

    def run_by_thread(self, dir_path=None):
        if not dir_path:
            dir_path = self.label_4.text()
        if not dir_path:
            self.show_progress_detail("请选择文件夹")
            self.set_state(state_value=2)
            return

        if not os.path.exists(dir_path):
            self.show_progress_detail("该文件夹不存在")
            self.set_state(state_value=2)
            return
        GenerateGoodsArtNoTable.deal(dir_path)
        # 完成处理
        self.set_state(state_value=2)

    def save_as_excel(self, out_excel_data, out_excel_path=None):
        self.show_progress_detail("开始尝试导出Excel文件~~~~")

        def close_book(_book):
            try:
                _book.close()
            except BaseException as e:
                print(e)
                self.show_progress_detail("请先关闭文件:{}".format(out_excel_path))
                return False
            return True

        options = {
            "default_format_properties": {
                "align": "left",
                "valign": "vcenter",
                "text_wrap": True,
            }
        }
        book = xlsxwriter.Workbook(filename=out_excel_path, options=options)
        sheet = book.add_worksheet("sheet1")
        # sheet.freeze_panes(1, 2)
        sheet.set_column("B:B", 17)

        sheet.write_row("A1", ["货号", "缩略图"])
        for index, data in enumerate(out_excel_data):
            # print(data)
            goods_no, image_file = data
            try:
                im = Image.open(image_file)
                im_x, im_y = im.size
                image_width = 100
                image_height = int(im_y * image_width / im_x)
                sheet.set_row(index + 1, 95)
                x_scale = round(image_width / im_x, 2)  # 固定宽度/要插入的原始图片宽
                y_scale = round(image_height / im_y, 2)  # 固定高度/要插入的原始图片高

                sheet.insert_image(
                    index + 1,
                    1,
                    image_file,
                    {
                        "x_scale": x_scale,
                        "y_scale": y_scale,
                        "x_offset": 5,
                        "y_offset": 5,
                    },
                )
            except:
                self.show_progress_detail("图片异常，{}".format(image_file))
                pass
            sheet.write_row("A{}".format(index + 2), [goods_no])

        close_book(book)
        self.show_progress_detail("已保存文件至：{}".format(out_excel_path))
        # while 1:
        #     if self.is_del:
        #         break
        #
        #     if not close_book(book):
        #         time.sleep(1)
        #         self.show_progress_detail("请先关闭文件:{}".format(out_excel_path))
        #     else:
        #         self.show_progress_detail("已保存文件至：{}".format(out_excel_path))
        #         break

    @classmethod
    def deal(cls, dir_path):
        def close_book(_book):
            try:
                _book.close()
            except BaseException as e:
                print(e)
                return False
            return True

        # print("dir_path", dir_path)
        out_excel_data = []
        for goods_art_no_folder in os.listdir(dir_path):  # 遍历货号文件夹集合
            if not os.path.isdir(
                "{}/{}".format(dir_path, goods_art_no_folder)
            ):  # 非文件夹进行过滤
                continue
            if "软件" in goods_art_no_folder:
                continue

            # print("goods_art_no_folder", goods_art_no_folder)
            # 如果存在800的主图，则优先进行使用
            big_image_folder_path = "{}/{}/800x800".format(
                dir_path, goods_art_no_folder
            )
            if not os.path.exists(big_image_folder_path):
                os.mkdir(big_image_folder_path)
            all_big_images = os.listdir(big_image_folder_path)
            goods_pic_total = len(all_big_images)
            _Type = [".png", ".PNG", ".jpg", ".JPG", ".gif", ".GIF", ".jpge", ".JPGE"]
            thumb_image_file_path = None
            # print("all_big_images",all_big_images)
            if all_big_images:
                for _file in all_big_images:
                    # print(_file)
                    file_name, e = os.path.splitext(_file)
                    # print(file_name, e)
                    if e in _Type:
                        thumb_image_file_path = "{}/{}/800x800/{}".format(
                            dir_path, goods_art_no_folder, _file
                        )
                        break

            # 如果不存在主图则进行使用原始图
            if thumb_image_file_path is None:
                _path = "{}/{}/原始图".format(dir_path, goods_art_no_folder)
                if not os.path.exists(_path):
                    continue

                all_original_images = os.listdir(_path)  # 遍历货号原始图文件夹
                goods_pic_total = len(all_original_images)
                if not all_original_images:
                    continue
                image_file = all_original_images[0]  # 取第一个货号图
                image_file_path = "{}/{}/原始图/{}".format(
                    dir_path, goods_art_no_folder, image_file
                )

                if not os.path.exists(
                    "{}/{}/200images".format(dir_path, goods_art_no_folder)
                ):
                    os.mkdir("{}/{}/200images".format(dir_path, goods_art_no_folder))

                thumb_image_file_path = "{}/{}/200images/{}".format(
                    dir_path, goods_art_no_folder, image_file
                )
                if not os.path.exists(thumb_image_file_path):
                    # 开始触发进行压缩生成文件
                    shutil.copy(image_file_path, thumb_image_file_path)  # 复制文件
                    pic = Picture(thumb_image_file_path)
                    pic.resize(width=600)
                    pic.save_img(thumb_image_file_path)
            # print("thumb_image_file_path", thumb_image_file_path)

            goods_number = ""
            if "@" in goods_art_no_folder:
                _ = goods_art_no_folder.split("@")
                goods_art_no_folder = _[0]
                goods_number = _[1].replace("NUM", "")

            out_excel_data.append(
                [
                    goods_number,
                    goods_art_no_folder,
                    thumb_image_file_path,
                    goods_pic_total,
                ]
            )

        if out_excel_data:
            out_excel_path = "{}/货号表-{}.xlsx".format(dir_path, time.time())
            options = {
                "default_format_properties": {
                    "align": "left",
                    "valign": "vcenter",
                    "text_wrap": True,
                }
            }
            book = xlsxwriter.Workbook(filename=out_excel_path, options=options)
            sheet = book.add_worksheet("sheet1")
            # sheet.freeze_panes(1, 2)
            sheet.set_column("B:B", 17)
            sheet.set_column("D:D", 20)

            sheet.write_row("A1", ["编号", "原货号", "新货号", "缩略图", "原始图张数"])
            for index, data in enumerate(out_excel_data):
                # print(data)
                goods_number, goods_art_no, image_file, goods_pic_total = data
                try:
                    im = Image.open(image_file)
                    im_x, im_y = im.size
                    image_width = 100
                    image_height = int(im_y * image_width / im_x)
                    sheet.set_row(index + 1, 95)
                    x_scale = round(
                        image_width / im_x, 2
                    )  # 固定宽度/要插入的原始图片宽
                    y_scale = round(
                        image_height / im_y, 2
                    )  # 固定高度/要插入的原始图片高
                    sheet.insert_image(
                        index + 1,
                        3,
                        image_file,
                        {
                            "x_scale": x_scale,
                            "y_scale": y_scale,
                            "x_offset": 5,
                            "y_offset": 5,
                            "object_position":1,
                        },
                    )


                except:
                    pass
                sheet.write_row("A{}".format(index + 2), [goods_number])
                sheet.write_row("B{}".format(index + 2), [goods_art_no])
                sheet.write_row("E{}".format(index + 2), [goods_pic_total])
            close_book(book)

    def __del__(self):
        self.is_del = True
