package com.zhentao.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.dto.BlockDto;
import com.zhentao.entity.ChatFriend;
import com.zhentao.service.ChatConversationService;
import com.zhentao.service.ChatFriendService;
import com.zhentao.mapper.ChatFriendMapper;
import com.zhentao.vo.GetblockVo;
import com.zhentao.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 26621
* @description 针对表【chat_friend(好友关系表)】的数据库操作Service实现
* @createDate 2025-11-27 14:04:39
*/
@Service
public class ChatFriendServiceImpl extends ServiceImpl<ChatFriendMapper, ChatFriend>
    implements ChatFriendService{
    @Autowired
    private ChatConversationService chatConversationService;


    @Override
    public ResultVo block(BlockDto blockDto) {
//        QueryWrapper<ChatFriend> chatFriendQueryWrapper = new QueryWrapper<>();
//        chatFriendQueryWrapper.lambda()
//                .eq(ChatFriend::getUserId,blockDto.getUserId())
//                .eq(ChatFriend::getFriendId,blockDto.getTargetUserId());

        ChatFriend chatFriends = this.baseMapper.selectOneall(blockDto.getUserId(),blockDto.getTargetUserId());

        if (chatFriends == null){
            ChatFriend chatFriend = new ChatFriend();
            chatFriend.setId(IdUtil.getSnowflake().nextId());
            chatFriend.setUserId(blockDto.getUserId());
            chatFriend.setFriendId(blockDto.getTargetUserId());
            chatFriend.setFriendAvatar(blockDto.getTargetUserAvatar());
            chatFriend.setFriendName(blockDto.getTargetUserName());
            chatFriend.setCreateTime(new Date());
            chatFriend.setUpdateTime(new Date());
            chatFriend.setStatus(2);

            int insert = this.baseMapper.insert(chatFriend);
            if (insert > 0){
                deleteChatConversation(blockDto);
                return ResultVo.success("拉黑成功");
            }
        }
        if (chatFriends.getStatus() == 2 && chatFriends.getIsDeleted() == 0){
            deleteChatConversation(blockDto);

            return ResultVo.success("拉黑成功");

        }
        chatFriends.setStatus(2);
        chatFriends.setIsDeleted(0);
        int i = this.baseMapper.updateByIdone(chatFriends.getId(),
                2,  // status=2（拉黑）
                0,  // is_deleted=0（未删除）
                new Date());
        if (i > 0){
            deleteChatConversation(blockDto);

            return ResultVo.success("拉黑成功");
        }
        return ResultVo.fail("拉黑失败");
    }

    @Override
    public ResultVo getBlacklist(Long userId) {
        QueryWrapper<ChatFriend> chatFriendQueryWrapper = new QueryWrapper<>();
        chatFriendQueryWrapper.lambda()
                .eq(ChatFriend::getUserId,userId)
                .eq(ChatFriend::getStatus,2)
                .eq(ChatFriend::getIsDeleted,0);
        ;
        List<ChatFriend> chatFriends = this.baseMapper.selectList(chatFriendQueryWrapper);
        if (CollUtil.isEmpty(chatFriends)){
            return ResultVo.success("success");
        }
        List<GetblockVo> getblockVoList = new ArrayList<>();
        for (ChatFriend chatFriend : chatFriends) {
            GetblockVo getblockVo = new GetblockVo();
            getblockVo.setUserId(chatFriend.getFriendId());
            getblockVo.setCreateTime(chatFriend.getCreateTime());
            getblockVoList.add(getblockVo);
        }
        return ResultVo.success("success",getblockVoList);
    }

    @Override
    public ResultVo isTargetBlockedMe(String targetUserId, String userId) {
        QueryWrapper<ChatFriend> chatFriendQueryWrapper = new QueryWrapper<>();
        chatFriendQueryWrapper.lambda().eq(ChatFriend::getUserId,targetUserId).eq(ChatFriend::getFriendId,userId).eq(ChatFriend::getStatus,2).eq(ChatFriend::getIsDeleted,0);
        List<ChatFriend> chatFriends = this.baseMapper.selectList(chatFriendQueryWrapper);
        if (CollUtil.isEmpty(chatFriends)){
            return ResultVo.success("success",false);
        }
        return ResultVo.success("success",true);
    }

    @Override
    public ResultVo getblocklist(Long userId) {
        QueryWrapper<ChatFriend> chatFriendQueryWrapper = new QueryWrapper<>();
        chatFriendQueryWrapper.lambda().eq(ChatFriend::getUserId,userId).eq(ChatFriend::getStatus,2).eq(ChatFriend::getIsDeleted,0);
        List<ChatFriend> chatFriends = this.baseMapper.selectList(chatFriendQueryWrapper);
//        if (CollUtil.isEmpty(chatFriends)){
//
//        }
        return ResultVo.success("success",chatFriends);
    }

    @Override
    public boolean removeFromBlacklist(Long userId, Long blockedUserId) {
        // 1. 查询拉黑记录
        LambdaQueryWrapper<ChatFriend> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getFriendId, blockedUserId)
                .eq(ChatFriend::getStatus, 2); // status=2表示拉黑状态

        ChatFriend chatFriend = this.getOne(queryWrapper);

        if (chatFriend == null) {
            return false; // 未找到拉黑记录
        }

        // 更新状态：解除拉黑（根据业务需求二选一）

        chatFriend.setStatus(1); // 0-正常 1-删除 2-拉黑
        chatFriend.setUpdateTime(new Date());


        // chatFriend.setIsDeleted(1);
        // chatFriend.setUpdateTime(new Date());

        return this.updateById(chatFriend);
    }



    public void deleteChatConversation(BlockDto dto){
        chatConversationService.deleteChatConversation(dto);
    }
}




