# Time    : 2024/8/9 10:11
# Author  : wangchao
# File    : ImageRecognitionClick.py
# Description :
import os
import time

import cv2
import numpy as np
from playwright.sync_api import sync_playwright

from Config import Config


class PlaywrightImageClicker:
    def __init__(self, url):
        self.url = url

    def capture_screenshot(self, screenshot_path):
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=False, channel="chromium", args=['--start-maximized'])
            context = browser.new_context(no_viewport=True, locale="zh-CN", accept_downloads=True)
            page = context.new_page()
            page.goto(self.url)
            time.sleep(5)
            page.screenshot(path=screenshot_path, full_page=True)
            browser.close()

    def find_element_position(self, screenshot_path, template_path, threshold=0.8):
        # 读取截图和模板图像
        full_image = cv2.imread(screenshot_path)
        template = cv2.imread(template_path)

        # 转换为灰度图
        gray_full = cv2.cvtColor(full_image, cv2.COLOR_BGR2GRAY)
        gray_template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)

        # 使用模板匹配
        result = cv2.matchTemplate(gray_full, gray_template, cv2.TM_CCOEFF_NORMED)

        # 寻找匹配位置
        loc = np.where(result >= threshold)

        for pt in zip(*loc[::-1]):
            return pt

        return None

    def click_element(self, element_position):
        if element_position is None:
            print("Element position not found. Cannot click.")
            return

        with sync_playwright() as p:
            browser = p.chromium.launch(headless=False, channel="chromium", args=['--start-maximized'])
            context = browser.new_context(no_viewport=True, locale="zh-CN", accept_downloads=True)
            page = context.new_page()
            page.goto(self.url)
            time.sleep(5)
            #x, y = element_position
            # Convert x and y to standard Python integers
            x, y = int(element_position[0]), int(element_position[1])
            print(f"Clicking at ({x}, {y})")
            page.mouse.click(x, y)
            time.sleep(5)
            browser.close()

    def perform_image_click(self, screenshot_path, template_path):
        # Step 1: Capture screenshot
        self.capture_screenshot(screenshot_path)

        # Step 2: Find element position
        element_position = self.find_element_position(screenshot_file_path, template_path)

        # Step 3: Click the element
        self.click_element(element_position)

# Example usage
if __name__ == "__main__":
    clicker = PlaywrightImageClicker('http://192.168.1.166:18000/#/editing/project/158/page/41')
    screenshot_file_path = Config.screenshot_img_dir + os.path.sep + f"{str(int(time.time()))}屏幕截图.png"
    template_file_path = Config.template_img_dir + os.path.sep + "Snipaste_2024-08-09_11-57-40.png"
    clicker.perform_image_click(screenshot_file_path, template_file_path)