package shop.alien.store.service;

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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.CommonCommentVo;
import shop.alien.entity.store.vo.LifePinglunVo;
import shop.alien.entity.store.vo.LifeUserDynamicsVo;
import shop.alien.mapper.*;
import shop.alien.store.util.LifeDynamicsIdentityHelper;
import shop.alien.store.util.LifeDynamicsIdentityHelper.PublisherScope;
import shop.alien.store.util.StoreLikeRecordIdentityHelper;
import shop.alien.util.common.constant.CommentSourceTypeEnum;
import shop.alien.util.type.LifeFansIdentityQuery;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户动态
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LifeUserDynamicsService extends ServiceImpl<LifeUserDynamicsMapper, LifeUserDynamics> {

    private final LifeUserDynamicsMapper lifeUserDynamicsMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeCommentMapper lifeCommentMapper;

    private final LifeFansMapper lifeFansMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final StoreCommentService storeCommentService;

    private final StoreUserService storeUserService;

    private final LifeUserService lifeUserService;

    private final LifeBlacklistMapper lifeBlacklistMapper;

    private final StoreImgMapper storeImgMapper;

    private final StoreCommentMapper storeCommentMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final StoreUserMapper storeUserMapper;

    private final CommonCommentMapper commonCommentMapper;

    private final CommonRatingService commonRatingService;
    
    private final CommonRatingMapper commonRatingMapper;

    private final LifeDynamicsIdentityHelper dynamicsIdentityHelper;

    private final StoreLikeRecordIdentityHelper lifeLikeIdentityHelper;

    private LifeFansIdentityQuery.Scope resolveFansScope(String phoneId) {
        PublisherScope scope = dynamicsIdentityHelper.resolveFromPhoneId(phoneId);
        return new LifeFansIdentityQuery.Scope(scope.getLegacyPhoneId(), scope.getPhoneUserType(), scope.getPhoneRefId());
    }

    private List<String> queryFollowedIds(String phoneId) {
        LifeFansIdentityQuery.Scope scope = resolveFansScope(phoneId);
        if (!scope.hasTypeRef()) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<LifeFans> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeFans::getDeleteFlag, 0);
        LifeFansIdentityQuery.applyFansSide(wrapper, scope);
        return lifeFansMapper.selectList(wrapper).stream()
                .map(LifeFans::getFollowedId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private List<String> queryFansIds(String phoneId) {
        LifeFansIdentityQuery.Scope scope = resolveFansScope(phoneId);
        if (!scope.hasTypeRef()) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<LifeFans> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeFans::getDeleteFlag, 0);
        LifeFansIdentityQuery.applyFollowedSide(wrapper, scope);
        return lifeFansMapper.selectList(wrapper).stream()
                .map(LifeFans::getFansId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }


    public int addLiulanCount(String id) {
        LambdaUpdateWrapper<LifeUserDynamics> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LifeUserDynamics::getId, id);
        lambdaUpdateWrapper.setSql("liulan_count = liulan_count + 1");
        return lifeUserDynamicsMapper.update(null, lambdaUpdateWrapper);
    }

    public int setTopStatus(LifeUserDynamicsVo lifeUserDynamicsVo) {
        if(!StringUtils.isEmpty(lifeUserDynamicsVo.getId()) && !StringUtils.isEmpty(lifeUserDynamicsVo.getTopStatus())){
            LambdaUpdateWrapper<LifeUserDynamics> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LifeUserDynamics::getId, lifeUserDynamicsVo.getId());
            lambdaUpdateWrapper.set(LifeUserDynamics::getTopStatus, lifeUserDynamicsVo.getTopStatus());
            if(lifeUserDynamicsVo.getTopStatus() == 0){
                lambdaUpdateWrapper.set(LifeUserDynamics::getTopTime, null);
            } else{
                lambdaUpdateWrapper.set(LifeUserDynamics::getTopTime, new Date());

            }
            return lifeUserDynamicsMapper.update(null, lambdaUpdateWrapper);
        } else {
            return 0;
        }
    }

    public int enableStatus(LifeUserDynamicsVo lifeUserDynamicsVo) {
        if(!StringUtils.isEmpty(lifeUserDynamicsVo.getId()) && !StringUtils.isEmpty(lifeUserDynamicsVo.getEnableStatus())) {
            LambdaUpdateWrapper<LifeUserDynamics> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LifeUserDynamics::getId, lifeUserDynamicsVo.getId());
            lambdaUpdateWrapper.set(LifeUserDynamics::getEnableStatus, lifeUserDynamicsVo.getEnableStatus());
            return lifeUserDynamicsMapper.update(null, lambdaUpdateWrapper);
        } else {
            return 0;
        }
    }

    public int addOrUpdateStore(LifeUserDynamics store) {
        dynamicsIdentityHelper.normalizePublisherFields(store);
        if (StringUtils.isEmpty(store.getId())) {
            Date nowDate = new Date(System.currentTimeMillis());
            store.setCreatedTime(new java.sql.Timestamp(nowDate.getTime()));
            return lifeUserDynamicsMapper.insert(store);
        } else {
            LifeUserDynamics lifeUserDynamics = lifeUserDynamicsMapper.selectById(store.getId());
            int draft = lifeUserDynamics.getDraft();
            if(draft == 1 && store.getDraft() == 0){
                store.setCreatedTime(new Date());
            }
            return lifeUserDynamicsMapper.updateById(store);
        }
    }

    public Boolean deleteDynamicsById(int id) {
        return this.removeById(id);
    }

    public Map<String, List<LifePinglunVo>> getUserDynamicsCommentById(String id) {
        LambdaUpdateWrapper<LifeComment> wrapper = new LambdaUpdateWrapper<>();
        wrapper.orderByDesc(LifeComment::getPinglunTime);
        wrapper.eq(LifeComment::getDongtaiShequId, id);
        wrapper.eq(LifeComment::getPinglunLeibie, "2");
        List<LifeComment> lifePingluns = lifeCommentMapper.selectList(wrapper);
        List<LifePinglunVo> lifePinglunVos = new ArrayList<>();
        if (!ObjectUtils.isEmpty(lifePingluns)) {
            for (LifeComment pl : lifePingluns) {
                LifePinglunVo vo = new LifePinglunVo();
                BeanUtils.copyProperties(pl, vo);
                if (!StringUtils.isEmpty(vo.getUserId())) {
                    LifeUser user = lifeUserMapper.selectById(vo.getUserId());
                    if (!ObjectUtils.isEmpty(user)) {
                        vo.setHeadImage(user.getUserImage());
                    }
                    LambdaQueryWrapper<LifeLikeRecord> recordLambdaUpdateWrapper = new LambdaQueryWrapper<>();
                    recordLambdaUpdateWrapper.eq(LifeLikeRecord::getHuifuId, vo.getId());
                    lifeLikeIdentityHelper.applyLikerFilter(recordLambdaUpdateWrapper,
                            lifeLikeIdentityHelper.resolveFromDianzanId(vo.getUserId()));
                    List<LifeLikeRecord> records = lifeLikeRecordMapper.selectList(recordLambdaUpdateWrapper);
                    if (ObjectUtils.isEmpty(records)) {
                        vo.setDianzanStatus("0");
                    } else {
                        vo.setDianzanStatus("1");
                    }
                }
                lifePinglunVos.add(vo);
            }
        }
        return lifePinglunVos.stream().collect(Collectors.groupingBy(LifePinglunVo::getHuifuId));
    }

    //
    // 生成用户动态信息
    // 该方法用于获取并处理用户的动态数据，包括过滤、排序和设置相关状态信息
    //
    // 参数:
    //   myself - "1"表示查询自己的动态，其他值表示非本人动态
    //   type - 动态类型，为空时返回所有类型
    //   isFollowed - "1"表示查询关注用户的动态
    //   phoneId - 用户标识，用于关联粉丝、点赞和黑名单信息
    // 返回值:
    //   List<LifeUserDynamicsVo> - 处理后的用户动态列表，包含状态信息如是否关注、是否点赞等
    //
    public List<LifeUserDynamicsVo> getUserDynamics(String myself, String type, String isFollowed, String phoneId) {
        // 查询动态数据并按类型过滤
        List<LifeUserDynamicsVo> lifeUserDynamicsVoList = lifeUserDynamicsMapper.getLifeUserDynamicsList();

        // 店铺id - 优化：批量查询评价数量，避免N+1查询
        List<String> storeUserIdList = new ArrayList<>();
        //对lifeUserDynamicsVoList数据进行处理，当type为2的时候，把userName的数值赋值到storeName
        lifeUserDynamicsVoList.forEach(item -> {
            dynamicsIdentityHelper.ensureVoLegacyPhoneId(item);
            if (item.getType().equals("2")) {
                item.setStoreName(item.getUserName());
                if (item.getStoreUserId() != null) {
                    storeUserIdList.add(item.getStoreUserId());
                }
            }
        });

        // 批量查询评价数量（优化：从N+1查询改为批量查询）
        Map<String, Integer> commitCountMap = batchGetRatingCount(storeUserIdList);
        if (!StringUtils.isEmpty(type)) {
            lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream().filter(item -> type.equals(item.getType())).collect(Collectors.toList());
        }

        // 并发查询关注、粉丝、点赞信息（优化：并行执行多个独立查询）
        CompletableFuture<List<String>> followListFuture = CompletableFuture.supplyAsync(() -> {
            if (StringUtils.isEmpty(phoneId)) {
                return Collections.emptyList();
            }
            return queryFollowedIds(phoneId);
        });

        CompletableFuture<List<String>> fansListFuture = CompletableFuture.supplyAsync(() -> {
            if (StringUtils.isEmpty(phoneId)) {
                return Collections.emptyList();
            }
            return queryFansIds(phoneId);
        });

        CompletableFuture<List<String>> likeListFuture = CompletableFuture.supplyAsync(() -> {
            if (StringUtils.isEmpty(phoneId)) {
                return Collections.emptyList();
            }
            LambdaQueryWrapper<LifeLikeRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LifeLikeRecord::getType, "2");
            lifeLikeIdentityHelper.applyLikerFilter(wrapper, lifeLikeIdentityHelper.resolveFromDianzanId(phoneId));
            return lifeLikeRecordMapper.selectList(wrapper).stream()
                    .map(LifeLikeRecord::getHuifuId)
                    .collect(Collectors.toList());
        });

        // 等待所有查询完成
        List<String> followList = followListFuture.join();
        List<String> fansList = fansListFuture.join();
        List<String> likeList = likeListFuture.join();

        // 根据myself参数过滤动态：自己或非本人动态
        PublisherScope viewerScope = dynamicsIdentityHelper.resolveFromPhoneId(phoneId);
        if ("1".equals(myself)) {
            lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream()
                    .filter(item -> dynamicsIdentityHelper.isSamePublisher(item, viewerScope))
                    .collect(Collectors.toList());
        } else {
            lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream().filter(item -> item.getDraft() == 0).collect(Collectors.toList());
        }

        // 如果isFollowed为"1"，进一步过滤出关注用户的动态
        if ("1".equals(isFollowed)) {
            lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream().filter(item -> followList.contains(item.getPhoneId())).collect(Collectors.toList());
        }

        // 批量查询评论数量（优化：一次性查询所有动态的评论数）
        List<CommonCommentVo> commonCommentVo = commonCommentMapper.getCommentCount(CommentSourceTypeEnum.DYNAMIC_COMMENT.getType());
        // 转换为Map，提升查找性能
        Map<Long, Integer> commentCountMap = commonCommentVo.stream()
                .collect(Collectors.toMap(
                        vo -> Long.parseLong(vo.getSourceId().toString()),
                        CommonCommentVo::getCommentCount,
                        (v1, v2) -> v1 + v2 // 如果有重复key，累加
                ));

        // 设置动态对象的状态信息：是否关注对方、是否被关注、是否点赞及评论数量
        // 设置.imagePath。视频为mp4+jpg格式，图片为jpg/png格式。
        for (LifeUserDynamicsVo vo : lifeUserDynamicsVoList) {
            // 设置评价数量
            if (commitCountMap.containsKey(vo.getStoreUserId())) {
                vo.setRatingCount(commitCountMap.get(vo.getStoreUserId()).toString());
            } else {
                vo.setRatingCount("0");
            }
            if (followList.contains(vo.getPhoneId())) {
                vo.setIsFollowThis("1");
            } else {
                vo.setIsFollowThis("0");
            }
            if (fansList.contains(vo.getPhoneId())) {
                vo.setIsFollowMe("1");
            } else {
                vo.setIsFollowMe("0");
            }
            if (likeList.contains(String.valueOf(vo.getId()))) {
                vo.setIsLike("1");
            } else {
                vo.setIsLike("0");
            }
            // 优化：直接从Map中获取评论数量，避免stream过滤
            Integer commentCount = commentCountMap.getOrDefault(Long.parseLong(vo.getId().toString()), 0);
            vo.setCommentCount(commentCount);
        }

        // 如果phoneId不为空，处理黑名单逻辑，过滤掉被拉黑用户的动态
        if (!StringUtils.isEmpty(phoneId)) {
            // 通过phoneId查询userId
            LifeUser myLifeUser = new LifeUser();
            StoreUser myStoreUser = new StoreUser();
            if ("user".equals(phoneId.split("_")[0])) {
                String myselfUserPhone = phoneId.split("_")[1];
                myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
            } else {
                String myselfStorePhone = phoneId.split("_")[1];
                myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
            }

            // 查询拉黑的对象
            LambdaQueryWrapper<LifeBlacklist> myLifeBlacklistWrapper = new LambdaQueryWrapper<>();

            if (null != myLifeUser && null != myLifeUser.getId()) {
                myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "2");
                myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myLifeUser.getId());
            } else {
                myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "1");
                myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myStoreUser.getId());
            }
            List<LifeBlacklist> lifeBlacklists = lifeBlacklistMapper.selectList(myLifeBlacklistWrapper);

            // 按类型分组的黑名单用户ID映射（1: 商户, 2: 用户）
            Map<String, Set<String>> blockedUserIdsByType = lifeBlacklists.stream().collect(Collectors.groupingBy(LifeBlacklist::getBlockedType, Collectors.mapping(LifeBlacklist::getBlockedId, Collectors.toSet())));

            // 过滤掉发布者在黑名单中的动态
            lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream().filter(dynamics -> {
                dynamicsIdentityHelper.ensureVoLegacyPhoneId(dynamics);
                String blackPhoneId = dynamicsIdentityHelper.resolveComparablePhoneId(dynamics);
                String userId = dynamics.getStoreOrUserId();
                String userType = dynamicsIdentityHelper.resolveBlacklistBlockedType(dynamics);

                // 如果无法识别类型或不在黑名单中，保留该动态
                if ("0".equals(userType) || !blockedUserIdsByType.containsKey(userType)) {
                    return true;
                }

                // 检查用户是否在对应类型的黑名单中
                return !blockedUserIdsByType.get(userType).contains(userId);
            }).collect(Collectors.toList());
        }

        // 最后按照创建时间倒序排序
//        lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream().sorted(Comparator.comparing(LifeUserDynamicsVo::getCreatedTime).reversed()).collect(Collectors.toList());

        return lifeUserDynamicsVoList;
    }

    /**
     * 批量查询评价数量（优化：从N+1查询改为批量查询）
     * 
     * @param storeUserIdList 店铺ID列表
     * @return 店铺ID -> 评价数量的映射
     */
    private Map<String, Integer> batchGetRatingCount(List<String> storeUserIdList) {
        Map<String, Integer> commitCountMap = new HashMap<>();
        if (storeUserIdList == null || storeUserIdList.isEmpty()) {
            return commitCountMap;
        }

        try {
            // 转换为Integer列表
            List<Integer> storeIdList = storeUserIdList.stream()
                    .filter(id -> id != null && !id.isEmpty())
                    .map(id -> {
                        try {
                            return Integer.parseInt(id);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    })
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            if (storeIdList.isEmpty()) {
                return commitCountMap;
            }

            // 批量查询评价记录（只查询审核通过且展示的）
            LambdaQueryWrapper<CommonRating> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(CommonRating::getBusinessId, storeIdList)
                    .eq(CommonRating::getBusinessType, 1)
                    .eq(CommonRating::getAuditStatus, 1)
                    .eq(CommonRating::getIsShow, 1);
            List<CommonRating> allRatings = commonRatingMapper.selectList(wrapper);

            // 按businessId分组统计评论总数
            Map<Integer, Long> ratingCountMap = allRatings.stream()
                    .collect(Collectors.groupingBy(
                            CommonRating::getBusinessId,
                            Collectors.counting()
                    ));

            // 转换为String -> Integer映射
            for (String storeIdStr : storeUserIdList) {
                try {
                    Integer storeId = Integer.parseInt(storeIdStr);
                    Long count = ratingCountMap.get(storeId);
                    commitCountMap.put(storeIdStr, count != null ? count.intValue() : 0);
                } catch (NumberFormatException e) {
                    commitCountMap.put(storeIdStr, 0);
                }
            }
        } catch (Exception e) {
            log.error("批量获取评价数量失败", e);
            // 如果批量查询失败，设置默认值
            storeUserIdList.forEach(storeId -> commitCountMap.put(storeId, 0));
        }

        return commitCountMap;
    }

    public List<LifeUserDynamicsVo> getStoreUserDynamics(String storePhone, String userType, String loginPhone) {
            PublisherScope storeScope = dynamicsIdentityHelper.resolveStorePublisherByStorePhone(storePhone);
            CompletableFuture<List<LifeUserDynamics>> dynamicsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<LifeUserDynamics> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                dynamicsIdentityHelper.applyPublisherFilter(lambdaQueryWrapper, storeScope);
                return lifeUserDynamicsMapper.selectList(lambdaQueryWrapper);
            });
            CompletableFuture<Set<String>> likeSetFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<LifeLikeRecord> likeWrapper = new LambdaQueryWrapper<>();
                likeWrapper.eq(LifeLikeRecord::getType, "2");
                String likerId = userType.equals("1") ? "user_" + loginPhone : "store_" + loginPhone;
                lifeLikeIdentityHelper.applyLikerFilter(likeWrapper,
                        lifeLikeIdentityHelper.resolveFromDianzanId(likerId));
                List<LifeLikeRecord> lifeLikeList = lifeLikeRecordMapper.selectList(likeWrapper);
                return lifeLikeList.stream().map(LifeLikeRecord::getHuifuId).collect(Collectors.toSet());
            });

            List<LifeUserDynamics> lifeUserDynamics = dynamicsFuture.join();
            Set<String> likeSet = likeSetFuture.join();

            List<LifeUserDynamicsVo> lifeUserDynamicsVos = lifeUserDynamics.stream()
                .map(dynamics -> {
                    LifeUserDynamicsVo vo = new LifeUserDynamicsVo();
                    BeanUtils.copyProperties(dynamics, vo);
                    dynamicsIdentityHelper.ensureVoLegacyPhoneId(vo);
                    return vo;
                })
                .collect(Collectors.toList());

            Set<Integer> userRefIds = new HashSet<>();
            Set<Integer> storeRefIds = new HashSet<>();
            for (LifeUserDynamicsVo vo : lifeUserDynamicsVos) {
                if (vo.getPhoneUserType() != null && vo.getPhoneRefId() != null) {
                    if (vo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_USER) {
                        userRefIds.add(vo.getPhoneRefId());
                    } else if (vo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_STORE) {
                        storeRefIds.add(vo.getPhoneRefId());
                    }
                }
            }

            Map<Integer, LifeUser> userByIdMap = CollectionUtils.isEmpty(userRefIds) ? Collections.emptyMap()
                    : lifeUserMapper.selectBatchIds(userRefIds).stream()
                            .collect(Collectors.toMap(LifeUser::getId, u -> u, (a, b) -> a));
            List<StoreUser> storeUserList = CollectionUtils.isEmpty(storeRefIds)
                    ? Collections.<StoreUser>emptyList()
                    : storeUserMapper.selectBatchIds(storeRefIds);
            Map<Integer, StoreUser> storeUserByIdMap = storeUserList.stream()
                    .collect(Collectors.toMap(StoreUser::getId, u -> u, (a, b) -> a));

            // 批量查询店铺信息
            List<Integer> storeIds = storeUserList.stream().map(StoreUser::getStoreId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            Map<Integer, StoreInfo> storeInfoMap = CollectionUtils.isEmpty(storeIds) ? Collections.emptyMap()
                    : storeInfoMapper.selectBatchIds(storeIds).stream().collect(Collectors.toMap(StoreInfo::getId, s -> s, (a, b) -> a));

            for (LifeUserDynamicsVo vo : lifeUserDynamicsVos) {
                if (likeSet.contains(String.valueOf(vo.getId()))) {
                    vo.setIsLike("1");
                } else {
                    vo.setIsLike("0");
                }

                if (vo.getPhoneUserType() != null && vo.getPhoneRefId() != null) {
                    if (vo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_USER) {
                        LifeUser lifeUser = userByIdMap.get(vo.getPhoneRefId());
                        if (lifeUser != null) {
                            vo.setUserName(lifeUser.getUserName());
                            vo.setUserImage(lifeUser.getUserImage());
                        }
                    } else if (vo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_STORE) {
                        StoreUser storeUser = storeUserByIdMap.get(vo.getPhoneRefId());
                        if (storeUser != null) {
                            if (storeUser.getStoreId() != null) {
                                StoreInfo storeInfo = storeInfoMap.get(storeUser.getStoreId());
                                if (storeInfo != null && StringUtils.hasText(storeInfo.getStoreName())) {
                                    vo.setUserName(storeInfo.getStoreName());
                                } else {
                                    vo.setUserName(storeUser.getNickName());
                                }
                            } else {
                                vo.setUserName(storeUser.getNickName());
                            }
                            vo.setUserImage(storeUser.getHeadImg());
                        }
                    }
                }
            }
            return lifeUserDynamicsVos;
    }

    public Map<String, Object> getUserDynamics(String myselfPhoneId, String phoneId, String type, Integer page, Integer size) {

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

        resultMap.put("phoneId", phoneId);

        // 查询好友的关注
        List<String> followList = queryFollowedIds(phoneId);

        resultMap.put("followListSum", followList.size());

        // 查询好友的粉丝
        List<String> fansList = queryFansIds(phoneId);

        // 查询我的粉丝
        List<String> myFansList = queryFansIds(myselfPhoneId);

        resultMap.put("fansListSum", fansList.size());

        //通过phoneId查询userId
        // 判断 targetPhone 是否在 fansList 中 1 已关注 0 未关注
        int isFollowed = fansList.contains(myselfPhoneId) ? 1 : 0;
        resultMap.put("isFollowed", isFollowed);
        resultMap.put("isFollowedMe", myFansList.contains(phoneId) ? 1 : 0);

        //是否关注用户
        String targetPhone;
        LifeUser myLifeUser = new LifeUser();
        StoreUser myStoreUser = new StoreUser();
        if ("user".equals(myselfPhoneId.split("_")[0])) {
            String myselfUserPhone = myselfPhoneId.split("_")[1];
            myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
            targetPhone = myLifeUser.getUserPhone();
        } else {
            String myselfStorePhone = myselfPhoneId.split("_")[1];
            myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
            targetPhone = myStoreUser.getPhone();
        }

        //查询是否已拉黑
        LambdaQueryWrapper<LifeBlacklist> myLifeBlacklistWrapper = new LambdaQueryWrapper<>();

        if (null != myLifeUser.getId()) {
            myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "2");
            myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myLifeUser.getId());
        } else {
            myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "1");
            myLifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myStoreUser.getId());
        }

        LifeUser lifeUser = new LifeUser();
        StoreUser storeUser = new StoreUser();
        // 商户 phoneId 时在 resultMap 与每条动态上填充店铺展示字段
        String profileStoreName = null;
        Double profileScoreAvg = null;
        String profileRatingCount = null;

        String[] split = myselfPhoneId.split("_");
//        if ("store".equals(split[0])) {
//            // 添加商户用户头像
//            StoreUser storeUserByPhone = storeUserService.getUserByPhone(split[1]);
//            StoreImg storeImg = storeImgMapper.selectOne(new LambdaQueryWrapper<StoreImg>().eq(StoreImg::getStoreId, storeUserByPhone.getId()).eq(StoreImg::getImgType, "10").eq(StoreImg::getDeleteFlag, "0"));
//            if (storeImg != null) {
//                resultMap.put("storeUserImg", storeImg.getImgUrl());
//            }
//        }
        if ("user".equals(phoneId.split("_")[0])) {
            String userPhone = phoneId.split("_")[1];
            lifeUser = lifeUserService.getUserByPhone(userPhone);
            resultMap.put("lifeUser", lifeUser);
        } else {
            String storePhone = phoneId.split("_")[1];
            storeUser = storeUserService.getUserByPhone(storePhone);
            // 根据storeId查询店铺信息，获取店铺名称
            if (storeUser != null) {
                if (storeUser.getStoreId() != null) {
                    String storeIdStr = String.valueOf(storeUser.getStoreId());
                    Map<String, Integer> ratingCountMap = batchGetRatingCount(Collections.singletonList(storeIdStr));
                    int ratingCnt = ratingCountMap.getOrDefault(storeIdStr, 0);
                    profileRatingCount = String.valueOf(ratingCnt);
                    resultMap.put("ratingCount", profileRatingCount);

                    StoreInfo storeInfo = storeInfoMapper.selectById(storeUser.getStoreId());
                    if (storeInfo != null) {
                        resultMap.put("businessSection", storeInfo.getBusinessSection());
                        double score = storeInfo.getScoreAvg() != null ? storeInfo.getScoreAvg() : 0.0;
                        resultMap.put("scoreAvg", score);
                        profileScoreAvg = score;
                        String sn = StringUtils.hasText(storeInfo.getStoreName()) ? storeInfo.getStoreName() : storeUser.getNickName();
                        resultMap.put("storeName", sn);
                        profileStoreName = sn;
                        storeUser.setUserName(sn);
                        storeUser.setNickName(sn);
                    } else {
                        resultMap.put("scoreAvg", 0.0);
                        profileScoreAvg = 0.0;
                        String nick = storeUser.getNickName();
                        resultMap.put("storeName", nick);
                        profileStoreName = nick;
                        storeUser.setUserName(nick);
                    }
                } else {
                    resultMap.put("scoreAvg", 0.0);
                    resultMap.put("ratingCount", "0");
                    String nick = storeUser.getNickName();
                    resultMap.put("storeName", nick);
                    profileScoreAvg = 0.0;
                    profileRatingCount = "0";
                    profileStoreName = nick;
                    storeUser.setUserName(nick);
                }
                storeUser.setUserImage(storeUser.getHeadImg());
                storeUser.setJianjie(storeUser.getAccountBlurb());
            }
            resultMap.put("storeUser", storeUser);
        }


        //查询是否已拉黑
        LambdaQueryWrapper<LifeBlacklist> lifeBlacklistWrapper = new LambdaQueryWrapper<>();

        if (null != myLifeUser.getId()) {
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "2");
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myLifeUser.getId());
        } else {
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "1");
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myStoreUser.getId());
        }

        if (null != lifeUser.getId()) {
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockedType, "2");
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockedId, lifeUser.getId());
        } else {
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockedType, "1");
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockedId, storeUser.getId());
        }
        LifeBlacklist lifeBlacklist = lifeBlacklistMapper.selectOne(lifeBlacklistWrapper);
        //是否拉黑 已拉黑1 未拉黑0
        int isBlocked = lifeBlacklist != null ? 1 : 0;
        int blockId = lifeBlacklist != null ? lifeBlacklist.getId() : 0;

        // 好友动态
        PublisherScope profileScope = dynamicsIdentityHelper.resolveFromPhoneId(phoneId);
        LambdaQueryWrapper<LifeUserDynamics> wrapper = new LambdaQueryWrapper<>();
        dynamicsIdentityHelper.applyPublisherFilter(wrapper, profileScope);
        wrapper.eq(LifeUserDynamics::getDraft, 0);
        IPage<LifeUserDynamics> lifeUserDynamicsPage = new Page<>(page, size);
        IPage<LifeUserDynamics> lifeUserDynamicsIPage = lifeUserDynamicsMapper.selectPage(lifeUserDynamicsPage, wrapper);
        List<LifeUserDynamicsVo> lifeUserDynamicsVoList = lifeUserDynamicsIPage.getRecords().stream().map(dynamics -> {
            LifeUserDynamicsVo dynamicsVo = new LifeUserDynamicsVo();
            BeanUtils.copyProperties(dynamics, dynamicsVo);
            dynamicsIdentityHelper.ensureVoLegacyPhoneId(dynamicsVo);
            return dynamicsVo;
        }).collect(Collectors.toList());

        // 设置动态总数
        resultMap.put("dynamicTotal", lifeUserDynamicsIPage.getTotal());
        // 查询我的点赞
        LambdaQueryWrapper<LifeLikeRecord> likeWrapper = new LambdaQueryWrapper<>();
        likeWrapper.eq(LifeLikeRecord::getType, "2");
        lifeLikeIdentityHelper.applyLikerFilter(likeWrapper,
                lifeLikeIdentityHelper.resolveFromDianzanId(myselfPhoneId));
        List<LifeLikeRecord> lifeLikeList = lifeLikeRecordMapper.selectList(likeWrapper);
        List<String> likeList = lifeLikeList.stream().map(LifeLikeRecord::getHuifuId).collect(Collectors.toList());

        // 我是否点赞，并且查询每条动态的评论数量
        for (LifeUserDynamicsVo dynamicsVo : lifeUserDynamicsVoList) {
            if (profileStoreName != null) {
                dynamicsVo.setStoreName(profileStoreName);
            }
            if (profileScoreAvg != null) {
                dynamicsVo.setScoreAvg(profileScoreAvg);
            }
            if (profileRatingCount != null) {
                dynamicsVo.setRatingCount(profileRatingCount);
            }
            if (likeList.contains(String.valueOf(dynamicsVo.getId()))) {
                dynamicsVo.setIsLike("1");
            } else {
                dynamicsVo.setIsLike("0");
            }
            // 根据store_comment 表 business_id 查询评论数量
//            int commentCount = storeCommentService.count(new QueryWrapper<StoreComment>().eq("business_id", dynamicsVo.getId()).eq("delete_flag", "0").eq("comment_type", "1"));
            int commonCommentCount = commonCommentMapper.selectCount(new QueryWrapper<CommonComment>().eq("source_id", dynamicsVo.getId()).eq("delete_flag", "0").eq("source_type", CommentSourceTypeEnum.DYNAMIC_COMMENT.getType()));
            dynamicsVo.setCommentCount(commonCommentCount);
            if (dynamicsVo.getPhoneUserType() != null && dynamicsVo.getPhoneRefId() != null) {
                if (dynamicsVo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_USER) {
                    dynamicsVo.setStoreUserId(String.valueOf(dynamicsVo.getPhoneRefId()));
                    dynamicsVo.setStoreOrUserId(String.valueOf(dynamicsVo.getPhoneRefId()));
                } else if (dynamicsVo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_STORE) {
                    StoreUser storeUser1 = storeUserService.getById(dynamicsVo.getPhoneRefId());
                    if (storeUser1 != null) {
                        dynamicsVo.setStoreUserId(storeUser1.getStoreId() != null ? String.valueOf(storeUser1.getStoreId()) : "");
                        dynamicsVo.setStoreOrUserId(String.valueOf(storeUser1.getId()));
                    }
                }
            }
        }

        // 好友获赞数量
        int dianzanCount = (int) lifeUserDynamicsIPage.getRecords().stream().mapToInt(LifeUserDynamics::getDianzanCount).sum();
        resultMap.put("likeListSum", dianzanCount);

        resultMap.put("isBlocked", isBlocked);
        resultMap.put("blockId", blockId);
        resultMap.put("lifeUserDynamics", lifeUserDynamicsVoList);
        if (lifeUser.getUserName() != null) {
            resultMap.put("name", lifeUser.getUserName());
        }
        return resultMap;
    }

    public List<LifeUserDynamics> getUserDraftDynamics(String phoneId) {
        PublisherScope scope = dynamicsIdentityHelper.resolveFromPhoneId(phoneId);
        LambdaQueryWrapper<LifeUserDynamics> wrapper = new LambdaQueryWrapper<>();
        dynamicsIdentityHelper.applyPublisherFilter(wrapper, scope);
        wrapper.eq(LifeUserDynamics::getDraft, 1)
                .orderByAsc(LifeUserDynamics::getUpdatedTime);
        List<LifeUserDynamics> drafts = lifeUserDynamicsMapper.selectList(wrapper);
        drafts.forEach(dynamicsIdentityHelper::ensureEntityLegacyPhoneId);
        return drafts;
    }

    public List<LifeUserDynamicsVo> getDianZanList(String phoneId) {
        PublisherScope viewerScope = dynamicsIdentityHelper.resolveFromPhoneId(phoneId);
        List<LifeUserDynamicsVo> lifeUserDynamicsVos = lifeUserDynamicsMapper.selectDianZanList(
                viewerScope.getPhoneUserType(), viewerScope.getPhoneRefId());


        // TODO  bugfix: 过滤掉我拉黑的和拉黑我的。
        //是否关注用户
        LifeUser myLifeUser = new LifeUser();
        StoreUser myStoreUser = new StoreUser();

        if ("user".equals(phoneId.split("_")[0])) {
            String myselfUserPhone = phoneId.split("_")[1];
            myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
        } else {
            String myselfStorePhone = phoneId.split("_")[1];
            myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
        }

        Integer myType ;
        Integer myId ;
        if (myLifeUser != null && myLifeUser.getId() != null) {
            // 我是用户（类型1）
            myType = 1;
            myId = myLifeUser.getId();
        } else {
            // 我是商户（类型2）
            myType = 2;
            myId = myStoreUser.getId();
        }
        // 2. 构建查询条件：(我拉黑的) OR (拉黑我的)
        QueryWrapper<LifeBlacklist> wrapper = new QueryWrapper<>();
        // 2.1 我拉黑的：blocker_type=我的类型 AND blocker_id=我的ID
        // 使用 and() 嵌套子条件，对应 SQL：(blocker_type = ? AND blocker_id = ?)
        wrapper.and(q -> q.eq("blocker_type", myType)
                .eq("blocker_id", myId));
        // 2.2 或者（OR）拉黑我的：blocked_type=我的类型 AND blocked_id=我的ID
        // 使用 or() 嵌套子条件，对应 SQL：OR (blocked_type = ? AND blocked_id = ?)
        wrapper.or(q -> q.eq("blocked_type", myType)
                .eq("blocked_id", myId));
        List<LifeBlacklist> result = lifeBlacklistMapper.selectList(wrapper);
        Set<String> combinedSet = result.stream()
                .flatMap(blacklist -> Stream.of(
                        blacklist.getBlockedPhoneId(),
                        blacklist.getBlockerPhoneId()
                ).filter(Objects::nonNull)) // 过滤null
                .collect(Collectors.toSet());
        List<String> storeUserIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(lifeUserDynamicsVos)){
            for (LifeUserDynamicsVo lifeUserDynamicsVo : lifeUserDynamicsVos) {
                dynamicsIdentityHelper.ensureVoLegacyPhoneId(lifeUserDynamicsVo);
                String comparablePhoneId = dynamicsIdentityHelper.resolveComparablePhoneId(lifeUserDynamicsVo);
                if (comparablePhoneId != null && combinedSet.contains(comparablePhoneId)) {
                    continue;
                }
                if (lifeUserDynamicsVo.getType().equals("2")){
                    if (lifeUserDynamicsVo.getPhoneUserType() != null
                            && lifeUserDynamicsVo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_STORE
                            && lifeUserDynamicsVo.getPhoneRefId() != null) {
                        StoreUser su = storeUserService.getById(lifeUserDynamicsVo.getPhoneRefId());
                        if (su != null && StringUtils.hasText(su.getPhone())) {
                            StoreInfo storeInfo = storeInfoMapper.getStoreNameByPhone(su.getPhone());
                            if (storeInfo != null) {
                                lifeUserDynamicsVo.setStoreName(storeInfo.getStoreName());
                                if (storeInfo.getBusinessSection() != null) {
                                    lifeUserDynamicsVo.setBusinessSection(storeInfo.getBusinessSection().toString());
                                }
                                lifeUserDynamicsVo.setBusinessTypeName(storeInfo.getBusinessTypeName());
                                lifeUserDynamicsVo.setStoreUserId(storeInfo.getId().toString());
                                lifeUserDynamicsVo.setScoreAvg(storeInfo.getScoreAvg() != null ? storeInfo.getScoreAvg() : 0.0);
                                storeUserIdList.add(storeInfo.getId().toString());
                            }
                        }
                    }
                } else if (lifeUserDynamicsVo.getType().equals("1")) {
                    if (lifeUserDynamicsVo.getPhoneUserType() != null
                            && lifeUserDynamicsVo.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_USER
                            && lifeUserDynamicsVo.getPhoneRefId() != null) {
                        LifeUser lifeUser = lifeUserMapper.selectById(lifeUserDynamicsVo.getPhoneRefId());
                        if (lifeUser != null) {
                            lifeUserDynamicsVo.setUserName(lifeUser.getUserName());
                        }
                    }
                }
            }
            Map<String, Integer> ratingCountMap = batchGetRatingCount(storeUserIdList);
            for (LifeUserDynamicsVo lifeUserDynamicsVo : lifeUserDynamicsVos) {
                if ("2".equals(lifeUserDynamicsVo.getType())) {
                    String storeUserId = lifeUserDynamicsVo.getStoreUserId();
                    int ratingCnt = storeUserId != null ? ratingCountMap.getOrDefault(storeUserId, 0) : 0;
                    lifeUserDynamicsVo.setRatingCount(String.valueOf(ratingCnt));
                    if (lifeUserDynamicsVo.getScoreAvg() == null) {
                        lifeUserDynamicsVo.setScoreAvg(0.0);
                    }
                }
            }
        }
        return  lifeUserDynamicsVos;
    }

    public List<LifeUserDynamicsVo> getDynamicsList(Integer page, Integer size, String nickName, String userType, Integer dynamicsType, String releaseStartTime, String releaseEndTime, String storeName) {
        List<LifeUserDynamicsVo> list = lifeUserDynamicsMapper.getDynamicsList(nickName, userType, dynamicsType, releaseStartTime, releaseEndTime, storeName);
        list.forEach(dynamicsIdentityHelper::ensureVoLegacyPhoneId);
        return list;
    }

    public LifeUserDynamicsVo getDynamicsDetail(Integer id) {
        LifeUserDynamicsVo lifeUserDynamicsVo = new LifeUserDynamicsVo();
        List<LifeUserDynamicsVo> lifeUserDynamicsVoList = lifeUserDynamicsMapper.getDynamicsDetail(id);
        if(!CollectionUtils.isEmpty(lifeUserDynamicsVoList)){
            lifeUserDynamicsVo = lifeUserDynamicsVoList.get(0);
            dynamicsIdentityHelper.ensureVoLegacyPhoneId(lifeUserDynamicsVo);
            String imagePath = lifeUserDynamicsVo.getImagePath();
            if(!StringUtils.isEmpty(imagePath)){
                List<String> imagePathList = Arrays.asList(imagePath.split(","));
                lifeUserDynamicsVo.setImagePathList(imagePathList);
            }
        }
        return lifeUserDynamicsVo;
    }

    public int addTransferCount(String id) {
        LambdaUpdateWrapper<LifeUserDynamics> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LifeUserDynamics::getId, id)
                .setSql("transfer_count = transfer_count + 1");
        return lifeUserDynamicsMapper.update(null, lambdaUpdateWrapper);
    }
}
