import time
import random
import threading

from . import duiwu

# 导入系统资源模块
from ascript.android.system import R

# 导入动作模块
from ascript.android import action

# 导入图色检索模块
from ascript.android.screen import FindImages

from ascript.android.screen import FindColors

# 文字识别
from ascript.android.screen import Ocr

# 战斗状态
isfire_wfstatus = False

# 捉鬼状态
zhuoguiisover = False

# 领取双倍状态
shuangbei = False

# 定义一个全局变量来管理定时器
alllive_task_timer = None


def huodong():
    while True:
        res_last = zhaotu("活动.png")
        if res_last is not None:
            findandclick(res_last)
            sleep(1)
            res_hd_c = FindImages.find([R.img("活动-c.png"), ], rect=[421, 76, 620, 137], confidence=0.95)
            if res_hd_c is not None:
                return True
            else:
                continue
        else:
            print("没找到活动按钮")
            if isfire():
                print("战斗中，打开所有按钮")
                res_suoyoutubiao = zhaotu("所有图标.png")
                if res_suoyoutubiao is None:
                    print("未找到目标图片：所有图标.png")
                    # 异常情况
                    closeAllbtn()
                else:
                    # 找到所有活动图标，点击
                    findandclick(res_suoyoutubiao)
            else:
                closeAllbtn()

    sleep(1)


def findandclick(res):
    # 提取矩形范围
    rect = res["rect"]  # [x1, y1, x2, y2]
    # 随机生成矩形范围内的一个点

    x = random.randint(rect[0], rect[2])  # 随机 x 坐标
    y = random.randint(rect[1], rect[3])  # 随机 y 坐标
    # 执行点击操作

    print(f"点击", rect)
    action.click(x, y)  # 在随机点点击
    time.sleep(0.5)


def closeAllbtn():
    res_allclose = zhaotu("总开关.png")

    if res_allclose is None:
        print("未找到目标图片：总开关.png")
    else:
        print("关闭-总开关弹框")
        findandclick(res_allclose)

    res_flkg = zhaotu("福利-开关.png")

    if res_flkg is None:
        print("未找到目标图片：福利-开关.png")
    else:
        print("关闭-福利-开关弹框")
        findandclick(res_flkg)

    # 见面礼-关闭.png
    res_flkg = zhaotu("见面礼-关闭.png")
    if res_flkg is None:
        print("未找到目标图片：见面礼-关闭.png")
    else:
        print("关闭-见面礼-开关弹框")
        findandclick(res_flkg)

    # 师门-关闭.png
    res_smgb = zhaotu("/shimen/师门-关闭.png")
    if res_smgb is not None:
        print("关闭-师门任务-弹框")
        findandclick(res_smgb)


def zhaotu(name):
    print(f"找图--", name)
    result = FindImages.find(
        [
            R.img(name),
        ],
        confidence=0.95,
    )
    if result is None:
        print(f"未找到图片：", name)

    return result


def isfire():
    global isfire_wfstatus
    # 战斗中
    res_zdqx = zhaotu("战斗-取消.png")
    if res_zdqx is None:
        print("未找到目标图片：战斗-取消.png")
        isfire_wfstatus = False
    else:
        print("战斗中.....")
        isfire_wfstatus = True
    return isfire_wfstatus


def denglu():
    while True:
        res_fwq = FindColors.find("382,434,#BC3010|380,442,#CE3116|643,431,#FFE986")
        if res_fwq is None:
            print("未找到服务器信息")
            # 找聊天框，找到认为已经进入游戏
            res_liaotian = zhaotu("聊天.png")
            if res_liaotian is None:
                print("找不到聊天，异常情况")
            else:
                # 在游戏中
                print("在游戏中-------")

                return
        else:
            res_denglu = zhaotu("登录游戏.png")
            # 判断是否找到目标图片
            if res_denglu is None:
                print("未找到目标图片：登录游戏.png")
            else:
                findandclick(res_denglu)
                sleep(5)

            while True:
                res_tcpd = zhaotu("退出排队.png")
                if res_tcpd is None:
                    print("未找到目标图片：退出排队.png")
                    return
                else:
                    # findandclick(res_tcpd)
                    sleep(60)

        sleep(1)


def zhaorenwu(name):
    # zhaorenwu.py 中优化滑动逻辑
    for i in range(3):
        res_tu = zhaotu(name)
        if res_tu is not None:
            return res_tu
        action.slide(731, 427, 408, 148, 2000)
        sleep(1)

    for i in range(3):
        res_tu = zhaotu(name)
        if res_tu is not None:
            return res_tu
        action.slide(408, 148, 731, 427, 2000)
        sleep(1)

    return None


def zhaocanjia_text(renwu_fanwei):
    # 266，273
    # 499,y1-   x1+320,y+50
    # x+234,y ,x+320,y+50
    gui_rect = renwu_fanwei["rect"]  # [x1, y1, x2, y2]
    print(gui_rect)
    x = gui_rect[0]
    y = gui_rect[1]
    x1 = x + 234
    x2 = x + 320
    y2 = y + 50
    search_region = [x1, y, x2, y2]
    print(f"找----参加-----文字坐标: ({x1}, {y},{x2}, {y2})")
    res = Ocr.paddleocr_v2(rect=search_region)
    if res is None:
        print("未找到参加文字")
        return None
    if res[0].text == "参加":
        res = {"rect": res[0].rect}
        return res
    else:
        return None


def zhaocanjia(renwu_fanwei):
    gui_rect = renwu_fanwei["rect"]  # [x1, y1, x2, y2]
    print(gui_rect)
    x1 = gui_rect[0]
    y1 = gui_rect[1]
    expand_x = 337  # X 方向扩展 337 像素
    expand_y = 93  # Y 方向扩展 93 像素
    x2 = x1 + expand_x
    y2 = y1 + expand_y
    search_region = [x1, y1, x2, y2]
    print(f"随机点击坐标: ({x1}, {y1},{x2}, {y2})")
    res_canjia = FindImages.find(
        [
            R.img("参加.png"),
        ],
        rect=search_region,
        confidence=0.95,
    )

    return res_canjia


def zhaowancheng_text(renwu_fanwei):
    # 266，273
    # 499,y1-   x1+320,y+50
    # x+234,y ,x+320,y+50
    gui_rect = renwu_fanwei["rect"]  # [x1, y1, x2, y2]
    print(gui_rect)
    x = gui_rect[0]
    y = gui_rect[1]
    x1 = x + 234
    x2 = x + 320
    y2 = y + 50
    search_region = [x1, y, x2, y2]
    print(f"找----完成-----文字坐标: ({x1}, {y},{x2}, {y2})")
    res = Ocr.paddleocr_v2(rect=search_region)
    if res is None:
        print("未找到参加文字")
        return None
    if res[0].text == "完成":
        res = {"rect": res[0].rect}
        return res
    else:
        return None


def zhaowancheng(renwu_fanwei):
    gui_rect = renwu_fanwei["rect"]  # [x1, y1, x2, y2]
    print(gui_rect)
    x1 = gui_rect[0]
    y1 = gui_rect[1]
    expand_x = 337  # X 方向扩展 337 像素
    expand_y = 93  # Y 方向扩展 93 像素
    x2 = x1 + expand_x
    y2 = y1 + expand_y
    search_region = [x1, y1, x2, y2]
    print(f"随机点击坐标: ({x1}, {y1},{x2}, {y2})")
    res_canjia = FindImages.find(
        [
            R.img("完成.png"),
        ],
        rect=search_region,
        confidence=0.95,
    )

    return res_canjia


def shizi(fanwei):
    print("开始识别")
    # 截取屏幕指定区域
    # fanwei=[500, 616, 545, 649] # 定义区域范围
    res = Ocr.paddleocr_v2(rect=fanwei)
    # print(res)
    if res:
        # 循环打印识别到的每一个段落
        for r in res:
            return r.text
    else:
        return None


def alllive_task(num):
    print("---------------定时任务-寻找异常弹窗----------------")
    # zhaotu("道具领取-弹框.png")
    ref_daoju = zhaotu("道具领取-弹框.png")
    if ref_daoju is None:
        print("未找到目标图片：弹框.png")
    else:
        findandclick(ref_daoju)

    res_map = zhaotu("地图.png")
    if res_map is None:
        print("未找到目标图片：地图.png")
    else:
        findandclick(res_map)

    res_dmj = zhaotu("洞冥记.png")
    if res_dmj is None:
        print("未找到目标图片：地图.png")
    else:
        findandclick(res_dmj)
    # 指引-关闭.png
    res_zy = zhaotu("指引-关闭.png")
    if res_zy is None:
        print("未找到目标图片：指引-关闭.png")
    else:
        findandclick(res_zy)

    # 充值-关闭.png
    res_cz = zhaotu("充值.png")
    if res_cz is None:
        print("未找到目标图片：充值.png")
    else:
        findandclick(res_cz)

    res_sl = zhaotu("算了.png")
    if res_sl is None:
        print("未找到目标图片：算了.png")
    else:
        findandclick(res_sl)

    res_jj = zhaotu("拒绝.png")
    if res_jj is None:
        print("未找到目标图片：拒绝.png")
    else:
        findandclick(res_jj)

    # 战斗状态监控
    isfire()

    duiwu.shifoukaping()

    start_alllive_task_timer(num)

def start_alllive_task_timer(num):
    global alllive_task_timer
    if alllive_task_timer is not None:
        alllive_task_timer.cancel()
    alllive_task_timer = threading.Timer(num, alllive_task, args=(num,))
    alllive_task_timer.start()
    print("定时任务已启动")


def stop_alllive_task_timer():
    global alllive_task_timer
    if alllive_task_timer is not None:
        alllive_task_timer.cancel()
        alllive_task_timer = None
        print("定时任务已停止")


def sleep(num):
    time.sleep(num)
