# apps/dingdan/utils/goeasy_service.py
import requests
import json
import logging
from django.conf import settings

logger = logging.getLogger(__name__)


class GoEasyService:
    """
    GoEasy聊天服务工具类
    用于建立用户间的私聊关系
    """

    def __init__(self):
        self.appkey = settings.GOEASY_APPKEY  # 需要在settings.py中配置
        self.secret = settings.GOEASY_SECRET  # GoEasy控制台获取的Secret
        self.rest_host = "https://rest-hz.goeasy.io"  # 杭州区域

    def create_private_chat(self, user1_id, user2_id, user1_info=None, user2_info=None):
        """
        建立两个用户间的私聊关系

        Args:
            user1_id: 用户1在GoEasy的标识
            user2_id: 用户2在GoEasy的标识
            user1_info: 用户1的附加信息 (avatar, nickname等)
            user2_info: 用户2的附加信息
        Returns:
            bool: 是否成功
        """
        try:
            # 构造消息数据
            message_data = {
                "appkey": self.appkey,
                "senderId": "system_admin",
                "senderData": {
                    "avatar": "/static/system_avatar.png",
                    "name": "系统通知"
                },
                "to": {
                    "type": "private",
                    "id": user1_id,
                    "data": user2_info or {
                        "avatar": "",
                        "name": f"用户{user2_id}"
                    }
                },
                "type": "system",
                "payload": {
                    "action": "create_chat",
                    "partner_id": user2_id,
                    "message": "已为您建立聊天连接"
                },
                "notification": {
                    "title": "新聊天",
                    "body": "您有新的聊天连接"
                }
            }

            # 发送请求
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.secret}"
            }

            response = requests.post(
                f"{self.rest_host}/v2/im/message",
                headers=headers,
                json=message_data,
                timeout=5  # 5秒超时
            )

            if response.status_code == 200:
                logger.info(f"成功建立聊天关系: {user1_id} ↔ {user2_id}")
                return True
            else:
                logger.error(f"建立聊天关系失败: {response.status_code}, {response.text}")
                return False

        except Exception as e:
            logger.error(f"调用GoEasy API异常: {str(e)}")
            return False

    def establish_chat_for_order(self, order, dashou_yonghuid, dashou_info=None):
        """
        为订单建立聊天关系
        """
        # user1_id 是老板/商家标识 (从订单中获取)
        # user2_id 是打手标识
        user1_id = order.user1_id
        user2_id = f"Ds{dashou_yonghuid}"

        if not user1_id or not user2_id:
            logger.warning(f"缺少用户标识，无法建立聊天: user1_id={user1_id}, user2_id={user2_id}")
            return False

        # 建立双向聊天关系
        success1 = self.create_private_chat(user1_id, user2_id, user2_info=dashou_info)
        success2 = self.create_private_chat(user2_id, user1_id)

        return success1 or success2  # 只要有一个方向成功就认为成功