import requests
from Entity.Variables import prologueList
from Utils.JsonUtils import JsonUtils
from Utils.LogManager import LogManager

BaseUrl = "https://crawlclient.api.yolozs.com/api/common/"


class Requester():
    comment = "comment"
    prologue = "prologue"

    @classmethod
    def requestPrologue(cls, token):
        try:
            headers = {
                "vvtoken": token,
            }
            url = BaseUrl + cls.prologue
            result = requests.get(headers=headers, url=url, verify=False)
            json = result.json()
            data = json.get("data")
            for i in data:
                prologueList.append(i)
        except Exception as e:
            LogManager.method_error(f"获取requestPrologue失败,报错的原因:{e}", "获取requestPrologue异常")

    # 翻译
    @classmethod
    def translation(cls, msg, country="英国"):
        try:
            if country == "":
                country = "英国"

            param = {
                "msg": msg,
                "country": country,
            }
            url = "https://ai.yolozs.com/translation"
            result = requests.post(url=url, json=param, verify=False)

            LogManager.info(f"翻译 请求的参数:{param}", "翻译")
            LogManager.info(f"翻译,状态码:{result.status_code},服务器返回的内容:{result.text}", "翻译")

            if result.status_code != 200:
                LogManager.error(f"翻译失败,状态码:{result.status_code},服务器返回的内容:{result.text}")
                return None

            json = result.json()
            data = json.get("data")
            return data
        except Exception as e:
            LogManager.method_error(f"翻译失败,报错的原因:{e}", "翻译失败异常")

    # ai聊天
    @classmethod
    def chatToAi(cls, param):
        aiConfig = JsonUtils.read_json("aiConfig")
        agentName = aiConfig.get("agentName")
        guildName = aiConfig.get("guildName")
        contactTool = aiConfig.get("contactTool", "")
        contact = aiConfig.get("contact", "")

        inputs = {
            "name": agentName,
            "Trade_union": guildName,
            "contcat_method": contactTool,
            "contcat_info": contact
        }

        param["inputs"] = inputs

        try:
            url = "https://ai.yolozs.com/chat"
            result = requests.post(url=url, json=param, verify=False)
            json = result.json()
            data = json.get("answer", {})
            session_id = json.get("conversation_id", {})
            LogManager.method_info(f"ai聊天的参数：{param},ai聊天返回的内容：{result.json()}", "ai聊天")

            return data, session_id
        except Exception as e:
            LogManager.method_error(f"ai聊天失败,ai聊天出现异常,报错的原因:{e}", "ai聊天接口异常")
