import datetime
import logging
import tkinter as tk
from tkinter import ttk

from tornado import concurrent

from control.base.base_control import BaseControl, UIControl


def loading(top, func):
    """
    等待加载完成
    :return:
    """
    # 创建加载指示器
    loading_window = tk.Toplevel(top)
    loading_window.title("连接中")
    loading_window.geometry("200x100")
    loading_window.transient(top)  # 设置为模态
    loading_window.grab_set()  # 设置为模态
    loading_window.overrideredirect(True)  # 移除窗口边框和按钮
    # 相对于父窗口居中显示
    window_width = loading_window.winfo_reqwidth()
    window_height = loading_window.winfo_reqheight()
    parent_x = top.winfo_rootx()
    parent_y = top.winfo_rooty()
    parent_width = top.winfo_width()
    parent_height = top.winfo_height()
    position_right = parent_x + (parent_width - window_width) // 2
    position_down = parent_y + (parent_height - window_height) // 2
    loading_window.geometry(f"+{position_right}+{position_down}")
    loading_label = ttk.Label(loading_window, text="连接中...", padding=20)
    loading_label.pack(expand=True)

    def thread_task():
        try:
            func()
        finally:
            # 在主线程中销毁加载指示器
            top.after(0, lambda: [loading_window.grab_release(), loading_window.destroy()])

    import threading
    thread = threading.Thread(target=thread_task)
    # thread.daemon = True  # 设置为守护线程，这样主程序退出时线程会自动结束
    thread.start()
    pass


class ControlUtils(UIControl):

    # def parallel_process_list(data):
    #     """并行处理列表数据"""
    #     results = []
    #     with concurrent.futures.ProcessPoolExecutor() as executor:
    #         # 使用 map 函数将处理函数应用到列表的每个元素
    #         # executor.map 返回一个迭代器，包含处理结果
    #         for result in executor.map(process_item, data):
    #             results.append(result)
    #     return results

    def __init__(self, **kwargs):
        self.top = kwargs.get('top', None)
        pass

    def event_1(self, **kwargs):
        logging.info('执行event1')
        log = kwargs.get('log')
        log.delete("1.0", tk.END)

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行1=event1=>{k},{v}')
                v['control'].event_1(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_2(self, **kwargs):
        """
              点击全部的 event2
              :return:
              """
        logging.info('执行event2')

        log = kwargs.get('log')
        log.delete("1.0", tk.END)
        kwargs['action'] = '开仓:买入/开多'

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                log.see(tk.END)
                v['control'].event_2(**kwargs)
                v['control'].event_10(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)
        pass

    def event_3(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event3=>{k},{v}')
                v['control'].event_3(**kwargs)

                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_4(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)
        kwargs['action'] = '平仓:卖出/平多'

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event4=>{k},{v}')
                v['control'].event_4(**kwargs)
                v['control'].event_10(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_5(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event5=>{k},{v}')
                v['control'].event_5(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_6(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)
        kwargs['action'] = '开仓:卖出/开空'

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event6=>{k},{v}')
                v['control'].event_6(**kwargs)
                v['control'].event_10(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_7(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event7=>{k},{v}')
                v['control'].event_7(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_8(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)
        kwargs['action'] = '平仓:买入/平空'

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event8=>{k},{v}')
                v['control'].event_8(**kwargs)
                v['control'].event_10(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_9(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event9=>{k},{v}')
                v['control'].event_9(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_10(self, **kwargs):
        log = kwargs.get('log')
        log.delete("1.0", tk.END)
        kwargs['action'] = '查看结果'

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event10=>{k},{v}')
                v['control'].event_10(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def event_11(self, **kwargs):
        """
        一键全平
        :param kwargs:
        :return:
        """
        log = kwargs.get('log')
        log.delete("1.0", tk.END)
        kwargs['action'] = '一键全平'

        def process_item(item):
            k, v = item
            try:
                # 确保子进程中的日志配置
                logging.basicConfig(level=logging.INFO)
                logging.info(f'执行=event11=>{k},{v}')
                v['control'].event_11(**kwargs)
                v['control'].event_10(**kwargs)
                return True
            except Exception as e:
                logging.error(f"处理元素 {k} 时发生错误: {e}")
            return False

        self._event(process_item, **kwargs)

    def _event(self, process_item, **kwargs):
        log = kwargs.get('log')

        def func():
            with concurrent.futures.ThreadPoolExecutor() as executor:
                futures = []
                for item in BaseControl.connect_dict.items():
                    logging.info(f'执行=event=>{item}')
                    future = executor.submit(process_item, item)
                    futures.append(future)
                    k, v = item
                    # 获取当前日期和时间
                    now = datetime.datetime.now()
                    # 格式化日期和时间为 "年月日-月月-日日 时时:分分:秒秒"
                    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
                    log.insert(tk.INSERT, f"======下发命令============\n"
                                          f"手机:{v['name']}\n"
                                          f"操作:{kwargs['action']}\n"
                                          f"时间:{formatted_time}\n"
                                          f"===========================\n")

                for future in concurrent.futures.as_completed(futures):
                    try:
                        result = future.result()
                        logging.info(f"任务完成状态: {result}")
                    except Exception as e:
                        logging.error(f"任务执行出错: {e}")

        loading(self.top, func)

        pass
