package shop.alien.store.service.impl;

import com.alibaba.fastjson2.JSONObject;
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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifeBlacklistVo;
import shop.alien.entity.store.vo.LifeFansVo;
import shop.alien.entity.store.vo.LifeMessageVo;
import shop.alien.mapper.*;
import shop.alien.store.service.LifeMessageService;
import shop.alien.store.service.LifeUserService;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.common.constant.LawyerStatusEnum;
import shop.alien.util.type.LifeFansIdentityQuery;
import shop.alien.util.type.LifeMessageUtil;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.util.type.PhoneTypeIdResult;
import shop.alien.util.type.TypeUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class LifeMessageServiceImpl extends ServiceImpl<LifeMessageMapper, LifeMessage> implements LifeMessageService {

    private final LifeMessageMapper lifeMessageMapper;
    private final LifeFansMapper fansMapper;
    private final LifeFansMapper lifeFansMapper;
    private final LifeUserMapper lifeUserMapper;
    private final StoreUserServiceImpl storeUserService;
    private final StoreImgServiceImpl storeImgService;
    private final LifeUserService lifeUserService;
    private final LifeMessageNotDisturbMapper lifeMessageNotDisturbMapper;
    private final LifeBlacklistMapper lifeBlacklistMapper;
    private final LifeNoticeMapper lifeNoticeMapper;
    private final LawyerUserMapper lawyerUserMapper;
    private final LawyerConsultationOrderMapper lawyerConsultationOrderMapper;

    private final LifeMessageUtil lifeMessageUtil;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final TypeUtil typeUtil;

    @Override
    public List<LifeMessageVo> getMessageList(String receiverId, int friendType, String search ,String userName) throws Exception {
        try {
            if (receiverId == null) {
                return new ArrayList<>();
            }
            String blockerType = "user".equals(Objects.requireNonNull(JwtUtil.getCurrentUserInfo()).getString("userType")) ? "2" : "1";
            String blockerId = JwtUtil.getCurrentUserInfo().getString("userId");
            QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
            wrapper.eq("message.num", 1);
            // 过滤拉黑
            wrapper.apply("(user.id not in ( " +
                    "     select blocked_id from life_blacklist " +
                    "     where blocker_type = '" + blockerType + "' and blocker_id = '" + blockerId + "' and blocked_type = '2' and delete_flag = 0 " +
                    ") or user.id is null)");
            wrapper.apply("(suser.id not in ( " +
                    "     select blocked_id from life_blacklist " +
                    "     where blocker_type = '" + blockerType + "' and blocker_id = '" + blockerId + "' and blocked_type = '1' and delete_flag = 0 " +
                    ") or suser.id is null)");

            // 通过搜索查询的情况下  不区分是否聊过  搜索所有消息
            if (0 == friendType && StringUtil.isNotEmpty(search)) {
                wrapper.apply("(user.user_name like '%" + search + "%' or suser.name like '%" + search + "%' or sinfo.store_name like '%" + search + "%')");
                // 聊过
            } else if (1 == friendType) {
                wrapper.apply("message.phoneId in ( " + lifeMessageUtil.sqlDistinctReceiverIdsBySender(receiverId) + ")");
                // 没聊过
            } else if (2 == friendType) {
                wrapper.apply("message.phoneId not in ( " + lifeMessageUtil.sqlDistinctReceiverIdsBySender(receiverId) + ")");
            }
            wrapper.orderByDesc("message.created_time");
            PhoneTypeIdResult participant = lifeMessageUtil.resolveIdentity(receiverId);
            Integer participantUserType = participant != null ? participant.getType() : -1;
            Integer participantRefId = participant != null ? participant.getId() : -1;
            List<LifeMessageVo> lifeMessagePageList = lifeMessageMapper.getLifeMessagePageByPhoneId(
                    receiverId, participantUserType, participantRefId, wrapper);
            List<LifeMessageVo> lifeMessagePageResultList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(lifeMessagePageList)) {
                boolean currentIsUser = receiverId != null && receiverId.startsWith("user_");
                boolean currentIsLawyer = receiverId != null && receiverId.startsWith("lawyer_");
                Integer currentUserId = null;
                Integer currentLawyerId = null;
                if (currentIsUser) {
                    LifeUser currentUser = lifeUserMapper.selectOne(new QueryWrapper<LifeUser>()
                            .eq("user_phone", receiverId.substring(5)));
                    currentUserId = currentUser != null ? currentUser.getId() : null;
                } else if (currentIsLawyer) {
                    LawyerUser currentLawyer = lawyerUserMapper.selectOne(new QueryWrapper<LawyerUser>()
                            .eq("phone", receiverId.substring(7)));
                    currentLawyerId = currentLawyer != null ? currentLawyer.getId() : null;
                }
                Map<String, String> chatEnabledCache = new HashMap<>();

                // 当前用户的所有关注
                LifeFansIdentityQuery.Scope receiverScope = LifeFansIdentityQuery.resolve(receiverId, typeUtil);
                LambdaQueryWrapper<LifeFans> followWrapper = new LambdaQueryWrapper<>();
                followWrapper.eq(LifeFans::getDeleteFlag, 0);
                LifeFansIdentityQuery.applyFansSide(followWrapper, receiverScope);
                List<LifeFans> followList = fansMapper.selectList(followWrapper);
                List<String> followIds = followList.stream().map(LifeFans::getFollowedId).collect(Collectors.toList());

                // 当前用户的所有粉丝
                LambdaQueryWrapper<LifeFans> fansWrapper = new LambdaQueryWrapper<>();
                fansWrapper.eq(LifeFans::getDeleteFlag, 0);
                LifeFansIdentityQuery.applyFollowedSide(fansWrapper, receiverScope);
                List<LifeFans> fansList = fansMapper.selectList(fansWrapper);
                List<String> fansIds = fansList.stream().map(LifeFans::getFansId).collect(Collectors.toList());

                // 查询所有未读消息
                LambdaQueryWrapper<LifeMessage> messageWrapper = new LambdaQueryWrapper<>();
                lifeMessageUtil.applyReceiverQuery(messageWrapper, receiverId);
                messageWrapper.eq(LifeMessage::getIsRead, 0);
                messageWrapper.eq(LifeMessage::getDeleteFlag, 0);
                messageWrapper.apply("(instr(delete_phone_id, '" + receiverId + "') is null or instr(delete_phone_id, '" + receiverId + "') = 0)");
                List<LifeMessage> noReadList = lifeMessageMapper.selectList(messageWrapper);

                // 查询免打扰用户
                QueryWrapper<LifeMessageNotDisturb> notDisturbWrapper = new QueryWrapper<>();
                notDisturbWrapper.eq("phone_id", receiverId);
                List<String> notDisturbList = lifeMessageNotDisturbMapper.selectList(notDisturbWrapper).stream().map(LifeMessageNotDisturb::getNotDisturbId).collect(Collectors.toList());

                for (LifeMessageVo messageVo : lifeMessagePageList) {
                    messageVo.setCanChat("1");
                    String messagePhoneId = messageVo.getPhoneId();
                    if (messagePhoneId != null && (currentIsUser || currentIsLawyer)) {
                        if (currentIsUser && messagePhoneId.startsWith("lawyer_")) {
                            Integer lawyerId = messageVo.getUserId();
                            if (lawyerId == null) {
                                LawyerUser lawyerUser = lawyerUserMapper.selectOne(new QueryWrapper<LawyerUser>()
                                        .eq("phone", messagePhoneId.substring(7)));
                                lawyerId = lawyerUser != null ? lawyerUser.getId() : null;
                            }
                            messageVo.setCanChat(isChatEnabled(currentUserId, lawyerId, chatEnabledCache));
                        } else if (currentIsLawyer && messagePhoneId.startsWith("user_")) {
                            Integer userId = messageVo.getUserId();
                            if (userId == null) {
                                LifeUser lifeUser = lifeUserMapper.selectOne(new QueryWrapper<LifeUser>()
                                        .eq("user_phone", messagePhoneId.substring(5)));
                                userId = lifeUser != null ? lifeUser.getId() : null;
                            }
                            messageVo.setCanChat(isChatEnabled(userId, currentLawyerId, chatEnabledCache));
                        }
                    }

                    // 免打扰
                    if (notDisturbList.contains(messageVo.getPhoneId())) {
                        messageVo.setIsNotDisturb("1");
                    } else {
                        messageVo.setIsNotDisturb("0");
                    }

                    // 未读消息数量
                    messageVo.setNotReadCount(noReadList.stream().filter(item -> item.getSenderId().equals(messageVo.getPhoneId())).count());

                    // 我是否关注对方
                    if (followIds.contains(messageVo.getPhoneId())) {
                        messageVo.setIsFollowThis("1");
                    } else {
                        messageVo.setIsFollowThis("0");
                    }

                    // 对方是否关注我
                    if (fansIds.contains(messageVo.getPhoneId())) {
                        messageVo.setIsFollowMe("1");
                    } else {
                        messageVo.setIsFollowMe("0");
                    }

                    // 判断当前登录人是否是商户
                    boolean store = messageVo.getPhoneId().contains("store_");
                    if (store) {
                        messageVo.setIsMerchant("1");
                    } else {
                        messageVo.setIsMerchant("0");
                    }

                    lifeMessagePageResultList.add(messageVo);
                }
            }
            if (userName == null){
                return lifeMessagePageResultList;
            }

            lifeMessagePageResultList = lifeMessagePageResultList.stream().filter(item -> item.getUserName().contains(userName)).collect(Collectors.toList());
            return lifeMessagePageResultList;
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.getMessageList Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    private String isChatEnabled(Integer userId, Integer lawyerId, Map<String, String> cache) {
        if (userId == null || lawyerId == null) {
            return "1";
        }
        String cacheKey = userId + "_" + lawyerId;
        if (cache.containsKey(cacheKey)) {
            return cache.get(cacheKey);
        }
        LambdaQueryWrapper<LawyerConsultationOrder> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(LawyerConsultationOrder::getClientUserId, userId);
        orderWrapper.eq(LawyerConsultationOrder::getLawyerUserId, lawyerId);
        orderWrapper.eq(LawyerConsultationOrder::getDeleteFlag, 0);
        orderWrapper.orderByDesc(LawyerConsultationOrder::getCreatedTime);
        orderWrapper.last("limit 1");
        LawyerConsultationOrder order = lawyerConsultationOrderMapper.selectOne(orderWrapper);
        boolean enabled = true;
        if (order != null) {
            Integer status = order.getOrderStatus();
            enabled = !Objects.equals(status, LawyerStatusEnum.COMPLETE.getStatus())
                    && !Objects.equals(status, LawyerStatusEnum.CANCEL.getStatus())
                    && !Objects.equals(status, LawyerStatusEnum.WAIT_PAY.getStatus())
                    && !Objects.equals(status, LawyerStatusEnum.WAIT_ACCEPT.getStatus())
                    && !Objects.equals(status, LawyerStatusEnum.REFUNDED.getStatus());
        }
        String chatStr = "1";
        if(!enabled){
            chatStr = "0";
        }

        cache.put(cacheKey, chatStr);
        return chatStr;
    }

    @Override
    public LifeMessageVo getStrangerMessageNum(String receiverId) throws Exception {
        try {
            // 查询免打扰用户
            QueryWrapper<LifeMessageNotDisturb> notDisturbWrapper = new QueryWrapper<>();
            notDisturbWrapper.eq("phone_id", receiverId);
            List<String> notDisturbList = lifeMessageNotDisturbMapper.selectList(notDisturbWrapper).stream().map(LifeMessageNotDisturb::getNotDisturbId).collect(Collectors.toList());

            String blockerType = "user".equals(Objects.requireNonNull(JwtUtil.getCurrentUserInfo()).getString("userType")) ? "2" : "1";
            String blockerId = JwtUtil.getCurrentUserInfo().getString("userId");
            QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
            // 过滤拉黑
            wrapper.apply("(user.id not in ( " +
                    "     select blocked_id from life_blacklist " +
                    "     where blocker_type = '" + blockerType + "' and blocker_id = '" + blockerId + "' and blocked_type = '2' and delete_flag = 0 " +
                    ") or user.id is null)");
            wrapper.apply("(suser.id not in ( " +
                    "     select blocked_id from life_blacklist " +
                    "     where blocker_type = '" + blockerType + "' and blocker_id = '" + blockerId + "' and blocked_type = '1' and delete_flag = 0 " +
                    ") or suser.id is null)");
            // 没聊过
            wrapper.apply("message.phoneId not in ( " + lifeMessageUtil.sqlDistinctReceiverIdsBySender(receiverId) + ")");
            wrapper.orderByDesc("message.created_time");

            PhoneTypeIdResult participant = lifeMessageUtil.resolveIdentity(receiverId);
            Integer participantUserType = participant != null ? participant.getType() : -1;
            Integer participantRefId = participant != null ? participant.getId() : -1;
            List<LifeMessageVo> lifeMessagePageList = lifeMessageMapper.getLifeMessagePageByPhoneId(
                    receiverId, participantUserType, participantRefId, wrapper);
            LifeMessageVo vo = new LifeMessageVo();
            if (!CollectionUtils.isEmpty(lifeMessagePageList)) {
                vo.setUserName(lifeMessagePageList.get(0).getUserName());
                vo.setCreatedTime(lifeMessagePageList.get(0).getCreatedTime());
                lifeMessagePageList = lifeMessagePageList.stream().filter(item -> !notDisturbList.contains(item.getPhoneId())).collect(Collectors.toList());
                vo.setNotReadCount(lifeMessagePageList.stream().filter(item -> 0 == item.getIsRead()).count());
            }

            return vo;
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.getStrangerMessageNum Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public LifeMessageVo getNoFriendMessageNum(String receiverId) throws Exception {
        try {
            // 查询所有好友
            QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
            wrapper.groupBy("foll.phoneId");
            String blockerType = "";
            String blockerId = "";
            if ("user".equals(receiverId.split("_")[0])) {
                String myselfUserPhone = receiverId.split("_")[1];
                blockerType = "2";
                LifeUser myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
                blockerId = String.valueOf(myLifeUser.getId());
            } else {
                String myselfStorePhone = receiverId.split("_")[1];
                blockerType = "1";
                StoreUser myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
                blockerId = String.valueOf(myStoreUser.getId());
            }

            LifeFansIdentityQuery.Scope receiverScope = LifeFansIdentityQuery.resolve(receiverId, typeUtil);
            List<LifeFansVo> lifeFansList = lifeFansMapper.getMutualAttention(new Page<>(1, Integer.MAX_VALUE), receiverId,
                    receiverScope.getUserType(), receiverScope.getRefId(), blockerType, blockerId, wrapper).getRecords();
            List<String> friendsIds = lifeFansList.stream().map(LifeFansVo::getPhoneId).filter(item -> !item.equals(receiverId)).collect(Collectors.toList());
            String friendsIdsStr = "'" + String.join("','", friendsIds) + "'";

            // 当前用户的所有未关注人消息
            wrapper = new QueryWrapper<>();
            wrapper.eq("num", 1);
            wrapper.apply("message.phoneId not in (" + friendsIdsStr + ")");
            wrapper.orderByDesc("message.created_time");
            PhoneTypeIdResult participant = lifeMessageUtil.resolveIdentity(receiverId);
            Integer participantUserType = participant != null ? participant.getType() : -1;
            Integer participantRefId = participant != null ? participant.getId() : -1;
            List<LifeMessageVo> lifeMessageVoList = lifeMessageMapper.getLifeMessagePageByPhoneId(
                    receiverId, participantUserType, participantRefId, wrapper);
            LifeMessageVo messageVos = null;
            if(CollectionUtils.isEmpty(lifeMessageVoList)){
                return messageVos;
            }

            lifeMessageVoList.sort(Comparator.comparing(LifeMessageVo::getCreatedTime).reversed());
            for(LifeMessageVo messageVo : lifeMessageVoList) {
                    String senderId = messageVo.getPhoneId();
                    if (senderId != null && senderId.startsWith("lawyer_")) {
                        continue;
                    }

                messageVo.setNotReadCount(lifeMessageVoList.stream().filter(item -> 0 == item.getIsRead()).count());
                // 根据手机号查询发送人信息
                String storePhones = "''";
                String userPhones = "''";
                if (messageVo.getPhoneId().split("_")[0].equals("store")) {
                    storePhones = "'" + messageVo.getPhoneId().split("_")[1] + "'";
                } else {
                    userPhones = "'" + messageVo.getPhoneId().split("_")[1] + "'";
                }
                List<LifeMessageVo> userList = lifeMessageMapper.getLifeUserAndStoreUserByPhone(storePhones, userPhones);
                if (!CollectionUtils.isEmpty(userList)) {
                    messageVo.setUserName(userList.get(0).getUserName());
                    messageVo.setUserImage(userList.get(0).getUserImage());
                }
                messageVos = messageVo;
                break;
            }
            return messageVos;
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.getNoFriendMessageNum Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public JSONObject getMessageListByReceiverId(String receiverId, String senderId) throws Exception {
        try {
            // 获取发送方与接收方头像
            LifeUser lifeUser1 = null;
            StoreImg storeImg = null;
            LawyerUser lawyerUser = null;
            if (receiverId.startsWith("user_")) {
                lifeUser1 = lifeUserMapper.selectOne(new QueryWrapper<LifeUser>().eq("user_phone", receiverId.substring(5)));
            } else if (receiverId.startsWith("store_")) {
                StoreUser storeUser1 = storeUserService.getOne(new QueryWrapper<StoreUser>().eq("phone", receiverId.substring(6)));
                List<StoreImg> storeImgList = storeImgService.getStoreImg(storeUser1.getStoreId(), 10);
                if (!storeImgList.isEmpty()) {
                    storeImg = storeImgList.get(0);
                }
            } else{
                // 律师端
                lawyerUser = lawyerUserMapper.selectOne(new QueryWrapper<LawyerUser>().eq("phone", receiverId.substring(7)));
            }

            LifeUser lifeUser2 = null;
            StoreImg storeImg1 = null;
            LawyerUser lawyerUser1 = null;
            if (senderId.startsWith("user_")) {
                lifeUser2 = lifeUserMapper.selectOne(new QueryWrapper<LifeUser>().eq("user_phone", senderId.substring(5)));
            } else if (senderId.startsWith("store_")) {
                StoreUser storeUser2 = storeUserService.getOne(new QueryWrapper<StoreUser>().eq("phone", senderId.substring(6)));
                List<StoreImg> storeImgList = storeImgService.getStoreImg(storeUser2.getStoreId(), 10);
                if (!storeImgList.isEmpty()) {
                    storeImg1 = storeImgList.get(0);
                }
            } else {
                // 律师端
                lawyerUser1 = lawyerUserMapper.selectOne(new QueryWrapper<LawyerUser>().eq("phone", senderId.substring(7)));
            }

            PhoneTypeIdResult receiverIdentity = lifeMessageUtil.resolveIdentity(receiverId);
            PhoneTypeIdResult senderIdentity = lifeMessageUtil.resolveIdentity(senderId);
            if (receiverIdentity == null || senderIdentity == null) {
                JSONObject empty = new JSONObject();
                empty.put("messageList", new ArrayList<>());
                empty.put("isStranger", true);
                return empty;
            }
            List<LifeMessageVo> lifeMessageVos = lifeMessageMapper.getMessageListByReceiverId(
                    receiverId,
                    senderIdentity.getType(), senderIdentity.getId(),
                    receiverIdentity.getType(), receiverIdentity.getId());
            for (LifeMessageVo lifeMessageVo : lifeMessageVos) {
                if (lifeMessageVo.getReceiverId().equals(receiverId)) {
                    if (null != lifeUser1) {
                        lifeMessageVo.setReceiverImg(lifeUser1.getUserImage());
                    } else if (null != storeImg) {
                        lifeMessageVo.setReceiverImg(storeImg.getImgUrl());
                    } else if (null != lawyerUser){
                        lifeMessageVo.setReceiverImg(lawyerUser.getHeadImg());
                    }

                    if (null != lifeUser2) {
                        lifeMessageVo.setSenderImg(lifeUser2.getUserImage());
                    } else if (null != storeImg1) {
                        lifeMessageVo.setSenderImg(storeImg1.getImgUrl());
                    } else if (null != lawyerUser1) {
                        lifeMessageVo.setSenderImg(lawyerUser1.getHeadImg());
                    }
                } else {
                    if (null != lifeUser1) {
                        lifeMessageVo.setSenderImg(lifeUser1.getUserImage());
                    } else if (null != storeImg) {
                        lifeMessageVo.setSenderImg(storeImg.getImgUrl());
                    } else if (null != lawyerUser) {
                        lifeMessageVo.setSenderImg(lawyerUser.getHeadImg());
                    }

                    if (null != lifeUser2) {
                        lifeMessageVo.setReceiverImg(lifeUser2.getUserImage());
                    } else if (null != storeImg1) {
                        lifeMessageVo.setReceiverImg(storeImg1.getImgUrl());
                    } else if (null != lawyerUser1) {
                        lifeMessageVo.setReceiverImg(lawyerUser1.getHeadImg());
                    }
                }
            }

            // 查询两个人是否是陌生人(只有一条消息)
            LambdaQueryWrapper<LifeMessage> wrapper = new LambdaQueryWrapper<>();
            lifeMessageUtil.applyConversationQuery(wrapper, senderId, receiverId);
            wrapper.orderByDesc(LifeMessage::getCreatedTime);
            int count = lifeMessageMapper.selectCount(wrapper);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("messageList", lifeMessageVos);
            jsonObject.put("isStranger", count <= 1);
            // 陌生人不限制一条消息
//            jsonObject.put("isStranger", false);

            return jsonObject;
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.getMessageListByReceiverId Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public String isStranger(String senderId, String receiverId) throws Exception {
        try {
//            // 查询两个人是否是陌生人(只有一条消息)
//            QueryWrapper<LifeMessage> wrapper = new QueryWrapper<>();
//            // 没聊过
//            wrapper.apply("((sender_id = '" + senderId + "' and receiver_id = '" + receiverId + "') or (sender_id = '" + receiverId + "' and receiver_id = '" + senderId + "'))");
//            wrapper.orderByDesc("created_time");
//            lifeMessageMapper.selectList(wrapper);
//            return lifeMessageMapper.selectCount(wrapper) <= 1;

            // 查询我发送过的消息
            LambdaQueryWrapper<LifeMessage> wrapper = new LambdaQueryWrapper<>();
            lifeMessageUtil.applySenderReceiverPairQuery(wrapper, senderId, receiverId);
            int senderCount = lifeMessageMapper.selectCount(wrapper);
            LambdaQueryWrapper<LifeMessage> wrapper1 = new LambdaQueryWrapper<>();
            lifeMessageUtil.applySenderReceiverPairQuery(wrapper1, receiverId, senderId);
            int receiverCount = lifeMessageMapper.selectCount(wrapper1);
            if (senderCount == 0){
                //本条可以发
                return "1";
            }
            senderCount++;
            // 可以一直唠
            if (senderCount >= 1 && receiverCount >= 1){
            // 发送本条消息并可以一直发
               return "2";
            }
            // 本人发过了,等待对方发
            if (senderCount > 1 && receiverCount==0){
                // 不允许发送本条消息
                 return "0";
            }

            return "0";

            // 陌生人不限制一条消息
//            return "2";
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.isStranger Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }


    @Override
    public int read(String receiverId, String senderId) throws Exception {
        try {
            LambdaUpdateWrapper<LifeMessage> wrapper = new LambdaUpdateWrapper<>();
            lifeMessageUtil.applySenderReceiverPairUpdate(wrapper, senderId, receiverId);
            wrapper.eq(LifeMessage::getDeleteFlag, 0);
            wrapper.set(LifeMessage::getIsRead, 1);
            return lifeMessageMapper.update(null, wrapper);
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.read Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public int noReadCount(String receiverId) throws Exception {
        try {
            LambdaQueryWrapper<LifeMessage> wrapper = new LambdaQueryWrapper<>();
            lifeMessageUtil.applyReceiverQuery(wrapper, receiverId);
            wrapper.eq(LifeMessage::getIsRead, 0);
            wrapper.eq(LifeMessage::getDeleteFlag, 0);
            return lifeMessageMapper.selectCount(wrapper);
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.noReadCount Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public int deleteMessageByPhoneId(String senderId, String receiverId) throws Exception {
        try {
            PhoneTypeIdResult sender = lifeMessageUtil.resolveIdentity(senderId);
            PhoneTypeIdResult receiver = lifeMessageUtil.resolveIdentity(receiverId);
            if (sender == null || receiver == null) {
                return 0;
            }
            return lifeMessageMapper.deleteMessageByPhoneId(
                    sender.getType(), sender.getId(),
                    receiver.getType(), receiver.getId(),
                    senderId, receiverId);
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.deleteMessageByPhoneId Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public int getAllNoReadCount(String receiverId) throws Exception {
        try {
            String blockerType = "user".equals(Objects.requireNonNull(JwtUtil.getCurrentUserInfo()).getString("userType")) ? "2" : "1";
            String blockerId = JwtUtil.getCurrentUserInfo().getString("userId");

            // 查询拉黑
            List<String> lifeBlacklistVoList = lifeBlacklistMapper.getPhoneIdByUserId(blockerType, blockerId)
                    .stream()
                    // 1. 先过滤掉 null 的 LifeBlacklistVo 对象（避免调用 getPhoneId() 时抛 NPE）
                    .filter(Objects::nonNull)
                    // 2. 调用 getPhoneId() 获取值
                    .map(LifeBlacklistVo::getPhoneId)
                    // 3. 过滤掉 getPhoneId() 返回的 null 值
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 查询免打扰用户
            QueryWrapper<LifeMessageNotDisturb> notDisturbWrapper = new QueryWrapper<>();
            notDisturbWrapper.eq("phone_id", receiverId);
            List<String> notDisturbList = lifeMessageNotDisturbMapper.selectList(notDisturbWrapper).stream().map(LifeMessageNotDisturb::getNotDisturbId).collect(Collectors.toList());
            notDisturbList.addAll(lifeBlacklistVoList);
            String notDisturbIdsStr = "'" + String.join("','", notDisturbList) + "'";

            // 查询未读消息数量（life_message 按 receiver_user_type + receiver_ref_id）
            LambdaQueryWrapper<LifeMessage> messageWrapper = new LambdaQueryWrapper<>();
            lifeMessageUtil.applyReceiverQuery(messageWrapper, receiverId);
            messageWrapper.eq(LifeMessage::getIsRead, 0);
            messageWrapper.notIn(LifeMessage::getSenderId, notDisturbIdsStr);
            messageWrapper.apply("(instr(delete_phone_id, '" + receiverId + "') is null or instr(delete_phone_id, '" + receiverId + "') = 0)");
            int noReadMessageCount = lifeMessageMapper.selectCount(messageWrapper);

            // 查询未读通知数量（life_notice 按 receiver_user_type + receiver_ref_id）
            LambdaQueryWrapper<LifeNotice> noticeWrapper = new LambdaQueryWrapper<>();
            lifeNoticeUtil.applyReceiverQuery(noticeWrapper, receiverId);
            noticeWrapper.eq(LifeNotice::getIsRead, 0);
            int noReadNoticeCount = lifeNoticeMapper.selectCount(noticeWrapper);

            return noReadMessageCount + noReadNoticeCount;
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.getAllNoReadCount Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public List<LifeFansVo> getTalkedUserList() throws Exception {
        try {
            String phoneId = Objects.requireNonNull(JwtUtil.getCurrentUserInfo()).getString("userType") + "_" + JwtUtil.getCurrentUserInfo().getString("phone");
            PhoneTypeIdResult participant = lifeMessageUtil.resolveIdentity(phoneId);
            if (participant == null) {
                return new ArrayList<>();
            }
            return lifeMessageMapper.getTalkedUserList(phoneId, participant.getType(), participant.getId());
        } catch (Exception e) {
            log.error("LifeMessageServiceImpl.getTalkedUserList Error Mgs={}", e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public boolean isBanned(String phoneId) {
        if (phoneId.startsWith("store_")) {
            return false;
        }
        LambdaQueryWrapper<LifeUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeUser::getUserPhone, phoneId.split("_")[1]);
        return lifeUserMapper.selectOne(wrapper).getIsBanned() == 1;
    }

}
