# -*- encoding=utf8 -*-
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, HttpUrl
from aiohttp import ClientSession
from PIL import Image
from io import BytesIO
import os
import time
from paddleocr import PaddleOCR
app = FastAPI()


class URLItem(BaseModel):
    url: HttpUrl


async def download_image(url: str) -> bytes:
    async with ClientSession() as session:
        async with session.get(str(url)) as response:
            if response.status != 200:
                raise HTTPException(status_code=404, detail="Image not found")
            return await response.read()


@app.post("/download-image/")
async def download_image_endpoint(item: URLItem):
    try:
        image_bytes = await download_image(item.url)
        image = Image.open(BytesIO(image_bytes))

        # Ensure the directory exists
        os.makedirs("images", exist_ok=True)

        image_filename = os.path.join("images", "{}.png".format(str(int(time.time()))))

        # Save the image to a file
        image.save(image_filename)
        target_text="安装"

        ocr = PaddleOCR(use_angle_cls=True, lang='ch')  # 可以根据需要选择语言

        ocr_result = ocr.ocr(image_filename, cls=True)
        if '请输入' in str(ocr_result):
            return {"code":201,"data":[]}
        # 遍历识别结果，找到目标文字的坐标
        target_coords = None
        for line in ocr_result:
            for word_info in line:
                #获取识别结果的文字信息
                textinfo = word_info[1][0]
                print(textinfo)

                if target_text in textinfo and len(textinfo)<5 or '授权本次安装' == textinfo:
                    # 获取文字的坐标（中心点）
                    x1, y1 = word_info[0][0]
                    x2, y2 = word_info[0][2]
                    target_coords = ((x1 + x2) / 2, (y1 + y2) / 2)
                    break
            if target_coords:
                break

        # 使用Airtest点击坐标
        if target_coords:
            print(target_coords)
            return {"code":200,"data":[str(target_coords[0]),str(target_coords[1])]}
        else:
            return {"code":404,"data":[]}


    except Exception as e:
        print(e)
        raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="10.90.1.217", port=8008)


# def ocr_touch(target_text) :
#      # 截屏当前画面
#     pic_path=r"./now.png"
#     snapshot(pic_path)
#
#      # 使用PaddleOCR识别图片文字
#     ocr_result = ocr.ocr(pic_path, cls=True)
#
#     # 遍历识别结果，找到目标文字的坐标
#     target_coords = None
#     for line in ocr_result:
#         for word_info in line:
#             #获取识别结果的文字信息
#             textinfo = word_info[1][0]
#             print(textinfo)
#
#             if target_text in textinfo:
#                 # 获取文字的坐标（中心点）
#                 x1, y1 = word_info[0][0]
#                 x2, y2 = word_info[0][2]
#                 target_coords = ((x1 + x2) / 2, (y1 + y2) / 2)
#                 break
#         if target_coords:
#             break
#
#     # 使用Airtest点击坐标
#     if target_coords:
#         touch(target_coords)
#     else:
#         print(f"未找到目标文字：{target_text}")


