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 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.LifePinglunVo;
import shop.alien.entity.store.vo.LifeUserDynamicsVo;
import shop.alien.entity.store.vo.StoreCommentVo;
import shop.alien.mapper.*;

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

/**
 * 用户动态
 */
@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;

    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) {
        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());
                    }
                    LambdaUpdateWrapper<LifeLikeRecord> recordLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    recordLambdaUpdateWrapper.eq(LifeLikeRecord::getHuifuId, vo.getId());
                    recordLambdaUpdateWrapper.eq(LifeLikeRecord::getDianzanId, 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();

        //对lifeUserDynamicsVoList数据进行处理，当type为2的时候，把userName的数值赋值到storeName
        lifeUserDynamicsVoList.forEach(item -> {
            if (item.getType().equals("2")) {
                item.setStoreName(item.getUserName());
            }
        });

        if (!StringUtils.isEmpty(type)) {
            lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream().filter(item -> type.equals(item.getType())).collect(Collectors.toList());
        }

        // 查询我的关注信息，构建关注者ID列表
        LambdaQueryWrapper<LifeFans> lifeFansWrapper = new LambdaQueryWrapper<>();
        lifeFansWrapper.eq(LifeFans::getFansId, phoneId);
        List<LifeFans> lifeFansList = lifeFansMapper.selectList(lifeFansWrapper);
        List<String> followList = lifeFansList.stream().map(LifeFans::getFollowedId).collect(Collectors.toList());

        // 查询我的粉丝信息，构建粉丝ID列表
        lifeFansWrapper = new LambdaQueryWrapper<>();
        lifeFansWrapper.eq(LifeFans::getFollowedId, phoneId);
        lifeFansList = lifeFansMapper.selectList(lifeFansWrapper);
        List<String> fansList = lifeFansList.stream().map(LifeFans::getFansId).collect(Collectors.toList());

        // 查询我的点赞记录，构建点赞ID列表
        LambdaQueryWrapper<LifeLikeRecord> likeWrapper = new LambdaQueryWrapper<>();
        likeWrapper.eq(LifeLikeRecord::getDianzanId, phoneId);
        likeWrapper.eq(LifeLikeRecord::getType, "2");
        List<LifeLikeRecord> lifeLikeList = lifeLikeRecordMapper.selectList(likeWrapper);
        List<String> likeList = lifeLikeList.stream().map(LifeLikeRecord::getHuifuId).collect(Collectors.toList());

        // 根据myself参数过滤动态：自己或非本人动态
        if ("1".equals(myself)) {
            lifeUserDynamicsVoList = lifeUserDynamicsVoList.stream().filter(item -> item.getPhoneId().equals(phoneId)).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<StoreCommentVo> rootCommitCount = storeCommentMapper.getRootCommitCount(2, null);
        List<StoreCommentVo> sonCommitCount = storeCommentMapper.getSonCommitCount(2, null);

        // 设置动态对象的状态信息：是否关注对方、是否被关注、是否点赞及评论数量
        // 设置.imagePath。视频为mp4+jpg格式，图片为jpg/png格式。
        for (LifeUserDynamicsVo vo : lifeUserDynamicsVoList) {
            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");
            }
            List<StoreCommentVo> rootList = rootCommitCount.stream().filter(item -> Objects.equals(item.getBusinessId(), vo.getId())).collect(Collectors.toList());
            if (rootList.isEmpty()) {
                vo.setCommentCount(0);
            } else {
                Integer count = rootList.size();
                for (StoreCommentVo storeCommentVo : rootList) {
                    List<StoreCommentVo> sonList = sonCommitCount.stream().filter(item -> Objects.equals(item.getReplyId(), storeCommentVo.getId())).collect(Collectors.toList());
                    if (!sonList.isEmpty()) {
                        count += sonList.get(0).getCommitCount();
                    }
                }
                vo.setCommentCount(count);
            }
        }

        // 如果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 -> {
                String blackPhoneId = dynamics.getPhoneId();
                String userId = dynamics.getStoreOrUserId();

                // 确定用户类型（根据phoneId前缀）
                String userType = blackPhoneId.startsWith("store") ? "1" : (blackPhoneId.startsWith("user") ? "2" : "0");

                // 如果无法识别类型或不在黑名单中，保留该动态
                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;
    }

    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);

        // 查询好友的关注
        LambdaQueryWrapper<LifeFans> lifeFansWrapper = new LambdaQueryWrapper<>();
        lifeFansWrapper.eq(LifeFans::getFansId, phoneId);
        List<LifeFans> lifeFansList = lifeFansMapper.selectList(lifeFansWrapper);
        List<String> followList = lifeFansList.stream().map(LifeFans::getFollowedId).collect(Collectors.toList());

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

        // 查询好友的粉丝
        lifeFansWrapper = new LambdaQueryWrapper<>();
        lifeFansWrapper.eq(LifeFans::getFollowedId, phoneId);
        lifeFansList = lifeFansMapper.selectList(lifeFansWrapper);
        List<String> fansList = lifeFansList.stream().map(LifeFans::getFansId).collect(Collectors.toList());

        // 查询我的粉丝
        lifeFansWrapper = new LambdaQueryWrapper<>();
        lifeFansWrapper.eq(LifeFans::getFollowedId, myselfPhoneId);
        List<LifeFans> mylifeFansList = lifeFansMapper.selectList(lifeFansWrapper);
        List<String> myFansList = mylifeFansList.stream().map(LifeFans::getFansId).collect(Collectors.toList());

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

        //通过phoneId查询userId
        // 判断 targetPhone 是否在 fansList 中 1 已关注 0 未关注
        // 处理 fansList
        fansList = lifeFansList.stream().map(LifeFans::getFansId)
//                .map(id -> id.split("_")[id.split("_").length - 1])
                .collect(Collectors.toList());

        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();

        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);
            storeUser.setUserName(storeUser.getNickName());
            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;

        // 好友动态
        LambdaQueryWrapper<LifeUserDynamics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeUserDynamics::getPhoneId, phoneId);
//        wrapper.eq(LifeUserDynamics::getType, Integer.parseInt(type));
        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);
            return dynamicsVo;
        }).collect(Collectors.toList());

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

        // 我是否点赞，并且查询每条动态的评论数量
        for (LifeUserDynamicsVo dynamicsVo : lifeUserDynamicsVoList) {
            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"));
            dynamicsVo.setCommentCount(commentCount);
            String phoneId1 = dynamicsVo.getPhoneId();
            String storeUserId = "";
            if (phoneId1.startsWith("user_")) {
                LifeUser lifeUser1 = lifeUserMapper.selectOne(new QueryWrapper<LifeUser>().eq("user_phone", phoneId1.substring(5)));
                storeUserId = String.valueOf(lifeUser1.getId());
            } else {
                StoreUser storeUser1 = storeUserService.getOne(new QueryWrapper<StoreUser>().eq("phone", phoneId1.substring(6)));
                storeUserId = String.valueOf(storeUser1.getStoreId());
            }
            dynamicsVo.setStoreUserId(storeUserId);
        }

        // 好友获赞数量
        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) {
//        List<LifeUserDynamics> lifeUserDynamics = lifeUserDynamicsMapper.selectList(new QueryWrapper<LifeUserDynamics>().eq("phone_id", phoneId).eq("draft", 1));

        List<LifeUserDynamics> lifeUserDynamics = lifeUserDynamicsMapper.selectList(
                new QueryWrapper<LifeUserDynamics>()
                        .eq("phone_id", phoneId)
                        .eq("draft", 1)
                        .orderByAsc("updated_time")
        );

//        for (LifeUserDynamics lifeUserDynamic : lifeUserDynamics) {
//            if(lifeUserDynamic.getImagePath().contains(",") && !lifeUserDynamic.getImagePath().contains(".mp4")){
//                lifeUserDynamic.setImagePath(lifeUserDynamic.getImagePath().split(",")[0]);
//            }
//        }
        return lifeUserDynamics;
    }

    public List<LifeUserDynamicsVo> getDianZanList(String phoneId) {
        List<LifeUserDynamicsVo> lifeUserDynamicsVos = lifeUserDynamicsMapper.selectDianZanList(phoneId);


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

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

        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());
        if (!CollectionUtils.isEmpty(lifeUserDynamicsVos)){
            for (LifeUserDynamicsVo lifeUserDynamicsVo : lifeUserDynamicsVos) {
                if(combinedSet.contains(lifeUserDynamicsVo.getPhoneId())){
                    continue;
                }
                if (lifeUserDynamicsVo.getType().equals("2")){
                    String phoneIdNew = lifeUserDynamicsVo.getPhoneId().substring(6);
                     StoreInfo storeInfo=storeInfoMapper.getStoreNameByPhone(phoneIdNew);
                    lifeUserDynamicsVo.setStoreName(storeInfo.getStoreName());
                } else if (lifeUserDynamicsVo.getType().equals("1")) {
                    String phoneIdNew = lifeUserDynamicsVo.getPhoneId().substring(5);
                    //根据手机号查询用户表
                    LifeUser lifeUser = lifeUserMapper.selectOne(new QueryWrapper<LifeUser>().eq("user_phone", phoneIdNew));
                    lifeUserDynamicsVo.setUserName(lifeUser.getUserName());
                }
            }
        }
        return  lifeUserDynamicsVos;
    }

    public List<LifeUserDynamicsVo> getDynamicsList(Integer page, Integer size, String nickName, String userType, Integer dynamicsType, String releaseStartTime, String releaseEndTime) {
        // 查询动态数据并按类型过滤
        return lifeUserDynamicsMapper.getDynamicsList(nickName, userType, dynamicsType, releaseStartTime, releaseEndTime);
    }

    public LifeUserDynamicsVo getDynamicsDetail(Integer id) {
        // 查询动态数据并按类型过滤
        LifeUserDynamicsVo lifeUserDynamicsVo = new LifeUserDynamicsVo();
        List<LifeUserDynamicsVo> lifeUserDynamicsVoList = lifeUserDynamicsMapper.getDynamicsDetail(id);
        if(!CollectionUtils.isEmpty(lifeUserDynamicsVoList)){
            lifeUserDynamicsVo = lifeUserDynamicsVoList.get(0);
            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);
    }
}
