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

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.soopin.member.domain.po.Fans;
import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.domain.vo.FansVO;
import com.wzj.soopin.member.mapper.FansMapper;
import com.wzj.soopin.member.mapper.MemberMapper;
import com.wzj.soopin.member.service.IFansService;
import com.wzj.soopin.member.service.IMemberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.CacheConstants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.enums.YesOrNo;
import org.dromara.common.core.utils.StringUtils;
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.redis.RedisCache;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
@RequiredArgsConstructor
public class FansServiceImpl extends ServiceImpl<FansMapper, Fans> implements IFansService {


    private final RedisCache redisCache;

    private final MemberMapper memberMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean doFollow(Long myId, Long vloggerId) {
        // 幂等性校验：已存在则不再插入

        Fans existing = queryFansRelationship(myId, vloggerId);
        if (existing != null) {
            return true;
        }

        Fans fans = new Fans();
        fans.setFanId(myId);
        fans.setVloggerId(vloggerId);

        // 判断对方是否关注我，如果关注我，那么双方都要互为朋友关系
        Fans vloger = queryFansRelationship(vloggerId, myId);
        if (vloger != null) {
            fans.setFriendFlag(YesOrNo.YES.type);
            fans.setBothFriend(YesOrNo.YES.type);
            vloger.setFriendFlag(YesOrNo.YES.type);
            vloger.setBothFriend(YesOrNo.YES.type);
            baseMapper.updateById(vloger);
        } else {
            fans.setFriendFlag(YesOrNo.YES.type);
        }
        baseMapper.insert(fans);
        MqUtil.sendIMMessage(buildMessage(fans));
        return true;
    }


    private MQMessage buildMessage(Fans fans) {
        // 推送关注消息
        Member follower = memberMapper.selectById(fans.getFanId());
        Member vlogger = memberMapper.selectById(fans.getVloggerId());
        // 新版：使用模板类型编号和参数
        Map<String, Object> params = new HashMap<>();
        params.put("userId", follower.getId());
        params.put("nickname", follower.getNickname() == null ? "" : follower.getNickname());
        params.put("faceUrl", vlogger.getAvatar()  );
        params.put("action", MessageActionEnum.NEW_FOUCS.getAccount());
        params.put("toUserId", vlogger.getId());
        MQMessage message = MQMessage.builder()
            .messageType("follow")
            .data(params)
            .source("member")
            .build();
        return message;
    }

    public Fans queryFansRelationship(Long fanId, Long vlogerId) {
        LambdaQueryWrapper<Fans> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Fans::getVloggerId, vlogerId)
            .eq(Fans::getFanId, fanId);

        List<Fans> fansList = baseMapper.selectList(queryWrapper);
        if (fansList.isEmpty()) {
            return null;
        }
        return fansList.get(0);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean doCancel(Long myId, Long vloggerId) {
        // 判断我们是否朋友关系，如果是，则需要取消双方的关系
        Fans fan = queryFansRelationship(myId, vloggerId);
        if (fan != null && YesOrNo.YES.type.equals(fan.getFriendFlag())) {
            // 抹除双方的朋友关系，自己的关系删除即可
            Fans pendingFan = queryFansRelationship(vloggerId, myId);
            if (pendingFan != null) {
                pendingFan.setBothFriend(YesOrNo.NO.type);
                baseMapper.updateById(pendingFan);
            } else {
                log.warn("取消关注时未找到对方的粉丝关系，myId={}, vloggerId={}", vloggerId, myId);
            }
        }
        // 删除自己的关注关联表记录
        if (fan != null) {
            LambdaQueryWrapper<Fans> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(Fans::getId, fan.getId());
            baseMapper.delete(deleteWrapper);
        } else {
            log.warn("取消关注时未找到自己的粉丝关系，myId={}, vloggerId={}", myId, vloggerId);
            return true;
        }
        // 博主的粉丝-1，我的关注-1
        RedisUtils.decrAtomicValue(CacheConstants.MEMBER_FANS + ":" + vloggerId);
        RedisUtils.decrAtomicValue(CacheConstants.MEMBER_FOLLOW + ":" + myId);
        // 推送取关消息
        Member follower = memberMapper.selectById(myId);
        Member vlogger = memberMapper.selectById(vloggerId);
        if (follower != null && vlogger != null && !myId.equals(vloggerId)) {
// 新版：使用模板类型编号和参数
            Map<String, Object> params = new HashMap<>();
            params.put("userId", follower.getUserId());
            params.put("nickname", follower.getNickname() == null ? "" : follower.getNickname());
            params.put("faceUrl", vlogger.getAvatar()  );
            params.put("action", MessageActionEnum.NEW_FOUCS.getAccount());
            params.put("toUserId", vloggerId);
            MQMessage message = MQMessage.builder()
                .messageType("follow")
                .data(params)
                .source("member")
                .build();
            // 关注消息
            MqUtil.sendIMMessage(message);
        }
        return true;
    }

    @Override
    public boolean queryDoIFollowVloger(Long myId, Long vloggerId) {
        Fans vlogger = queryFansRelationship(myId, vloggerId);
        return vlogger != null;
    }

    @Override
    public boolean queryDoIFollowVloger(String myId, String vloggerId) {
        try {
            // Try to convert string IDs to Long if they are numeric
            if (myId != null && vloggerId != null &&
                myId.matches("\\d+") && vloggerId.matches("\\d+")) {
                Fans vlogger = queryFansRelationship(Long.valueOf(myId), Long.valueOf(vloggerId));
                return vlogger != null;
            } else {
                // If IDs contain non-numeric characters, return false for now
                // This prevents the NumberFormatException
                log.warn("Cannot convert string IDs to Long: myId={}, vloggerId={}", myId, vloggerId);
                return false;
            }
        } catch (NumberFormatException e) {
            log.warn("Failed to convert string IDs to Long: myId={}, vloggerId={}", myId, vloggerId, e);
            return false;
        }
    }

    @Override
    public IPage<FansVO> queryMyFans(Long myId, Integer pageNo, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("myId", myId);
        // 查询粉丝列表
        Page<FansVO> page = new Page<>();
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        for (FansVO f : page.getRecords()) {
            String relationship = redisCache.getCacheObject(
                CacheConstants.MEMBER_FANS + ":" + myId + ":" + f.getFan().getId());
            if (StringUtils.isNotBlank(relationship) && relationship.equalsIgnoreCase("1")) {
                f.setFriendFlag(YesOrNo.YES.type);
            }
        }

        return null;
    }

    @Override
    public Long countFansByVloggerId(Long vloggerId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Fans>().eq(Fans::getVloggerId, vloggerId));
    }

    // 拉黑前只删除“我关注对方”的关系
    @Override
    public void removeFansRelationship(Long myId, Long vloggerId) {
        Fans fan = queryFansRelationship(myId, vloggerId);
        if (fan != null) {
            baseMapper.deleteById(fan.getId());
        }
    }


    //从缓存中获取我的关注列表

}
