package com.fs.wxcid.service.impl;


import com.fs.common.exception.CustomException;
import com.fs.wxcid.ServiceUtils;
import com.fs.wxcid.dto.callback.CallbackConfigRequest;
import com.fs.wxcid.dto.callback.CallbackConfigResponse;
import com.fs.wxcid.dto.callback.ReturnMessage;
import com.fs.wxcid.dto.common.ApiResponse;
import com.fs.wxcid.dto.login.AccountIdParam;
import com.fs.wxcid.dto.common.ApiResponseCommon;
import com.fs.wxcid.dto.login.LoginQrCodeResponseData;
import com.fs.wxcid.dto.login.RequestBaseVo;
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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 = "/message/";
    @Value("${ipad.wxIpadUrl}")
    private String wxIpadUrl;
    @Autowired
    private ServiceUtils serviceUtils;


    @Override
    public ReturnMessage returnMessage(Map<String, Object> callback) {
        ReturnMessage returnMessage = new ReturnMessage();

        // 外层 key
        returnMessage.setAuthkey((String) callback.get("key"));

        // 获取 message 子对象
        Map<String, Object> message = (Map<String, Object>) callback.get("message");
        if (message != null) {
            // msg_id: 可能是 Long 或 Integer，统一转为 Long
            Object msgIdObj = message.get("msg_id");
            if (msgIdObj != null) {
                returnMessage.setMsgId(msgIdObj instanceof Number ? ((Number) msgIdObj).longValue() : Long.valueOf(msgIdObj.toString()));
            }

            // from_user_name.str
            Map<?, ?> fromUser = (Map<?, ?>) message.get("from_user_name");
            if (fromUser != null) {
                returnMessage.setFromWxId((String) fromUser.get("str"));
            }

            // to_user_name.str
            Map<?, ?> toUser = (Map<?, ?>) message.get("to_user_name");
            if (toUser != null) {
                returnMessage.setToWxId((String) toUser.get("str"));
            }

            // content.str
            Map<?, ?> content = (Map<?, ?>) message.get("content");
            if (content != null) {
                returnMessage.setText((String) content.get("str"));
            }

            // msg_type
            Object msgTypeObj = message.get("msg_type");
            if (msgTypeObj != null) {
                returnMessage.setMsgType(msgTypeObj instanceof Number ? ((Number) msgTypeObj).intValue() : Integer.parseInt(msgTypeObj.toString()));
            }

            // create_time
            Object timeObj = message.get("create_time");
            if (timeObj != null) {
                returnMessage.setTime(timeObj instanceof Number ? ((Number) timeObj).longValue() : Long.parseLong(timeObj.toString()));
            }

            // status
            Object statusObj = message.get("status");
            if (statusObj != null) {
                returnMessage.setStatus(statusObj instanceof Number ? ((Number) statusObj).intValue() : Integer.parseInt(statusObj.toString()));
            }
        }

        log.info("接收到回调消息, 发送者id: {}, 接收者id: {}, 消息内容: {}, 消息类型: {}, 状态: {}, 时间: {}",
                returnMessage.getFromWxId(),
                returnMessage.getToWxId(),
                returnMessage.getText(),
                returnMessage.getMsgType(),
                returnMessage.getStatus(),
                returnMessage.getTime());

        return returnMessage;
    }

    @Override
    public ApiResponseCommon<Void> setCallback(AccountIdParam param) {
        CallbackConfigRequest request = new CallbackConfigRequest();
        request.setCallbackURL(wxIpadUrl);
        request.setEnabled(true);
        ApiResponseCommon<Void> response = serviceUtils.sendPost(BASE_URL + "SetCallback", RequestBaseVo.builder().accountId(param.getAccountId()).data(request).build(), new TypeReference<ApiResponseCommon<Void>>() {});
        String text = response.getText();
        int code = response.getCode();
        if (code == 200) {
            return response;
        }else{
            String errorMsg = text != null ? text : "设置回调地址，未知错误";
            throw new CustomException("设置回调地址: " + errorMsg);
        }
    }

    /**
     * 获取消息回调配置
     */
    public ApiResponseCommon<CallbackConfigResponse> getCallback(String key) {
        String url = BASE_URL + "/message/GetCallback?key=" + key;
        ApiResponseCommon<CallbackConfigResponse> response = WxWorkHttpUtil.getWithType(
                url,
                new TypeReference<ApiResponseCommon<CallbackConfigResponse>>() {}
        );

        if (response.getCode() != 200 || response.getData() == null) {
            throw new CustomException("获取回调配置失败: " + (response.getText() != null ? response.getText() : "未知错误"));
        }

        return response;
    }

    /**
     * 删除消息回调配置
     */
    public ApiResponseCommon<Void> deleteCallback(String key) {
        String url = BASE_URL + "/message/DeleteCallback?key=" + key;
        ApiResponseCommon<Void> response = WxWorkHttpUtil.getWithType(
                url,
                new TypeReference<ApiResponseCommon<Void>>() {}
        );

        if (response.getCode() != 200) {
            throw new CustomException("删除回调配置失败: " + (response.getText() != null ? response.getText() : "未知错误"));
        }

        return response;
    }


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

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