import time
import json
import hashlib
import base64
import ddddocr
import os
import socket
import platform
from robot.api.deco import keyword

class Util(object):

    @keyword("获取本机内网IP")
    def get_local_internal_ip(self):
        """
        获取本机默认路由的内网IP（最常用，如 192.168.1.100）
        无需额外依赖，跨平台（Windows/Mac/Linux）
        """
        try:
            # 创建UDP连接（不实际发送数据），获取默认路由的IP
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # 连接到任意公网地址（仅用于获取本地出口IP，无需可达）
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
            s.close()
            return local_ip
        except Exception as e:
            # 备用方案：获取本地主机名对应的IP
            local_ip = socket.gethostbyname(socket.gethostname())
            return local_ip

    @keyword("is file exist")
    def is_file_exist(self, file_path):
        """判断文件是否存在（返回布尔值），明确返回 True/False"""
        return os.path.exists(file_path)

    @keyword("write file")
    def write_file(self, file_path, content, encoding="utf-8"):
        """写入文件内容（覆盖）"""
        with open(file_path, "w", encoding=encoding) as f:
            f.write(str(content))

    @keyword("read file")
    def read_file(self, file_path, encoding="utf-8"):
        """读取文件内容"""
        with open(file_path, encoding=encoding) as f:
            return f.read().strip()

    @keyword("get current time")
    def get_current_time(self,format):
        """
        获取当前时间的日期，并格式化
        """
        localtime = time.localtime()
        formatetime = time.strftime(format,localtime)
        print(formatetime)
        return formatetime

    @keyword("decode")
    def decode(self, customstr, mode):
        return customstr.decode(mode)

    @keyword("stringToJson")
    def stringToJson(self,body):
        ini_string = json.dumps(body)
        final_dictionary = json.loads(ini_string)
        return final_dictionary

    @keyword("GET MD5")
    def get_md5(self, str):
        """
        将字符转换md5
        """
        md5Key = hashlib.md5()
        str_utf8 = str.encode(encoding="utf-8")
        md5Key.update(str_utf8)
        md5_str = md5Key.hexdigest()
        return md5_str

    @keyword("base64 encode")
    def base64_encode(self, str_input):
        """
        将输入的字符串base64.encode转换
        """
        byte_str = str_input.encode()
        bs64 = base64.b64encode(byte_str)
        return bs64.decode()

    @keyword("base64 decode")
    def base64_decode(self, str_input):
        """
        将输入的字符串base64.decode转换
        """
        byte_str = str_input.encode()
        bs64 = base64.b64decode(byte_str)
        return bs64.decode()

    @keyword("get verify code")
    def get_verify_code(self, image_path):
        ocr = ddddocr.DdddOcr()
        with open(image_path, 'rb') as f:
            img_bytes = f.read()
        return ocr.classification(img_bytes)


if __name__ == '__main__':
    util=Util()
    util.get_current_time("%Y-%m-%d %H:%M:%S")
    body = {'vishesh': 1, 'ram': 5, 'prashant': 10, 'vishal': 15}
    util.stringToJson(body)
    #test base64 decode
    str = "YTg2ODJmMjRiMWRkZmI0NGNjZDlmYzVmYTBlNzhkNTE="
    print(util.base64_decode(str))
    print(util.get_local_internal_ip())