package com.wzj.soopin.member.service.impl;

import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.domain.vo.IMCallbackVO;
import com.wzj.soopin.member.service.IFansService;
import com.wzj.soopin.member.service.IMCallbackService;
import com.wzj.soopin.member.service.IMemberBlockService;
import com.wzj.soopin.member.service.IMemberService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.dromara.common.core.constant.CacheConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.mq.domain.MQMessage;
import org.dromara.common.mq.enums.MessageActionEnum;
import org.dromara.common.mq.utils.MqUtil;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
@Slf4j
public class IMCallbackServiceImpl implements IMCallbackService {
    private final IFansService fansService;
    private final IMemberBlockService memberBlockService;
    private final IMemberService memberService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public IMCallbackVO handleImFollow(Map<String, Object> callbackData) {
        // 幂等性校验：已存在则不再插入
        // 1. IM回调格式
        if (callbackData != null && callbackData.containsKey("CallbackCommand")) {
            log.info("收到IM关注回调: {}", callbackData);

            // 1.1 兼容腾讯IM的 PairList 回调格式
            Object pairListObj = callbackData.get("PairList");
            if (pairListObj instanceof List) {
                List<?> pairList = (List<?>) pairListObj;
                for (Object pairObj : pairList) {
                    if (pairObj instanceof Map) {
                        Map<?, ?> pair = (Map<?, ?>) pairObj;
                        Object fromAccountObj = pair.get("From_Account");
                        Object toAccountObj = pair.get("To_Account");
                        if (fromAccountObj != null && toAccountObj != null) {
                            Long fromId = null;
                            Long toId = null;
                            try {
                                fromId = Long.valueOf(fromAccountObj.toString());
                                toId = Long.valueOf(toAccountObj.toString());
                            } catch (Exception e) {
                                log.warn("IM回调Pair参数转换失败: {}", pair);
                                continue;
                            }
                            fansService.doFollow(fromId, toId);
                            log.info("IM回调处理成功: fromId={}, vloggerId={}", fromId, toId);
                        } else {
                            log.warn("IM回调Pair参数不完整: {}", pair);
                        }
                    }
                }
                // 返回IM平台要求的应答
                return IMCallbackVO.success();
            }

            // 1.2 兼容原有 FollowList 格式
            String fromAccount = (String) callbackData.get("From_Account");
            List<Map<String, String>> followList = (List<Map<String, String>>) callbackData.get("FollowList");
            if (fromAccount != null && followList != null) {
                Long fromId = Long.valueOf(fromAccount.replace("UserID_", ""));
                List<Long> vloggerIds = new java.util.ArrayList<>();
                for (Map<String, String> follow : followList) {
                    String toAccount = follow.get("To_Account");
                    fansService.doFollow(fromId, Long.valueOf(toAccount.replace("UserID_", "")));
                }

                log.info("IM回调处理成功: fromId={}, vloggerIds={}", fromId, vloggerIds);
            } else {
                log.warn("IM回调参数不完整: {}", callbackData);
            }
            return IMCallbackVO.success();
        }
        // 2. 兼容JSON方式传递myId和vloggerId
        if (callbackData != null && callbackData.containsKey("myId") && callbackData.containsKey("vloggerId")) {
            log.info("收到JSON关注回调: {}", callbackData);
            Object myIdObj = callbackData.get("myId");
            Object vloggerIdObj = callbackData.get("vloggerId");
            if (myIdObj != null && vloggerIdObj != null) {
                Long myIdVal = Long.valueOf(myIdObj.toString());
                Long vloggerIdVal = Long.valueOf(vloggerIdObj.toString());
                fansService.doFollow(myIdVal, vloggerIdVal);

                log.info("JSON回调处理成功: myId={}, vloggerId={}", myIdVal, vloggerIdVal);
                return IMCallbackVO.success();
            } else {
                log.warn("JSON回调参数不完整: {}", callbackData);
            }
        }
        return IMCallbackVO.success();
    }


    @Override
    public IMCallbackVO handleImCancelFollow(Map<String, Object> callbackData) {
        // 1. 判断是否为IM回调格式
        if (callbackData != null && callbackData.containsKey("CallbackCommand")) {
            log.info("收到IM取消关注回调: {}", callbackData);

            // 1.1 兼容腾讯IM的 PairList 回调格式
            Object pairListObj = callbackData.get("PairList");
            log.info("PairList 类型: {}, 内容: {}", pairListObj != null ? pairListObj.getClass() : "null", pairListObj);
            if (pairListObj instanceof List) {
                List<?> pairList = (List<?>) pairListObj;
                for (Object pairObj : pairList) {
                    if (pairObj instanceof Map) {
                        Map<?, ?> pair = (Map<?, ?>) pairObj;
                        Object fromAccountObj = pair.get("From_Account");
                        Object toAccountObj = pair.get("To_Account");
                        if (fromAccountObj != null && toAccountObj != null) {
                            Long fromId = null;
                            Long toId = null;
                            try {
                                fromId = Long.valueOf(fromAccountObj.toString());
                                toId = Long.valueOf(toAccountObj.toString());
                            } catch (Exception e) {
                                log.warn("IM回调Pair参数转换失败: {}", pair);
                                continue;
                            }
                            fansService.doCancel(fromId, toId);
                            log.info("IM取消关注回调处理成功: fromId={}, toId={}", fromId, toId);
                        } else {
                            log.warn("IM取消关注回调Pair参数不完整: {}", pair);
                        }
                    } else {
                        log.warn("PairList元素不是Map: {}", pairObj);
                    }
                }
                // 返回IM平台要求的应答

                return IMCallbackVO.success();
            } else {
                log.warn("PairList 不是 List 类型: {}", pairListObj);
            }

            // 1.2 兼容原有 To_Account 逻辑
            String fromAccount = (String) callbackData.get("From_Account");
            List<String> toAccounts = null;
            // 兼容腾讯IM的 To_Account 可能是 List<String> 或 List<Map<String, String>>
            Object toAccountObj = callbackData.get("To_Account");
            if (toAccountObj instanceof List) {
                List<?> list = (List<?>) toAccountObj;
                if (!list.isEmpty() && list.get(0) instanceof String) {
                    toAccounts = (List<String>) list;
                } else if (!list.isEmpty() && list.get(0) instanceof Map) {
                    // 兼容部分IM平台格式
                    toAccounts = new java.util.ArrayList<>();
                    for (Object obj : list) {
                        Map<?, ?> map = (Map<?, ?>) obj;
                        Object acc = map.get("To_Account");
                        if (acc != null) toAccounts.add(acc.toString());
                    }
                }
            }
            if (fromAccount != null && toAccounts != null) {
                Long fromId = Long.valueOf(fromAccount.replace("UserID_", ""));
                for (String toAccount : toAccounts) {
                    Long toId = Long.valueOf(toAccount.replace("UserID_", ""));
                    fansService.doCancel(fromId, toId);
                }
                log.info("IM取消关注回调处理成功: fromId={}, toAccounts={}", fromId, toAccounts);
            } else {
                log.warn("IM取消关注回调参数不完整: {}", callbackData);
            }
            // 返回IM平台要求的应答
          return IMCallbackVO.success();
        }
        return IMCallbackVO.success();

    }



    // 资料修改回调处理逻辑
    @Override
    public IMCallbackVO handleProfileCallbackPortraitSet(Map<String, Object> callbackData) {
        log.info("收到IM用户资料更新回调: {}", callbackData);
        String fromAccount = (String) callbackData.get("From_Account");
        List<Map<String, Object>> profileItems = (List<Map<String, Object>>) callbackData.get("ProfileItem");
        if (fromAccount != null && profileItems != null) {
            Long userId = null;
            try {
                userId = Long.valueOf(fromAccount.replace("UserID_", ""));
            } catch (Exception e) {
                log.warn("用户ID转换失败: {}", fromAccount);
            }
            if (userId != null) {
                Member memberToUpdate = memberService.getById(userId);
                if (memberToUpdate != null) {
                    for (Map<String, Object> item : profileItems) {
                        String tag = (String) item.get("Tag");
                        Object value = item.get("Value");
                        updateMemberProfile(memberToUpdate, tag, value);
                    }
                    memberService.updateById(memberToUpdate);
                    log.info("IM用户资料更新回调处理成功: userId={}, profileItems={}", userId, profileItems);
                } else {
                    log.warn("IM用户资料更新回调中用户不存在: userId={}", userId);
                }
            }
        } else {
            log.warn("IM用户资料更新回调参数不完整: {}", callbackData);
        }
        return IMCallbackVO.success();
    }

    // 只更新 nickname/gender 字段
    private void updateMemberProfile(Member member, String tag, Object value) {
        if (tag == null || value == null) {
            return;
        }
        switch (tag) {
            case "Tag_Profile_IM_Nick":
                member.setNickname(value.toString());
                break;
            case "Tag_Profile_IM_Gender":
                if ("Gender_Type_Male".equals(value)) {
                    member.setGender(1);
                } else if ("Gender_Type_Female".equals(value)) {
                    member.setGender(2);
                } else {
                    member.setGender(0);
                }
                break;
            default:
                log.debug("未处理的用户资料字段: tag={}, value={}", tag, value);
                break;
        }
    }

    // 处理IM黑名单添加事件
    @Override
    public IMCallbackVO handleImAddBlock(Map<String, Object> requestBody) {
        Object pairListObj = requestBody.get("PairList");
        if (pairListObj instanceof List) {
            List<?> pairList = (List<?>) pairListObj;
            for (Object pairObj : pairList) {
                if (pairObj instanceof Map) {
                    Map<?, ?> pair = (Map<?, ?>) pairObj;
                    Object fromAccountObj = pair.get("From_Account");
                    Object toAccountObj = pair.get("To_Account");
                    if (fromAccountObj != null && toAccountObj != null) {
                        try {
                            Long myId = Long.valueOf(fromAccountObj.toString());
                            Long vloggerId = Long.valueOf(toAccountObj.toString());
                            // 1. 判断两个id不能为空
                            if (myId == null || vloggerId == null) {
                                log.warn("黑名单回调参数id为空: myId={}, vloggerId={}", myId, vloggerId);
                                continue;
                            }
                            // 2. 是否已经存在关注关系
                            boolean flow = fansService.queryDoIFollowVloger(myId, vloggerId);
                            if (flow) {
                                // 删除关注
                                fansService.doCancel(myId, vloggerId);
                                // 博主的粉丝-1，我的关注-1
                                RedisUtils.decrAtomicValue(CacheConstants.MEMBER_FANS + ":" + vloggerId);
                                RedisUtils.decrAtomicValue(CacheConstants.MEMBER_FOLLOW + ":" + myId);
                            }
                            // 3. 检查是否已在黑名单中
                            boolean hasblock = memberBlockService.hasBlocked(myId, vloggerId);
                            if (hasblock) {
                                log.info("用户{}已拉黑{}", myId, vloggerId);
                                continue;
                            }
                            // 4. 拉黑
                            memberBlockService.addBlock(myId, vloggerId);
                            log.info("用户{}成功拉黑{}", myId, vloggerId);
                        } catch (Exception e) {
                            log.warn("黑名单回调参数转换失败: {}", pair);
                        }
                    }
                }
            }
        }
        return IMCallbackVO.success();
    }


    // 处理IM取消拉黑事件
    @Override
    public IMCallbackVO handleImCancelBlock(Map<String, Object> requestBody) {
        Object pairListObj = requestBody.get("PairList");
        if (pairListObj instanceof List) {
            List<?> pairList = (List<?>) pairListObj;
            for (Object pairObj : pairList) {
                if (pairObj instanceof Map) {
                    Map<?, ?> pair = (Map<?, ?>) pairObj;
                    Object fromAccountObj = pair.get("From_Account");
                    Object toAccountObj = pair.get("To_Account");
                    if (fromAccountObj != null && toAccountObj != null) {
                        try {
                            Long myId = Long.valueOf(fromAccountObj.toString());
                            Long vloggerId = Long.valueOf(toAccountObj.toString());
                            if (myId == null || vloggerId == null) {
                                log.warn("取消拉黑回调参数id为空: myId={}, vloggerId={}", myId, vloggerId);
                                continue;
                            }
                            memberBlockService.removeBlock(myId, vloggerId);
                            log.info("用户{}已取消拉黑{}", myId, vloggerId);
                        } catch (Exception e) {
                            log.warn("取消拉黑回调参数转换失败: {}", pair);
                        }
                    }
                }
            }
        }
        return IMCallbackVO.success();
    }
}
