import hashlib
import json
import os
import signal
import tempfile
import time
import tkinter
import uuid
from time import sleep
from tkinter import messagebox

import requests

from common.hardware import Hardware
from common.log import logger
from service.socket_client import SocketClient
from service.ui import WinGUI
from wcferry import Wcf

from config import load_config, conf
from service.robot import Robot



class Win(WinGUI):
    def __init__(self):
        super().__init__()
        self.__event_bind()
        self.__style_config()
        self.robot = None

    def __event_bind(self):
        # self.tk_button_save.bind('<Button-1>', self.save_event)
        self.tk_button_start.bind('<Button-1>', self.start_event)
        self.tk_button_pause.bind('<Button-1>', self.stop_event)
        self.tk_button_version.bind('<Button-1>', self.version_event)
        pass

    def __style_config(self):
        pass

    def version_event(self, event):
        messagebox.showinfo('版本信息', '当前版本：v2.0.4')

    def stop_event(self, event):

        if self.tk_button_pause.cget('state') == tkinter.DISABLED:
            return

        self.robot.wcf.cleanup()
        self.robot = None
        self.tk_button_start.config(state=tkinter.NORMAL)
        self.tk_button_pause.config(state=tkinter.DISABLED)
        messagebox.showinfo('提示', '助手已停止运行！')

    @staticmethod
    def check_token(token:str):
        # 获取当前网卡mac地址
        merchine_code = Hardware.get_machine_code()
        mac = "PC-"+str(merchine_code)
        url = "https://wxadminapi.gkscrm.com/wechat-api/token/check"

        payload = json.dumps({
            "token": token,
            "mac": str(mac)
        },indent=4)


        headers = {
            'Content-Type': 'application/json'
        }

        logger.info(f"token:{payload}")

        response = requests.request("POST", url, headers=headers, data=payload)


        if response.status_code == 200:
            resp = json.loads(response.text)

            if resp['valid'] == True:
                sign = resp['sign']
                timestamp = resp['timestamp']
                # 获取当前unix时间戳
                current_timestamp = int(time.time())

                if abs(current_timestamp - int(timestamp)) > 180:
                    messagebox.showerror('错误', '验证失败！请重试')
                    return False
                # 创建一个MD5哈希对象
                md5_hash = hashlib.md5()
                # 更新哈希对象
                md5_hash.update(token.encode('utf-8'))
                # 获取十六进制格式的MD5哈希值
                md5_token = md5_hash.hexdigest()

                md5_hash = hashlib.md5()
                md5_hash.update(str(mac).encode('utf-8'))
                md5_mac = md5_hash.hexdigest()


                md5_hash = hashlib.md5()
                md5_hash.update(str(timestamp).encode('utf-8'))
                md5_timestamp = md5_hash.hexdigest()

                md5_hash = hashlib.md5()
                md5_hash.update((md5_token+md5_mac+md5_timestamp).encode('utf-8'))
                md5_sign = md5_hash.hexdigest()


                if md5_sign != sign:
                    messagebox.showerror('错误', 'token验证失败！')
                    return False

                return True

            else:
                messagebox.showerror('错误', 'token已失效 或 与当前设备未绑定，每个token只能绑定一台设备！请填入和当前设备绑定的token，或者获取新的token！')
                return False
        else:
            messagebox.showerror('错误', '您的网络状态异常！请稍候重试')
            return False

    def start_event(self, event):

        if self.tk_button_start.cget('state') == tkinter.DISABLED:
            return

        # 检查token
        if not self.check_token(str(self.tk_input_token.get())):
            return

        wcf = Wcf(debug=conf().get("debug", False))
        def handler(sig, frame):
            wcf.cleanup()  # 退出前清理环境
            exit(0)
        signal.signal(signal.SIGINT, handler)

        self.robot = Robot(conf(), wcf)

        if self.robot.wcf.is_login():

            # 开启socket 连接
            self.sc = SocketClient(self.robot)


            self.tk_button_start.config(state='disabled')
            self.tk_button_pause.config(state='normal')
            messagebox.showinfo('提示', '助手开始运行！')

        # robot.keepRunningAndBlockProcess()

    def save_event(self, event):
        conf().update({
            "api_base":self.tk_input_api_base.get(),
            "api_key":self.tk_input_api_key.get(),
            "token":self.tk_input_token.get()
        })
        # 将字典写入 JSON 文件
        with open('config.json', 'w') as json_file:
            json.dump(conf(), json_file, indent=4)

        messagebox.showinfo('提示', '保存文件成功！')

def main():
    # load_config()

    win = Win()
    win.mainloop()



    # wcf = Wcf(debug=conf().get("debug", False))
    #
    # def handler(sig, frame):
    #     wcf.cleanup()  # 退出前清理环境
    #     exit(0)
    #
    # signal.signal(signal.SIGINT, handler)
    #
    # robot = Robot(conf(), wcf)
    #
    # # 接收消息
    # # robot.enableRecvMsg()     # 可能会丢消息？
    # robot.enableReceivingMsg()  # 加队列
    #
    #
    # robot.keepRunningAndBlockProcess()



# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    main()