# Time    : 2024/8/12 14:14
# Author  : wangchao
# File    : Get_Screenshot.py
# Description :
import functools
import os
import time

from playwright.sync_api import sync_playwright

from Config import Config


class ScreenCapture:
    def __init__(self):
        self.browser = None
        self.page = None

    def init(self):
        playwright = sync_playwright().start()
        self.browser = playwright.chromium.launch(headless=False, channel="chromium", args=['--start-maximized'])  # 启动 Chromium 浏览器
        context = self.browser.new_context(no_viewport=True, locale="zh-CN")
        self.page = context .new_page()  # 创建新的页面

    def navigate(self, url):
        self.page.goto(url)  # 导航到指定的 URL
        self.page.wait_for_load_state('networkidle')  # 等待页面的所有网络请求结束并且在一段时间没有新的请求（默认是500毫秒）
        #time.sleep(5)
    def capture_screenshot(self, x, y, width, height, output_path):
        # 根据指定区域截取快照
        self.page.screenshot(path=output_path, clip={'x': x, 'y': y, 'width': width, 'height': height})

    def close(self):
        self.page.close()  # 关闭页面
        self.browser.close()  # 关闭浏览器

    def generate_screenshot(self, url, x, y, width, height, screenshot_file_path):
        """生成页面截图"""
        try:
            self.init()
            self.navigate(url)
            #screenshot_file_path = Config.actual_img_dir + os.path.sep + f"{case_name}_{str(int(time.time()))}屏幕截图.png" # actual_img_dir为存储实际截图的路径
            self.capture_screenshot(x, y, width, height, screenshot_file_path)
        finally:
            self.close()

# 使用示例
if __name__ == "__main__":
    screen_capture = ScreenCapture()
    screenshot_file_path = Config.actual_img_dir + os.path.sep + f"测试用例2_页面截图_实际_{str(int(time.time()))}.png"  # actual_img_dir为存储实际截图的路径
    screen_capture.generate_screenshot('http://192.168.1.166:18000/#/editing/project/158/page/41', 345, 333, 865, 640, screenshot_file_path)
