import os.path
import time
from concurrent.futures import ThreadPoolExecutor, wait
import threading

from middleware import UnicornException

from .deal_one_image import DealOneImage, DealOneImageBeforehand
from logger import logger
from .online_request.module_online_data import GetOnlineDataHLM


class DealCutout():
    # signal_data = Signal(dict)

    def __init__(self, windows,token):
        super().__init__()
        self.windows = windows
        self.token = token
        self.lock = threading.Lock()
        self.need_cutout_images = {}
        self.state = 2  # 1进行中 2停止  状态 用于中途取消, 3已结束
        # 当前阿里预处理后的图片数量（未消费）
        self.is_upload_pic_num = 0
        self.is_deal_num = 0
        # 图片列表
        self.upload_pic_dict = {}
        self.logger = logger

        self.remaining_times = 0  # 剩余总次数
        self.get_online_data = GetOnlineDataHLM(token)

        self.resultData = [] # 最终的结果

    def refresh_times(self, is_online=True, remaining_times=None):
        # 刷新剩余次数
        if remaining_times is not None:
            self.remaining_times = remaining_times

        if is_online:
            _ = self.get_online_data.get_cutout_image_times()
            if _ is False:
                self.remaining_times = 0
            else:
                if "balance" in _:
                    self.remaining_times = _["balance"]

        if self.remaining_times <= 0:
            return False
        return True

    def send_sign(self, data):
        # show_info    complete
        self.signal_data.emit(data)

    def check_before(self):
        self.refresh_times()
        if self.remaining_times <= 0:
            # self.send_sign({"type": "show_info",
            #                 "message": "精细化抠图余量不足",
            #                 })
            raise UnicornException("精细化抠图余量不足")
        return True

    def run(self):
        """
        need_cutout_images 结构：
        [
        "file_name": file_name, # 文件名
        "file_e": file_e, # 后缀，.jpg
        "file_path": image_path, # 完整路径
        "file": file, # 图片文件名，带后缀
        "need_cutout": True,# 必须，需要抠图
        "out_path":图片输出路径
        ]
        """
        if not self.check_before():
            # self.signal_data.emit({"_type": "complete",
            #                        "data": []})
            self.state = 3
            return

        # executor = ThreadPoolExecutor(max_workers=4)
        # executor_pic_upload = ThreadPoolExecutor(max_workers=2)

        # tasks_1 = []
        # tasks_2 = []
        self.state = 1
        self.resultData = []
        self.is_upload_pic_num = 0
        self.is_deal_num = 0
        num = 0
        success_image_path = []
        for image_data in self.need_cutout_images:
            if not image_data["need_cutout"]:
                continue
            num += 1
            deal2 = DealOneImageBeforehand(
                image_data=image_data,
                lock=self.lock,
                windows=self,
                num=num,
                token=self.token,
            )
            res2 = deal2.run()
            try:
                image_path = res2
                if image_path:
                    if isinstance(image_path, str):
                        if os.path.exists(image_path):
                            success_image_path.append(image_path)
            except BaseException as e:
                self.logger.info("有线程出错：{}".format(e))
            deal1 = DealOneImage(
                image_data=image_data,
                lock=self.lock,
                windows=self,
                num=num,
                token=self.token,
            )
            res1 = deal1.run()
            # tasks_1.append(task_1)
            print("res1===>", res1)
            try:
                image_path = res1
                if image_path:
                    if isinstance(image_path, str):
                        if os.path.exists(image_path):
                            success_image_path.append(image_path)
            except BaseException as e:
                self.logger.info("有线程出错：{}".format(e))
        # self.check_thread(tasks_1, tasks_2)
        self.resultData = success_image_path
        self.state = 3
    def __del__(self):
        self.state = 2

    def check_thread(self, *tasks_list):
        time.sleep(2)
        success_image_path = []
        while 1:
            f = True
            for tasks in tasks_list:
                done, not_done = wait(tasks)
                if not_done:
                    time.sleep(2)
                    f = False
                    continue

                for task in done:
                    try:
                        image_path = task.result()
                        if image_path:
                            if isinstance(image_path, str):
                                if os.path.exists(image_path):
                                    success_image_path.append(image_path)
                    except BaseException as e:
                        self.logger.info("有线程出错：{}".format(e))
            if f:
                break

        # self.signal_data.emit({"_type": "complete",
        #                        "data": success_image_path})
        self.resultData = success_image_path
        self.state = 3
