import threading
import time
import os
import settings

from service.remove_bg_ali import RemoveBgALi
from service.generate_main_image.grenerate_main_image_test import (
    GeneratePic,
)
from service.generate_main_image.image_deal_base_func import *
from functools import partial
import io
from PIL import Image
from .base import check_path, get_date_time_original
from middleware import UnicornException

class OnePicTest():
    # is_end = Signal()

    def __init__(self,  pic_path="", is_auto_closed=False):
        # super().__init__()
        # 加载默认配置
        # self.ui = Ui_Form()
        # self.ui.setupUi(self)
        self.pic_path = pic_path
        self.is_auto_closed = False
        # self.init()
        # self.show()
        # if pic_path:
        #     self.run()

    def call_back_deal_image(self, data):
        # 处理后回调
        print(data)
        if data["code"] == 0:
            return data
        else:
            if data["message"]:
                raise UnicornException(data["message"])

    def deal_image(self, image_path):
        # 处理加工图片
        return_data = {"code": 99, "message": "", "data": {}}

        # =============清空temp文件夹================
        check_path("temp")
        check_path("temp\pic_test")
        root = r"{}\temp\pic_test".format(os.getcwd())
        try:
            for file_name in os.listdir(root):
                path = "{}\{}".format(root, file_name)
                if os.path.isfile(path):
                    os.remove(path)
        except Exception as e:
            print("deal_image", e)

        # ==============抠图处理=====================
        remove_pic_ins = RemoveBgALi()
        file = os.path.split(image_path)[1]
        cut_image_path = r"{}\temp\pic_test\{}.png".format(
            os.getcwd(), os.path.splitext(file)[0]
        ).replace("\\", "/")
        remove_pic_ins.get_image_cut(file_path=image_path, out_file_path=cut_image_path)

        # ==============生成主图====================
        main_out_path = r"{}\temp\pic_test\{}-主图.jpg".format(
            os.getcwd(), os.path.splitext(file)[0], 
        )
        print("image_path", image_path)
        print("cut_image_path", cut_image_path)
        print("main_out_path", main_out_path)
        # try:
        GeneratePic().run(
                    image_path=image_path,
                    cut_image_path=cut_image_path,
                    out_path=main_out_path,
                    image_deal_mode=1,
                    resize_mode=1,
                    out_pic_size=1024,
                    is_logo=False,
            )
        # except Exception as e:
        #     print(e)
        #     raise UnicornException("处理失败,请重试")

        # return_data["code"] = 0
        # return_data["data"]["image_path"] = image_path
        # return_data["data"]["image_cutout_path"] = cut_image_path
        # return_data["data"]["image_main_path"] = main_out_path
        return main_out_path

    def HandlerMainImage(self):
        # 先做整体校验
        if not os.path.exists(self.pic_path):
            raise UnicornException("图片不存在")
        image_pth = Image.open(self.pic_path)
        if image_pth.mode == "RGBA":
            raise UnicornException("抠图图片不能是PNG")
        return_data = self.deal_image(self.pic_path)
        # if return_data["message"]:
        #     raise UnicornException(return_data["message"])
        return return_data.replace("\\", "/")

if __name__ == "__main__":
    pic = OnePicTest(pic_path="C:/Users/15001/Desktop/mmexport1739929178317.jpg")
    pic.HandlerMainImage()
