#!/usr/bin/env python
"""
@Project ：django_base_ai
@File    ：client.py
@Author  ：congxing.wang
@Date    ：2025/02/09
@Desc    ：消息客户端与通知发送
"""

import json

import requests

from django_base_ai import dispatch


class Client:
    def __init__(self):
        self.domain = dispatch.get_system_config_values("message.client_server_url")
        self.agent_id = dispatch.get_system_config_values("message.client_server_appid")
        self.app_secret = dispatch.get_system_config_values("message.client_server_secret")
        self.get_suite_token = f"{self.domain}/base/api/system/apps/get_suite_token/"
        self.open_api_create_message = f"{self.domain}/base/api/system/message_center/open_api_create_message/"
        self.open_api_get_message = f"{self.domain}/base/api/system/message_center/open_api_get_message/?agent_id="
        self.open_api_message_user_list = (
            f"{self.domain}/base/api/system/message_center_target_user/open_api_message_user_list/?nid="
        )
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": requests.request(
                "POST", self.get_suite_token, data={"agent_id": self.agent_id, "secret": self.app_secret}
            )
            .json()
            .get("data", None),
        }
        print(f"self.headers={self.headers}")

    def read(self):
        response = requests.request("GET", f"{self.open_api_get_message}{self.agent_id}", headers=self.headers)
        print(response.text)
        return response.json()

    def send(self, payload):
        # print(self.headers)
        response = requests.request(
            "POST", f"{self.open_api_create_message}", headers=self.headers, data=json.dumps(payload)
        )
        print(response.text)
        return response.json()

    def user_list(self, nid):
        response = requests.request("GET", f"{self.open_api_get_message}{nid}", headers=self.headers)
        print(response.text)
        return response.json()


if __name__ == "__main__":
    # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sobase.settings")
    # django.setup()
    domain, agent_id, app_secret = (
        "http://0.0.0.0:8020",
        "appid_e63af4df25af480b9aa4233de651bebd",
        "secret_f27fcafc92a111efa00eacde480011223549a001e5d24bbeb24829560f5bdb97",
    )
    client = Client()
    payload = {
        "title": "通知标题",
        "short_content": "哈哈哈哈哈哈哈哈",
        "message_type": 0,
        "thumbnail": "#",
        "content": "内容哈哈哈哈哈哈",
        "url": "http://www.baidu.com",
        "send_user_info": [{"id": 5, "name": "测试用户", "node_type": 4}],
    }
    send_json = client.send(payload)
    print(send_json)
    read_json = client.read()
    print(read_json)
    user_list = client.user_list(send_json.get("data").get("nid"))
    print(user_list)
