from copy import deepcopy

from mower.data import agent_list
from mower.solvers.fight.battle_choose.battle_filter import BattleFilterSolver
from mower.solvers.fight.battle_choose.battle_tag_choose import BattleTagChoose
from mower.solvers.fight.battle_choose.choose_skill import ChooseSkillSolver
from mower.utils import config
from mower.utils.character_recognize import (
    operator_team_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 BattleAgentChooseSolver(SceneGraphSolver):
    solver_name = "战斗选择指定干员"

    def run(self, agents: list) -> list:
        if agents == []:
            raise ValueError("干员列表为空")
        self.agents = agents
        self.agents_copy = deepcopy(agents)

        self.agent = None
        self.tmp_swipe = None

        self.choosed = []
        self.lack = []
        self.clean = False
        self.filter = False

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

        super().run()

        self.choosed = set(self.choosed)
        logger.debug(f"选择完成干员：{self.choosed}")
        return [self.lack, len(self.choosed)]

    @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:
                return True
        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_team_select(config.recog.img))

        agent = None
        if "opers" in self.agent[0]:
            for i in self.agent[0]["opers"]:
                if i["name"] in self.recog_agents.keys():
                    agent = i
                    logger.info(f"干员组选择：{agent}")

            if agent is None:
                agent = self.agent[0]["opers"][0]
        else:
            agent = self.agent[0]

        agent_name = agent["name"]

        if agent_name in self.recog_agents.keys():
            is_choosed = self.is_choosed(self.recog_agents[agent_name])
            if is_choosed:
                ChooseSkillSolver().run(agent["skill"])
                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

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

            if BattleTagChoose().run(tag):
                self.agent[1] = True
                self.recog_agents = None
            return
        if self.agent[2] is False:
            logger.debug(f"左滑 {self.agent}")
            tmp_recog = self.swipe_update(
                [(700, 770), (1600, 770), (1600, 500)],
                [200, 200],
                up_wait=200,
                interval=0.2,
                func=operator_team_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_team_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}")
                self.lack.append(self.agent[0])
                self.agent = None

                if len(self.lack) > 1:
                    # 缺少两个及以上
                    return True

        self.before = config.recog.gray

    def is_choosed(self, scope) -> bool:
        if (
            cropimg(
                config.recog.img,
                [
                    [scope[0][0] + 60, scope[0][1] - 113],
                    [scope[0][0] + 61, scope[0][1] - 112],
                ],
            )[0][0][0]
            < 50
        ) and cropimg(
            config.recog.img,
            [
                [scope[0][0] + 60, scope[1][1] + 216],
                [scope[0][0] + 61, scope[1][1] + 217],
            ],
        )[0][0][0] < 50:
            return True
        return False

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.OPERATOR_AGENT_SELECT:
            if pos := self.find("choose_agent/open_profession"):
                self.ctap(pos, interval=self.interval)
            if self.filter is False:
                if BattleFilterSolver().run("等级", ascending=False):
                    self.filter = True
            if self.clean is False and len(self.agents) > 1:
                agents_dict = dict(operator_team_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_battle", interval=self.interval)
                        return
                self.clean = True

            return self.choose_agents()

        elif scene == Scene.OPERATOR_SELECT:
            self.tap("choose_agent/fast_select")
        elif scene == Scene.SSS_SQUAD:
            self.tap("sss/choose/fast_select")
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            return True
