package com.fs.wxcid.service.impl;


import com.fs.wxcid.dto.callback.ReturnMessage;
import com.fs.wxcid.dto.common.ApiResponse;
import com.fs.wxcid.dto.callback.CallbackConfigRequest;
import com.fs.wxcid.service.MessageCallbackService;
import com.fs.wxwork.utils.WxWorkHttpUtil;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class MessageCallbackServiceImpl implements MessageCallbackService {

    private static final String BASE_URL = "http://114.117.215.244:7006";

    @Override
    public ReturnMessage returnMessage(Map<String, Object> callback) {
        // 安全地获取 authKey
        String authKey = (String) callback.get("authKey");

        // 获取 message 子对象（也是一个 Map）
        Map<String, Object> message = (Map<String, Object>) callback.get("message");
        ReturnMessage returnMessage=new ReturnMessage();
        if (message != null) {
            // 获取嵌套的 from_user_name -> str
            Map<String, String> fromUser = (Map<String, String>) message.get("from_user_name");
            String fromWxId = fromUser != null ? fromUser.get("str") : null;

            // 获取 content
            Map<String, String> contentWrapper = (Map<String, String>) message.get("content");
            String text = contentWrapper != null ? contentWrapper.get("str") : null;

            returnMessage.setFromWxId(fromWxId);
            returnMessage.setText(text);
        }
        log.info("接收到回调消息,发送者id:{},发送内容:{}", returnMessage.getFromWxId(),returnMessage.getText());
        return returnMessage;
    }

    /**
     * 设置消息回调
     */
    public ApiResponse setCallback(String authKey, CallbackConfigRequest config) {
        return post("/message/SetCallback", authKey, config);
    }

    /**
     * 获取消息回调配置
     */
    public ApiResponse getCallback(String authKey) {
        return get("/message/GetCallback", authKey);
    }

    /**
     * 删除消息回调配置
     */
    public ApiResponse deleteCallback(String authKey) {
        return get("/message/DeleteCallback", authKey);
    }


    // ------------------ 工具方法 ------------------
    /**
     * 通用 POST 请求方法
     *
     * @param path   接口路径，如 "/friend/AgreeAdd"
     * @param authKey    账号唯一标识（query 参数）
     * @param request 请求体对象
     * @return 统一响应结果
     */
    private ApiResponse post(String path, String authKey, Object request) {
        String url = BASE_URL + path + "?key=" + authKey;
        return WxWorkHttpUtil.postWithType(url, request, new TypeReference<ApiResponse>() {});
    }

    /**
     * 通用 GET 请求方法（无请求体）
     *
     * @param path 接口路径
     * @param authKey  账号唯一标识
     * @return 统一响应结果
     */
    private ApiResponse get(String path, String authKey) {
        String url = BASE_URL + path;
        Map<String, Object> params = new HashMap<>();
        params.put("authKey", authKey);
        String resp = WxWorkHttpUtil.get(url, params);
        return com.alibaba.fastjson.JSON.parseObject(resp, ApiResponse.class);
    }
}