from copy import deepcopy
from datetime import datetime

from mower.data import agent_list
from mower.solvers.infra.base_mixin import BaseMixin
from mower.solvers.infra.enter_room import EnterRoomSolver
from mower.solvers.infra.filter import RIIC_Filter
from mower.solvers.infra.riic_free_fill import RIIC_FreeFillSolver
from mower.solvers.infra.riic_tag_choose import RIICTagChoose
from mower.utils import config
from mower.utils.character_recognize import operator_room_select
from mower.utils.graph.utils import SceneGraphSolver
from mower.utils.image import cropimg, diff_ratio
from mower.utils.log import logger
from mower.utils.scene import Scene


class RIIC_ChooseSolver(SceneGraphSolver, BaseMixin):
    solver_name = "基建选人"

    def run(self, room: str, agents: list, wait_time: float = 0) -> bool:
        """
        Args:
            room (str): 房间
            agents (list): 选人名单
            wait_time (float, optional): 选人完成到按确定的时间
        """
        logger.info(f"安排干员：{agents}")
        self.agents = agents
        self.room = room
        self.wait_time = wait_time

        self.success = False
        self.agents_copy = deepcopy(agents)
        self.clean = False
        self.filter = False
        self.agent = None
        self.tmp_left = None

        self.start_time = datetime.now()
        self.tap_time = datetime.now()
        self.tmp_swipe = None

        self.recog_agents = None
        self.before = None
        self.solver_update_before_transition = True
        self.choosed = []

        logger.debug(f"待选名单:{self.agents}")

        super().run()  # 不一定选完，但一定结束流程了

        return len(self.choosed) == self.agents

    @property
    def interval(self):
        return config.screenshot_avg / 1000  # 截图延迟

    def choose_agents(self):
        if self.agent is None:
            if len(self.agents_copy) > 0:
                """
                self.agent =[干员名,是否选过tag,是否左滑过]
                """
                self.agent = [self.agents_copy.pop(0), False, False]
                logger.info(f"开始选择干员：{self.agent[0]}")
            else:
                if self.wait_time > 0:
                    self.sleep(self.check_wait_time())
                self.success = True
                if pos := self.find("confirm_blue"):
                    self.tap(pos)
                return
        if self.before is not None:
            self.sleep(0.1)
            if diff_ratio(self.before, config.recog.gray):
                logger.debug("滑动还在继续")
                self.before = config.recog.gray
                self.recog_agents = None
                return
            self.before = None

        if self.recog_agents is None:
            self.recog_agents = dict(operator_room_select(config.recog.img))

        if len(self.agents) > 1:
            for i in self.recog_agents:
                if (
                    self.is_choosed(self.recog_agents[i])
                    and self.recog_agents[i][0][0] < 1600
                ):
                    if i not in self.agents and i not in self.choosed:
                        logger.info(f"存在错选 {i}")
                        self.tap("choose_agent/clear", interval=self.interval)
                        self.agents_copy = deepcopy(self.agents)
                        self.choosed = []
                        self.recog_agents = None
                        self.agent = None
                        return

        agent_name = self.agent[0]

        if agent_name == "Free":
            self.choosed.append(RIIC_FreeFillSolver().run())
            self.agent = None
            return

        if agent_name in self.recog_agents.keys():
            is_choosed = self.is_choosed(self.recog_agents[agent_name])
            if is_choosed:
                logger.info(f"{agent_name}选择完成")
                self.recog_agents = None
                self.choosed.append(agent_name)
                self.agent = None
            else:
                if self.recog_agents[agent_name][0][0] > 1650:
                    logger.debug(f"滑动调整位置 {self.recog_agents[agent_name]}")
                    self.swipe_update(
                        [(700, 770), (400, 770), (400, 500)],
                        [200, 200],
                        up_wait=200,
                        interval=0.2,
                    )
                    self.recog_agents = None
                    return

                logger.debug(f"tap {agent_name} ")
                self.ctap(self.recog_agents[agent_name], 5, self.interval, agent_name)
            self.recog_agents = None
            return

        logger.debug(f"选tag和左滑 {self.agent}")
        if self.agent[1] is False:
            tag = agent_list[agent_name]["profession"]
            if agent_name == "阿米娅":
                tag = "ALL"

            if RIICTagChoose().run(tag):
                self.agent[1] = True
                self.recog_agents = None
            return
        if self.agent[2] is False:
            tmp_recog = self.swipe_update(
                [(700, 770), (1600, 770), (1600, 500)],
                [200, 200],
                up_wait=200,
                interval=0.2,
                func=operator_room_select,
            )
            if tmp_recog[0][0] == list(self.recog_agents.keys())[0]:
                self.agent[2] = True
            self.recog_agents = None
            return

        # 右滑
        self.recog_agents = dict(
            self.swipe_update(
                [(1600, 770), (600, 770), (600, 900)],
                [300, 500],
                up_wait=200,
                interval=0.2,
                func=operator_room_select,
            )
        )
        tmp_img = config.recog.gray
        config.recog.update()
        if diff_ratio(tmp_img, config.recog.gray):
            if agent_name not in self.recog_agents.keys():
                logger.info(f"缺少：{agent_name}")
                return True

        self.before = config.recog.gray

    def is_choosed(self, scope) -> bool:
        # logger.info(scope)
        up_pt = cropimg(
            config.recog.img,
            [
                [scope[0][0] + 0, scope[0][1] - 128],
                [scope[0][0] + 1, scope[0][1] - 127],
            ],
        )[0][0][0]

        down_pt = cropimg(
            config.recog.img,
            [
                [scope[0][0] + 0, scope[1][1] + 212],
                [scope[0][0] + 1, scope[1][1] + 213],
            ],
        )[0][0][0]

        logger.debug(f"is_choosed: {up_pt},{down_pt}")
        if up_pt < 50 and down_pt < 50:
            return True
        return False

    def check_wait_time(self) -> float:
        return max(
            self.wait_time - (datetime.now() - self.start_time).total_seconds(), 0
        )

    def transition(self) -> bool:
        if (datetime.now() - self.tap_time).total_seconds() > 300:
            EnterRoomSolver().run(self.room)
            return True
        if (scene := self.scene()) == Scene.RIIC_OPERATOR_SELECT:
            if pos := self.find("choose_agent/open_profession"):
                self.ctap(pos, interval=self.interval)
                return
            if self.filter is False:
                if RIIC_Filter().run("技能", ascending=False):
                    self.filter = True
            if self.clean is False and len(self.agents) > 1:
                agents_dict = dict(operator_room_select(config.recog.img))
                for i in agents_dict:
                    if self.is_choosed(agents_dict[i]):
                        logger.debug(f"开始选人前先清空干员 {i}")
                        self.tap("choose_agent/clear", interval=self.interval)
                        return
                self.clean = True

            return self.choose_agents()

        elif self.find("room_detail") and self.detect_room() == self.room:
            if self.success:
                return True
            else:
                self.ctap((1400, 200))
        elif (
            scene in [Scene.ORDER_LIST, Scene.FACTORY_ROOMS]
            and self.detect_room_inside() == self.room
        ):
            if self.success:
                return True
            else:
                self.tap((500, 970))
        elif scene == Scene.INFRA_ARRANGE_ORDER:
            self.scene_graph_step(Scene.RIIC_OPERATOR_SELECT)
        elif scene == Scene.INFRA_ARRANGE_CONFIRM:
            self.scene_graph_step(Scene.RIIC_OPERATOR_SELECT)
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            EnterRoomSolver().run(self.room)
