import os.path
import subprocess
import time

from PyQt5.QtWidgets import QFileDialog

from yangke.base import save_temp_para, get_temp_para
from yangke.common.qt import YkWindow, run_app
from yangke.common.config import logger
import win32api  # 先要安装pywin32，pip install pywin32
from yangke.common.win.win_x64 import capture_pic, find_window, do_click


class Main(YkWindow):
    def __init__(self):
        super(Main, self).__init__()
        self.exe_file = get_temp_para("exe_file", get_func_or_default_value="C://")
        self.exe_title = get_temp_para("exe_title", get_func_or_default_value="天谕")
        self.enable_input_panel()
        self.set_value_of_panel([self.exe_file, self.exe_title])
        self.pid = 0

    def btn_clicked(self, anything=None, anything2=None, **kwargs):
        text = self.sender().text()
        values = self.get_value_of_panel(False, True)
        self.exe_file = values.get("应用程序路径：")
        if text == "启动":
            self.login()

    def choose_file(self):
        file, file_type = QFileDialog.getOpenFileName(parent=self, caption="选择文件",
                                                      directory=os.path.dirname(self.exe_file), filter="*.exe")
        if file != self.exe_file:
            self.exe_file = file
            save_temp_para("exe_file", file)
        self.set_value_of_panel([file, self.exe_title])

    def login(self):
        hwnd = find_window(self.exe_title)
        if hwnd == 0:
            self.pid = subprocess.Popen(self.exe_file).pid  # 该方法获取到的pid一般不是游戏文件打开后对应的pid，这是因为exe多次调用的关系
            time.sleep(5)
            hwnd = find_window(self.exe_title)
        capture_pic(hwnd, show=True)
        do_click(1031, 338, hwnd)


run_app(Main)
