package com.ssyf.third.bmiss.services;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ssyf.third.bmiss.core.ConfigManager;
import com.ssyf.third.bmiss.core.RequestManager;
import com.ssyf.third.bmiss.model.ApiResponse;
import com.ssyf.third.bmiss.model.AsrSpeechText;
import com.ssyf.third.bmiss.model.Gift;
import com.ssyf.third.bmiss.model.GiftCategory;
import com.ssyf.third.bmiss.model.GiftDetail;
import com.ssyf.third.bmiss.model.GiftListResponse;
import com.ssyf.third.bmiss.model.LiveRoom;
import com.ssyf.third.bmiss.model.LoginResponse;
import com.ssyf.third.bmiss.model.OtherUserCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 业务服务类
 * 实现业务API服务，包含登录、直播间操作和礼物赠送等功能
 *
 * @author system
 * @since 1.0
 */
@Slf4j
@Service
public class BusinessService {

    /**
     * 登录接口路径
     */
    private static final String LOGIN_PATH = "/api/login";

    /**
     * 直播间操作接口路径
     */
    private static final String LIVE_ROOM_ACTION_PATH = "/api/live/room/action";

    /**
     * 礼物赠送接口路径
     */
    private static final String GIFT_SEND_PATH = "/api/Live/liveRoomSendGift";

    /**
     * 邮箱登录接口路径
     */
    private static final String LOGIN_EMAIL_PATH = "/api/Login/loginWithEmail";

    /**
     * 退出登录接口路径
     */
    private static final String LOGOUT_PATH = "/api/Login/loginOut";

    /**
     * 更新用户信息接口路径
     */
    private static final String UPDATE_USER_PATH = "/api/robot/updateUser";

    /**
     * 加入直播间接口路径
     */
    private static final String JOIN_LIVE_ROOM_PATH = "/api/Live/joinRoom";

    /**
     * 退出直播间接口路径
     */
    private static final String QUIT_LIVE_ROOM_PATH = "/api/Live/goOutRoom";

    /**
     * 点赞直播间接口路径
     */
    private static final String LIKE_LIVE_ROOM_PATH = "/api/Live/likeLiveRoom";
    /**
     * 关注用户接口路径
     */
    private static final String FOLLOW_USER_PATH = "/api/User/followUser";

    /**
     * 分享/api/Live/getRoomOtherConfig
     */
    private static final String GET_ROOM_OTHER_CONFIG_PATH = "/api/Live/getRoomOtherConfig";

    /**
     * //app/Live/liveRoomChat ，发送直播间消息
     */
    private static final String LIVE_ROOM_CHAT_PATH = "/api/Live/liveRoomChat";

    /**
     * 获取用户中心信息接口路径
     */
    private static final String GET_USER_CENTER_PATH = "/api/User/getUserCenter";

    /**
     * 获取直播间状态接口路径
     */
    private static final String GET_ROOM_STATE_PATH = "/api/robot/getRoomState";

    /**
     * 获取礼物列表接口路径
     */
    private static final String GET_GIFT_LIST_PATH = "/api/goods/getGiftList";

    /**
     * 获取礼物列表接口路径
     */
    private static final String GET_ROBOT_GIFT_LIST = "/api/robot/getGiftList";


    /**
     * 赠送热门礼物接口路径
     */
    private static final String GIVE_HOT_GIFTS_PATH = "/api/gift/giveHotGifts";

    /**
     * 获取热门奖励状态接口路径
     */
    private static final String GET_HOT_AWARD_STATUS_PATH = "/api/hot/getHotAwardStatus";

    /**
     * 获取热门奖励门槛接口路径
     */
    private static final String GET_HOT_DOOR_SILL_PATH = "/api/hot/getHotDoorSill";

    /**
     * 申请余额接口路径
     */
    private static final String APPLY_FOR_BALANCE_PATH = "/api/robot/requestBalance";
    /**
     * 获取直播间的人数
     * /api/Live/getRoomOnlineUserList
     */
    private static final String GET_ROOM_ONLINE_USER_LIST_PATH = "/api/Live/getRoomOnlineUserList";

    /**
     * 开始主播开播状态接口路径
     */
    private static final String START_BROADCAST_ANCHOR_PATH = "/api/robot/getAllShowingRooms";

    /**
     * 获取机器人资金池接口路径
     * /api/robot/robotFundPool
     */
    private static final String GET_ROBOT_FUND_POOL_PATH = "/api/robot/robotFundPool";

    /**
     * 获取其他用户中心信息接口路径
     * /api/User/getOtherUserCenter
     */
    private static final String GET_OTHER_USER_CENTER_PATH = "/api/User/getOtherUserCenter";
    /**
     * 搜索其他用户信息接口路径
     */
    private static final String SEARCH_FOR_USER_BY_NUMBER_PATH = "/api/User/searchForUserByNumber";
    /**
     * 获取直播间当前状态接口路径
     * /api/Live/getLiveRoomCurrentState
     */
    private static final String GET_LIVE_ROOM_CURRENT_STATE_PATH = "/api/Live/getLiveRoomCurrentState";

    /**
     * 开启ASR解析接口路径
     */
    private static final String ASR_START_PATH = "/api/Live/asr/start";

    /**
     * 结束ASR解析接口路径
     */
    private static final String ASR_END_PATH = "/api/Live/asr/end";

    /**
     * 获取直播间主播语音解析结果接口路径
     */
    private static final String ASR_GET_SPEECH_TEXT_PATH = "/api/Live/asr/getSpeechText";

    @Autowired
    private RequestManager requestManager;

    @Autowired
    private ConfigManager configManager;

    /**
     * 将JSONObject转换为ApiResponse
     *
     * @param jsonObject JSON响应对象
     * @param <T>        数据类型
     * @return ApiResponse对象
     */
    @SuppressWarnings("unchecked")
    private <T> ApiResponse<T> convertToApiResponse(JSONObject jsonObject) {
        return convertToApiResponse(jsonObject, null);
    }

    /**
     * 将JSONObject转换为ApiResponse
     *
     * @param jsonObject JSON响应对象
     * @param <T>        数据类型
     * @return ApiResponse对象
     */
    private <T> ApiResponse<T> convertToApiResponse(JSONObject jsonObject, Class<T> clazz) {
        if (jsonObject == null) {
            return ApiResponse.error("响应为空");
        }

        Integer code = jsonObject.getInt("code");
        String message = jsonObject.getStr("message");
        String msg = jsonObject.getStr("msg");
        Object data = jsonObject.get("data");
        Long timestamp = jsonObject.getLong("timestamp");

        ApiResponse<T> response = new ApiResponse<>();
        response.setCode(code);
        response.setMessage(StrUtil.isNotBlank(message) ? message : msg);
        response.setMsg(StrUtil.isNotBlank(msg) ? msg : message);

        response.setTimestamp(timestamp != null ? timestamp : System.currentTimeMillis());

        if (data == null) {
            return response;
        }

        if (clazz == null) {
            response.setData((T) data);
            return response;
        }

        try {
            // 处理基本数据类型的转换
            if (clazz == String.class) {
                response.setData(clazz.cast(data.toString()));
            } else if (clazz == Integer.class || clazz == int.class) {
                if (data instanceof Number) {
                    response.setData(clazz.cast(((Number) data).intValue()));
                } else {
                    response.setData(clazz.cast(Integer.valueOf(data.toString())));
                }
            } else if (clazz == Long.class || clazz == long.class) {
                if (data instanceof Number) {
                    response.setData(clazz.cast(((Number) data).longValue()));
                } else {
                    response.setData(clazz.cast(Long.valueOf(data.toString())));
                }
            } else if (clazz == Double.class || clazz == double.class) {
                if (data instanceof Number) {
                    response.setData(clazz.cast(((Number) data).doubleValue()));
                } else {
                    response.setData(clazz.cast(Double.valueOf(data.toString())));
                }
            } else if (clazz == Float.class || clazz == float.class) {
                if (data instanceof Number) {
                    response.setData(clazz.cast(((Number) data).floatValue()));
                } else {
                    response.setData(clazz.cast(Float.valueOf(data.toString())));
                }
            } else if (clazz == Boolean.class || clazz == boolean.class) {
                if (data instanceof Boolean) {
                    response.setData(clazz.cast(data));
                } else {
                    response.setData(clazz.cast(Boolean.valueOf(data.toString())));
                }
            } else if (clazz == Short.class || clazz == short.class) {
                if (data instanceof Number) {
                    response.setData(clazz.cast(((Number) data).shortValue()));
                } else {
                    response.setData(clazz.cast(Short.valueOf(data.toString())));
                }
            } else if (clazz == Byte.class || clazz == byte.class) {
                if (data instanceof Number) {
                    response.setData(clazz.cast(((Number) data).byteValue()));
                } else {
                    response.setData(clazz.cast(Byte.valueOf(data.toString())));
                }
            } else {
                // 对于复杂对象，使用JSON转换
                response.setData(JSONUtil.toBean(JSONUtil.toJsonStr(data), clazz));
            }
            return response;
        } catch (Exception e) {
            log.error("转换数据异常", e);
            // 如果转换失败，尝试直接赋值
            try {
                response.setData((T) data);
            } catch (ClassCastException cce) {
                log.error("数据类型转换失败", cce);
            }
            return response;
        }
    }

    private <T> ApiResponse<List<T>> convertToApiResponseList(JSONObject jsonObject, Class<T> clazz) {
        if (jsonObject == null) {
            return ApiResponse.error("响应为空");
        }

        Integer code = jsonObject.getInt("code");
        String message = jsonObject.getStr("message");
        String msg = jsonObject.getStr("msg");
        Object data = jsonObject.get("data");
        Long timestamp = jsonObject.getLong("timestamp");

        ApiResponse<List<T>> response = new ApiResponse<>();
        response.setCode(code);
        response.setMessage(StrUtil.isNotBlank(message) ? message : msg);
        response.setMsg(StrUtil.isNotBlank(msg) ? msg : message);

        response.setTimestamp(timestamp != null ? timestamp : System.currentTimeMillis());
        if (data == null) {
            return response;
        }
        try {
            response.setData(JSONUtil.toList(JSONUtil.toJsonStr(data), clazz));
            return response;
        } catch (Exception e) {
            log.error("转换数据列表失败", e);
            response.setData((List<T>)data);
            return response;
        }
    }

    /**
     * 获取token，优先使用传入的token，如果没有则使用配置的token
     *
     * @param token 传入的token
     * @return 最终使用的token
     */
    private String getToken(String token) {
        return StrUtil.isNotBlank(token) ? token : "";
    }



    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @param token    令牌（可选，为空时使用配置的token）
     * @return 登录结果
     */
    public ApiResponse<Object> login(String username, String password, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + LOGIN_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 用户登录（使用配置的token）
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    public ApiResponse<Object> login(String username, String password) {
        return login(username, password, null);
    }

    /**
     * 直播间操作
     *
     * @param roomId      直播间ID
     * @param action      操作类型（如：start, stop, pause, resume）
     * @param extraParams 额外参数
     * @param token       令牌（可选，为空时使用配置的token）
     * @return 操作结果
     */
    public ApiResponse<Object> liveRoomAction(Integer roomId, String action, Map<String, Object> extraParams, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_id", roomId);
        params.put("action", action);
        params.put("token", getToken(token));

        if (extraParams != null) {
            params.putAll(extraParams);
        }

        String url = configManager.getBusiness().getBaseUrl() + LIVE_ROOM_ACTION_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 直播间操作（使用配置的token）
     *
     * @param roomId      直播间ID
     * @param action      操作类型（如：start, stop, pause, resume）
     * @param extraParams 额外参数
     * @return 操作结果
     */
    public ApiResponse<Object> liveRoomAction(Integer roomId, String action, Map<String, Object> extraParams) {
        return liveRoomAction(roomId, action, extraParams, null);
    }

    /**
     * 开始直播
     *
     * @param roomId 直播间ID
     * @param token  令牌（可选，为空时使用配置的token）
     * @return 操作结果
     */
    public ApiResponse<Object> startLive(Integer roomId, String token) {
        return liveRoomAction(roomId, "start", null, token);
    }

    /**
     * 开始直播（使用配置的token）
     *
     * @param roomId 直播间ID
     * @return 操作结果
     */
    public ApiResponse<Object> startLive(Integer roomId) {
        return startLive(roomId, null);
    }

    /**
     * 停止直播
     *
     * @param roomId 直播间ID
     * @param token  令牌（可选，为空时使用配置的token）
     * @return 操作结果
     */
    public ApiResponse<Object> stopLive(Integer roomId, String token) {
        return liveRoomAction(roomId, "stop", null, token);
    }

    /**
     * 停止直播（使用配置的token）
     *
     * @param roomId 直播间ID
     * @return 操作结果
     */
    public ApiResponse<Object> stopLive(Integer roomId) {
        return stopLive(roomId, null);
    }

    /**
     * 暂停直播
     *
     * @param roomId 直播间ID
     * @param token  令牌（可选，为空时使用配置的token）
     * @return 操作结果
     */
    public ApiResponse<Object> pauseLive(Integer roomId, String token) {
        return liveRoomAction(roomId, "pause", null, token);
    }

    /**
     * 暂停直播（使用配置的token）
     *
     * @param roomId 直播间ID
     * @return 操作结果
     */
    public ApiResponse<Object> pauseLive(Integer roomId) {
        return pauseLive(roomId, null);
    }

    /**
     * 恢复直播
     *
     * @param roomId 直播间ID
     * @param token  令牌（可选，为空时使用配置的token）
     * @return 操作结果
     */
    public ApiResponse<Object> resumeLive(Integer roomId, String token) {
        return liveRoomAction(roomId, "resume", null, token);
    }

    /**
     * 恢复直播（使用配置的token）
     *
     * @param roomId 直播间ID
     * @return 操作结果
     */
    public ApiResponse<Object> resumeLive(Integer roomId) {
        return resumeLive(roomId, null);
    }

    /**
     * 赠送礼物
     *
     * @param roomId   直播间ID
     * @param giftIdArr 礼物ID数组，包含礼物信息
     * @param isWishReach 是否心愿达成
     * @param ext 扩展信息
     * @param sendFrom 发送来源
     * @param recipientArr 接收者数组
     * @param sceneType 场景类型
     * @param token    令牌（可选，为空时使用配置的token）
     * @return 赠送结果
     *
     * 入参示例：
     * {
     *     "room_user_id": 7253,
     *     "gift_id_arr": [
     *         {
     *             "gift_id": 31593, //礼物id
     *             "skin_id": 0,
     *             "num": 1, //礼物数量
     *             "id":[28] //礼物背包id
     *         }
     *     ],
     *     "is_wish_reach": 0,
     *     "ext": {
     *         "num": 0,
     *         "callback_information": "王总的火箭"
     *     },
     *     "send_from": 1,
     *     "recipient_arr": [
     *         {
     *             "user_id": 7253
     *         }
     *     ],
     *     "scene_type":0
     * }
     */
    public ApiResponse<Object> sendGift(Integer roomId, List<Map<String, Object>> giftIdArr, Integer isWishReach,
                                        Map<String, Object> ext, Integer sendFrom, List<Map<String, Object>> recipientArr,
                                        Integer sceneType, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", roomId);
        params.put("gift_id_arr", giftIdArr);
        params.put("is_wish_reach", isWishReach);
        params.put("ext", ext);
        params.put("send_from", sendFrom);
        params.put("recipient_arr", recipientArr);
        params.put("scene_type", sceneType);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + GIFT_SEND_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }


    /**
     * 邮箱登录
     *
     * @param email    邮箱地址
     * @param password 密码
     * @param token    令牌（可选，为空时使用配置的token）
     * @return 登录结果
     * {
     * "code": 200,
     * "msg": "success",
     * "data": {
     * "user_info": {
     * "user_id": 6904,
     * "user_number": 43280101,
     * "nick_name": "132****280",
     * "country_mobile_code": "86",
     * "mobile": "13212329280",
     * "follow_me_number": 0,
     * "head_portrait": "https://cos.bmiss3.zhubei.cn/static_data/publicimg/img.jpg",
     * "head_audit": "",
     * "general_play_count": 0,
     * "personal_signature": "这个人很懒，什么都没留下。",
     * "head_portrait_box": "",
     * "age": "",
     * "birthday": "",
     * "city": "火星",
     * "gender": 0,
     * "adolescent_model": 0,
     * "province": "火星",
     * "fans_num": 0,
     * "my_follow_num": 0,
     * "balance": 199910,
     * "improve_information": 1,
     * "display_follow_sta": 0,
     * "is_show_like": 1,
     * "display_like_list": 1,
     * "is_achor": 0,
     * "like_dynamic_num": 0,
     * "user_dynamic_num": 0,
     * "video_give_up_num": 0,
     * "talent_name": "",
     * "confirm_name": "",
     * "season_info": {
     * "rankName": "青銅Ⅲ",
     * "rankImageD": "https://resources.test.brieftalk.cn/application_static_data/static_data/season_level/qtd.png",
     * "currentStar": 0,
     * "totalStar": 3,
     * "key": "qt3"
     * },
     * "im_sign_info": {
     * "sign": "eJwtjF0LgjAYRv-LrkO3uVYTuqiIUXYhMzBDiMGmvEQxdEgR-ff8unzOeThfdDlnQWcbFCMaYLQYNxj78lDBiL1t-Z0LzGbZmod2DgyKCccYE8IZmYx9O2hsz6kYzAQ9PAe04rg-0iiaI1D3aSaLk6Rd4g67OhW5TlV*LJa8DFUZ6j1ZJ56rrLrK20fJ7Qb9-uGcMW4_",
     * "app_id": "1600011641",
     * "identifier": "test_6904"
     * },
     * "show_list": [
     * {
     * "path": "https://cos.bmiss3.zhubei.cn/static_data/publicimg/public_bg.png",
     * "id": 1,
     * "path_violation": "0"
     * }
     * ],
     * "vip_img_info": {
     * "img": "/vip/vip_gray_month.png",
     * "network_img": "https://cos.bmiss3.zhubei.cn/static_data/public/vip_gray_month.png"
     * },
     * "vip_img": "/vip/vip_gray_month.png",
     * "network_vip_img": "https://cos.bmiss3.zhubei.cn/static_data/public/vip_gray_month.png",
     * "vip": {
     * "vip_status": 0,
     * "vip_icon": "",
     * "vip_grade": 0
     * },
     * "network_wealth_level": "https://cos.bmiss3.zhubei.cn/static_data/wealth/wealth_0.png",
     * "network_active_level": "https://cos.bmiss3.zhubei.cn/static_data/new_active_level/level_1.png",
     * "advertisement_all": null,
     * "advertisement_sta": 0,
     * "is_vip": 0,
     * "label_data": [],
     * "industry": "",
     * "emotion": 0,
     * "location_sta": 1,
     * "age_sta": 1,
     * "anchor_title_sta": 1,
     * "fan_card_sta": 1,
     * "is_chat_anchor": 0,
     * "is_chat_online": 0,
     * "email": ""
     * },
     * "token": "0c86d329b50fe867ee3e3ff1fddf37e6",
     * "cancellation_info": null,
     * "login_status": 1,
     * "register_status": 0,
     * "password_status": null
     * }
     * }
     */
    public ApiResponse<LoginResponse> loginByEmail(String email, String password, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("email", email);
        params.put("password", password);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + LOGIN_EMAIL_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse, LoginResponse.class);
    }



    /**
     * 邮箱登录（使用配置的token）
     *
     * @param email    邮箱地址
     * @param password 密码
     * @return 登录结果
     */
    public ApiResponse<LoginResponse> loginByEmail(String email, String password) {
        return loginByEmail(email, password, null);
    }

    /**
     * 退出登录
     *
     * @param userId 用户ID
     * @param token  用户令牌
     * @return 退出结果
     */
    public ApiResponse<Object> logout(Integer userId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + LOGOUT_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * {
     *     "head_portrait": "string",
     *     "nick_name": "string",
     *     "personal_signature": "string"
     * }
     * @param token
     * @return
     */
    public ApiResponse<Object> updateUser(String head_portrait, String nick_name, String personal_signature, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("head_portrait", head_portrait);
        params.put("nick_name", nick_name);
        params.put("personal_signature", personal_signature);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + UPDATE_USER_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }
    /**
     * 加入直播间
     *
     * @param roomId 直播间ID
     * @param userId 用户ID
     * @param token  用户令牌
     * @return 加入结果
     */
    public ApiResponse<Object> joinLiveRoom(Integer roomId, Integer userId ,String clientId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", roomId);
        params.put("join_room_type_keyword", "自动机器人");
        params.put("user_id", userId);
        params.put("client_id", clientId);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + JOIN_LIVE_ROOM_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }
    
    /**
     * 退出直播间
     *
     * @param roomId 直播间ID
     * @param userId 用户ID
     * @param token  用户令牌
     * @return 退出结果
     */
    public ApiResponse<Object> quitLiveRoom(Integer roomId, Integer userId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", roomId);
        params.put("user_id", userId);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + QUIT_LIVE_ROOM_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 点赞直播间
     *
     * @param roomId 直播间ID
     * @param userId 用户ID
     * @param token  用户令牌
     * @return 点赞结果
     */
    public ApiResponse<Object> giveLike(Integer roomId, Integer userId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", roomId);
//        params.put("user_id", userId);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + LIKE_LIVE_ROOM_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * {
     *     "operated_user_id": 0,
     *     "source_type": 0,
     *     "im_msg_type": 0
     * }
     * operated_user_id
     * integer
     * 被关注的用户id
     * 必需
     * source_type
     * integer
     * 关注来源
     * 必需
     * 0外部关注 1直播间内操作
     *
     * im_msg_type
     * integer
     * 是否回关触发
     * 可选
     * 0否1是
     */
    public ApiResponse<Object> followUser(Integer operated_user_id, String token , Integer source_type, Integer im_msg_type) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("operated_user_id", operated_user_id);
        params.put("source_type", source_type);
        params.put("im_msg_type", im_msg_type);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + FOLLOW_USER_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }


    /**
     *  {
     *         "room_user_id": 570674
     *     }
     *    获取分享信息
     * @param room_user_id
     * @param token
     * @return
     */
    public ApiResponse<Object> getRoomOtherConfig(Integer room_user_id, String token ) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", room_user_id);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + GET_ROOM_OTHER_CONFIG_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     *  直播间聊天
     *     //LIVE_ROOM_CHAT_PATH{
     *     //    "room_user_id": 0,
     *     //    "content": "string",
     *     //    "at_user_id": 0
     *     //}
     * @param room_user_id
     * @param token
     * @param content
     * @return
     */
    public ApiResponse<Object> liveRoomChat(Integer room_user_id, String token ,String content ) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", room_user_id);
        params.put("content", content);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + LIVE_ROOM_CHAT_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }


    /**
     * 获取用户中心信息
     *
     * @param userId 用户ID
     * @param token  用户令牌
     * @return 用户中心信息
     */
    public ApiResponse<Object> getUserCenter(Integer userId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + GET_USER_CENTER_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 获取直播间状态
     *{
     *     "code": 200,
     *     "msg": "success",
     *     "data": {
     *         "user_count": 123,
     *         "luck_gift_list": [1,2,3]
     *     }
     * }
     * @param roomId 直播间ID
     * @return 直播间状态信息
     */
    public ApiResponse<Gift> getRoomState(Integer roomId) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", roomId);

        String url = configManager.getBusiness().getBaseUrl() + GET_ROOM_STATE_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse ,Gift.class);
    }

    /**
     * 获取礼物列表
     *{
     * 	"code": 200,
     * 	"msg": "success",
     * 	"data": {
     * 		"data": [
     *            {
     * 				"id": 11,
     * 				"open_img_url": "http://oss.3yakj.com/application_static_data/static_data/gift/ac14bd9da64ad8d2e984130cd8d847f9.png",
     * 				"version": "",
     * 				"close_img_url": "http://oss.3yakj.com/application_static_data/static_data/gift/017be55c581a5df8b25ba68cb3225edd.png",
     * 				"order_by": 0,
     * 				"type": 2,
     * 				"title": "粉丝礼物",
     * 				"background_img": null,
     * 				"gui_zhu": "",
     * 				"wealth_level_start": 0,
     * 				"wealth_level_end": 0,
     * 				"click_type": 1,
     * 				"app_page_id": 0,
     * 				"is_sort": 1,
     * 				"remarks": "",
     * 				"is_support_sort": 1,
     * 				"gift_all": [
     *                    {
     * 						"gift_id": 9503,
     * 						"gift_cate_id": 6,
     * 						"gift_name": "默认-棒棒糖",
     * 						"gift_image": "http://oss.3yakj.com/application_static_data/static_data/gift/60630d183dd34.png",
     * 						"gift_flash": "http://oss.3yakj.com/application_static_data/static_data/gift/1.swf",
     * 						"gift_price": 1,
     * 						"version": "1.0",
     * 						"tag": "",
     * 						"color": "#fd79a8",
     * 						"charm_value": 53,
     * 						"anchor_exp": 2000,
     * 						"user_exp": 2000,
     * 						"privilege": "0",
     * 						"display_status": "0",
     * 						"crowd": "0",
     * 						"status": "1",
     * 						"noble": "3020",
     * 						"grade": "1",
     * 						"gift_amount": 0,
     * 						"gift_start_time": 0,
     * 						"gift_end_time": 0,
     * 						"gift_pattern_id": -2,
     * 						"jump_mode_id": 0,
     * 						"is_vip": 0,
     * 						"is_skin": 0,
     * 						"is_rocket": 0,
     * 						"is_function": 0,
     * 						"type": "",
     * 						"url": "http://oss.3yakj.com/application_static_data/static_data/gift/9503.zip",
     * 						"is_show": "1",
     * 						"parent_id": 11,
     * 						"wealth_val": 1,
     * 						"tag_name": "",
     * 						"action": "0",
     * 						"validate": -1,
     * 						"is_meng_yan": "0",
     * 						"action_extend": {},
     * 						"top_left_corner_img": "",
     * 						"gradients_color": {
     * 							"l": "",
     * 							"r": ""
     *                        },
     * 						"data_type": "normal",
     * 						"jump_info": null,
     * 						"skin_list": []
     *                    }
     * 				]
     *            },
     * 		]
     * 	},
     * }
     * @param roomId 直播间ID
     * @return 礼物列表信息
     */
    public ApiResponse<GiftListResponse> getGiftList(Integer roomId,String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("keywords", "liveRoom");
        params.put("room_user_id", roomId);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + GET_GIFT_LIST_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse, GiftListResponse.class);
    }

    public ApiResponse<List<GiftDetail>> getRobotGiftList() {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();

        String url = configManager.getBusiness().getBaseUrl() + GET_ROBOT_GIFT_LIST;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponseList(jsonResponse, GiftDetail.class);
    }


    /**
     * 赠送热门礼物
     *
     * @param roomId   直播间ID
     * @param giftId   礼物ID
     * @param quantity 数量
     * @param receiver 接收者
     * @param token    令牌（可选，为空时使用配置的token）
     * @return 赠送结果
     */
    public ApiResponse<Object> giveHotGifts(Integer roomId, String giftId, int quantity, String receiver, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        if (roomId == null  || StrUtil.isBlank(giftId) || quantity <= 0) {
            throw new IllegalArgumentException("参数不完整或无效");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_id", roomId);
        params.put("gift_id", giftId);
        params.put("quantity", quantity);
        params.put("receiver", receiver);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + GIVE_HOT_GIFTS_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 赠送热门礼物（使用配置的token）
     *
     * @param roomId   直播间ID
     * @param giftId   礼物ID
     * @param quantity 数量
     * @param receiver 接收者
     * @return 赠送结果
     */
    public ApiResponse<Object> giveHotGifts(Integer roomId, String giftId, int quantity, String receiver) {
        return giveHotGifts(roomId, giftId, quantity, receiver, null);
    }

    /**
     * 获取热门奖励状态
     *
     * @param roomId 直播间ID
     * @param token  令牌（可选，为空时使用配置的token）
     * @return 热门奖励状态
     */
    public ApiResponse<Object> getHotAwardStatus(Integer roomId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        if (roomId == null ) {
            throw new IllegalArgumentException("直播间ID不能为空");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_id", roomId);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + GET_HOT_AWARD_STATUS_PATH;
        String response = requestManager.get(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 获取热门奖励状态（使用配置的token）
     *
     * @param roomId 直播间ID
     * @return 热门奖励状态
     */
    public ApiResponse<Object> getHotAwardStatus(Integer roomId) {
        return getHotAwardStatus(roomId, null);
    }

    /**
     * 获取热门奖励瓜分门槛
     *
     * @param roomId 直播间ID
     * @param token  令牌（可选，为空时使用配置的token）
     * @return 热门奖励门槛信息
     */
    public ApiResponse<Object> getHotDoorSill(Integer roomId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        if (roomId == null ) {
            throw new IllegalArgumentException("直播间ID不能为空");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_id", roomId);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + GET_HOT_DOOR_SILL_PATH;
        String response = requestManager.get(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 获取热门奖励瓜分门槛（使用配置的token）
     *
     * @param roomId 直播间ID
     * @return 热门奖励门槛信息
     */
    public ApiResponse<Object> getHotDoorSill(Integer roomId) {
        return getHotDoorSill(roomId, null);
    }

    /**
     * 申请余额
     *
     * @param userId 用户ID
     * @param amount 申请金额
     * @param token  用户令牌
     * @return 申请结果
     */
    public ApiResponse<Object> applyForBalance(Integer userId ,String reason, double amount, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        if (userId == null || amount <= 0) {
            throw new IllegalArgumentException("参数不完整或无效");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("amount", amount);
        params.put("reason", reason);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + APPLY_FOR_BALANCE_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     *
     * @param room_user_id
     * @param token
     * @return
     */
    public ApiResponse<List<Object>> getRoomOnlineUserList(Integer room_user_id ,String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", room_user_id);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + GET_ROOM_ONLINE_USER_LIST_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponseList(jsonResponse ,Object.class);
    }
    /**
     * 开始主播广播
     *
     * @param roomId 直播间ID
     * @param token  令牌（可选，为空时使用配置的token）
     * @return 广播结果
     * 
     */
    public ApiResponse<List<LiveRoom>> startBroadcastAnchor(Integer roomId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_id", roomId);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + START_BROADCAST_ANCHOR_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponseList(jsonResponse ,LiveRoom.class);
    }

    /**
     * 获取机器人资金池
     * @return
     */
    public ApiResponse<Double> getRobotFundPool() {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();

        String url = configManager.getBusiness().getBaseUrl() + GET_ROBOT_FUND_POOL_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse ,Double.class);
    }

    /**
     * 查询指令用户的信息
     * @param find_user_id
     * @return
     * {
     *     "code": 200,
     *     "msg": "success",
     *     "data": {
     *         "info": {
     *             "user_id": 7298,
     *             "is_mystery": 0,
     *             "user_number": 44210101,
     *             "nick_name": "danai",
     *             "follow_me_number": 0,
     *             "my_follow_num": 0,
     *             "head_portrait": "https://resources.test.brieftalk.cn/application_static_data/static_data/user/avatar/default/7298_1764829350.png",
     *             "general_play_count": 0,
     *             "personal_signature": "这个人很懒，什么都没留下。",
     *             "head_portrait_box": "",
     *             "gender": 0,
     *             "fans_num": 0,
     *             "is_achor": 0,
     *             "like_dynamic_num": 0,
     *             "user_dynamic_num": 0,
     *             "is_follow": 0,
     *             "video_give_up_num": 0,
     *             "display_like_list": 1,
     *             "is_show_like": 1,
     *             "display_follow_sta": 0,
     *             "talent_name": "",
     *             "confirm_name": "",
     *             "share_info": {
     *                 "open_type": "share",
     *                 "jump_address": {
     *                     "ios_url": "https://api.bmiss3.zhubei.cn/share/user?uid=7298&source=com.beishijie.begal",
     *                     "android_url": "https://api.bmiss3.zhubei.cn/share/user?uid=7298&source=com.beishijie.begal"
     *                 },
     *                 "extra": {
     *                     "title": "danai's Profile",
     *                     "cont": "这个人很懒，什么都没留下。 粉絲數:0",
     *                     "img": "https://resources.test.brieftalk.cn/application_static_data/static_data/user/avatar/default/7298_1764829350.png"
     *                 }
     *             },
     *             "is_showing": 0,
     *             "season_info": {
     *                 "rankName": "青銅Ⅲ",
     *                 "rankImageD": "https://resources.test.brieftalk.cn/application_static_data/static_data/season_level/qtd.png",
     *                 "currentStar": 0,
     *                 "totalStar": 3,
     *                 "key": "qt3"
     *             },
     *             "show_list": [
     *                 {
     *                     "path": "https://resources.test.brieftalk.cn/application_static_data/static_data/publicimg/public_bg.png",
     *                     "id": 1,
     *                     "path_violation": "0"
     *                 }
     *             ],
     *             "vip": {
     *                 "vip_status": 0,
     *                 "vip_icon": "",
     *                 "vip_grade": 0
     *             },
     *             "vip_img_info": null,
     *             "network_wealth_level": "https://resources.test.brieftalk.cn/application_static_data/static_data/wealth/wealth_7.png",
     *             "network_active_level": "https://resources.test.brieftalk.cn/application_static_data/static_data/new_active_level/level_6.png",
     *             "wealth_level_info": {
     *                 "level": 7,
     *                 "icon": "https://resources.test.brieftalk.cn/application_static_data/static_data/wealth/wealth_7.png",
     *                 "icon_large": "https://resources.test.brieftalk.cn/application_static_data/static_data/wealth/wealth_level_v2_1.png"
     *             },
     *             "active_level_info": {
     *                 "level": 6,
     *                 "icon": "https://resources.test.brieftalk.cn/application_static_data/static_data/new_active_level/level_6.png",
     *                 "icon_large": "https://resources.test.brieftalk.cn/application_static_data/static_data/level/user_level_big_1.png"
     *             },
     *             "advertisement_all": null,
     *             "advertisement_sta": 0,
     *             "label_data": [
     *                 {
     *                     "id": 41,
     *                     "name": "無肉不歡"
     *                 },
     *                 {
     *                     "id": 49,
     *                     "name": "起牀困難戶"
     *                 }
     *             ],
     *             "notes_status": 0,
     *             "industry": "",
     *             "emotion": 0,
     *             "location_sta": 1,
     *             "age_sta": 1,
     *             "anchor_title_sta": 1,
     *             "fan_card_sta": 1,
     *             "user_status": 0,
     *             "is_friend": 0,
     *             "city": "",
     *             "province": "",
     *             "age": "",
     *             "birthday": ""
     *         }
     *     }
     * }
     */
    public ApiResponse<OtherUserCenter> getOtherUserCenter(Integer find_user_id) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("find_user_id", find_user_id);

        String url = configManager.getBusiness().getBaseUrl() + GET_OTHER_USER_CENTER_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonObject = requestManager.parseEncryptedResponse(response);
        Integer code = jsonObject.getInt("code");
        String message = jsonObject.getStr("message");
        String msg = jsonObject.getStr("msg");
        JSONObject data = jsonObject.getJSONObject("data");
        Long timestamp = jsonObject.getLong("timestamp");

        ApiResponse<OtherUserCenter> result = new ApiResponse<>();
        result.setCode(code);
        result.setMessage(StrUtil.isNotBlank(message) ? message : msg);
        result.setMsg(StrUtil.isNotBlank(msg) ? msg : message);
        result.setTimestamp(timestamp != null ? timestamp : System.currentTimeMillis());
        if(result.isSuccess() && data != null){
            result.setData(JSONUtil.toBean(JSONUtil.toJsonStr(data.get("info")) ,OtherUserCenter.class));
        }
        return result;
    }

    /**
     *
     * @param user_number
     * @return
     */
    public ApiResponse<OtherUserCenter> searchForUserByNumber(Integer user_number) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("user_number", user_number);

        String url = configManager.getBusiness().getBaseUrl() + SEARCH_FOR_USER_BY_NUMBER_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonObject = requestManager.parseEncryptedResponse(response);
        Integer code = jsonObject.getInt("code");
        String message = jsonObject.getStr("message");
        String msg = jsonObject.getStr("msg");
        JSONObject data = jsonObject.getJSONObject("data");
        Long timestamp = jsonObject.getLong("timestamp");

        ApiResponse<OtherUserCenter> result = new ApiResponse<>();
        result.setCode(code);
        result.setMessage(StrUtil.isNotBlank(message) ? message : msg);
        result.setMsg(StrUtil.isNotBlank(msg) ? msg : message);
        result.setTimestamp(timestamp != null ? timestamp : System.currentTimeMillis());
        if(result.isSuccess() && data != null){
            result.setData(JSONUtil.toBean(JSONUtil.toJsonStr(data) ,OtherUserCenter.class));
        }
        return result;
    }

    public ApiResponse getLiveRoomCurrentState(Integer room_user_id,String clientId ,String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("room_user_id", room_user_id);
        params.put("client_id", clientId);
        params.put("token", token);

        String url = configManager.getBusiness().getBaseUrl() + GET_LIVE_ROOM_CURRENT_STATE_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
    }

    /**
     * 开始主播广播（使用配置的token）
     *
     * @param roomId 直播间ID
     * @return 广播结果
     */
    public ApiResponse<List<LiveRoom>> startBroadcastAnchor(Integer roomId) {
        return startBroadcastAnchor(roomId, null);
    }

    /**
     * 检查用户是否已登录
     *
     * @param userId 用户ID
     * @param token  用户令牌
     * @return 是否已登录
     */
    public boolean isLoggedIn(Integer userId, String token) {
        return userId != null && StrUtil.isNotBlank(token);
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户ID
     * @param token  用户令牌
     * @return 用户信息
     */
    public JSONObject getUserInfo(Integer userId, String token) {
        JSONObject userInfo = new JSONObject();
        userInfo.put("user_id", userId);
        userInfo.put("token", token);
        userInfo.put("logged_in", isLoggedIn(userId, token));
        return userInfo;
    }

    /**
     * 验证响应是否成功
     *
     * @param response 响应对象
     * @return 是否成功
     */
    public boolean isSuccess(ApiResponse<Object> response) {
        if (response == null) {
            return false;
        }

        Integer code = response.getCode();
        return code != null && code == 200;
    }

    /**
     * 获取响应消息
     *
     * @param response 响应对象
     * @return 响应消息
     */
    public String getMessage(ApiResponse<Object> response) {
        if (response == null) {
            return "响应为空";
        }

        String message = response.getMessage();
        return StrUtil.isNotBlank(message) ? message : "未知消息";
    }

    /**
     * 获取响应数据
     *
     * @param response 响应对象
     * @return 响应数据
     */
    public JSONObject getData(ApiResponse<Object> response) {
        if (response == null) {
            return new JSONObject();
        }

        Object data = response.getData();
        if (data instanceof JSONObject) {
            return (JSONObject) data;
        }

        return new JSONObject();
    }

    /**
     * 开启ASR解析
     *
     * @param userId 主播ID
     * @param token 令牌（可选，为空时使用配置的token）
     * @return 操作结果
     */
    public ApiResponse<Object> startAsr(Integer userId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + ASR_START_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
//        return ApiResponse.success(null);
    }

    /**
     * 开启ASR解析（使用配置的token）
     *
     * @param userId 主播ID
     * @return 操作结果
     */
    public ApiResponse<Object> startAsr(Integer userId) {
        return startAsr(userId, null);
    }

    /**
     * 结束ASR解析
     *
     * @param userId 主播ID
     * @param token 令牌（可选，为空时使用配置的token）
     * @return 操作结果
     */
    public ApiResponse<Object> endAsr(Integer userId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + ASR_END_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);
        return convertToApiResponse(jsonResponse);
//        return ApiResponse.success(null);
    }

    /**
     * 结束ASR解析（使用配置的token）
     *
     * @param userId 主播ID
     * @return 操作结果
     */
    public ApiResponse<Object> endAsr(Integer userId) {
        return endAsr(userId, null);
    }

    /**
     * 获取直播间主播语音解析结果
     *
     * @param showId 直播场次ID
     * @param token 令牌（可选，为空时使用配置的token）
     * @return 语音解析结果
     */
    public ApiResponse<List<AsrSpeechText>> getAsrSpeechText(Integer showId, String token) {
        if (!configManager.isBusinessApiConfigValid()) {
            throw new IllegalStateException("业务API配置不完整");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("show_id", showId);
        params.put("token", getToken(token));

        String url = configManager.getBusiness().getBaseUrl() + ASR_GET_SPEECH_TEXT_PATH;
        String response = requestManager.post(url, params);

        JSONObject jsonResponse = requestManager.parseEncryptedResponse(response);

        // 使用AsrSpeechText实体类来处理语音解析结果
        return convertToApiResponseList(jsonResponse, AsrSpeechText.class);

//        //模拟随机返回一些数据，每次调用的数据和时间都不一样，每次返回5条
//        List<AsrSpeechText> asrSpeechTexts = new ArrayList<>();
//        int currentTime = (int)(System.currentTimeMillis() /1000);
//
//        for (int i = 0; i < 5; i++) {
//            AsrSpeechText asrSpeechText = new AsrSpeechText();
//
//            // 生成一个不超过60秒的随机时间偏移（单位：秒）
//            int randomOffset = new Random().nextInt(6000);
//
//            // 设置时间为当前时间减去随机偏移
//            asrSpeechText.setTime(currentTime - randomOffset);
//
//            asrSpeechText.setContent("这是第" + i + "条语音解析结果");
//            asrSpeechTexts.add(asrSpeechText);
//        }
//
//        return ApiResponse.success(asrSpeechTexts);
    }

    /**
     * 获取直播间主播语音解析结果（使用配置的token）
     *
     * @param showId 直播场次ID
     * @return 语音解析结果
     */
    public ApiResponse<List<AsrSpeechText>> getAsrSpeechText(Integer showId) {
        return getAsrSpeechText(showId, null);
    }

    /**
     * 便捷方法：快速登录用户
     *
     * @param configManager  配置管理器
     * @param requestManager 请求管理器
     * @param username       用户名
     * @param password       密码
     * @return 登录结果
     */
    public static ApiResponse<Object> quickLogin(ConfigManager configManager, RequestManager requestManager,
                                                 String username, String password) {
        BusinessService service = new BusinessService();

        // 使用反射设置依赖（在实际项目中，这应该通过依赖注入）
        try {
            java.lang.reflect.Field configField = BusinessService.class.getDeclaredField("configManager");
            configField.setAccessible(true);
            configField.set(service, configManager);

            java.lang.reflect.Field requestField = BusinessService.class.getDeclaredField("requestManager");
            requestField.setAccessible(true);
            requestField.set(service, requestManager);
        } catch (Exception e) {
            throw new RuntimeException("设置依赖失败", e);
        }

        return service.login(username, password);
    }
}