package shop.alien.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import shop.alien.store.util.CommonConstant;
import shop.alien.store.util.LifeDynamicsIdentityHelper;
import shop.alien.store.util.StoreLikeRecordIdentityHelper;
import shop.alien.store.util.StoreLikeRecordIdentityHelper.StoreLikerScope;
import shop.alien.entity.second.SecondGoods;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifePinglunVo;
import shop.alien.mapper.*;
import shop.alien.mapper.second.SecondGoodsMapper;
import shop.alien.store.service.clockin.ClockInRecommendCacheService;
import shop.alien.store.service.dynamics.DynamicsRecommendCacheService;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.util.type.PhoneTypeIdResult;
import shop.alien.util.type.TypeUtil;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 评论服务类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LifeCommentService {

    /** App 点击推送后跳转页面（uni-app 页面路径） */
    private static final String DYNAMICS_LIKE_PUSH_OPEN_PATH =
            "pages/secondHandTransactions/pages/message/noticesAndMessage";

    private final LifeCommentMapper lifeCommentMapper;

    private final StoreCommentMapper storeCommentMapper;

    private final LifeUserDynamicsMapper lifeUserDynamicsMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeActivityMapper lifeActivityMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final StoreMenuMapper storeRecommendMapper;

    private final StoreClockInMapper storeClockInMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final SecondGoodsMapper secondGoodsMapper;

    private final StoreStaffConfigMapper storeStaffConfigMapper;

    private final  CommonRatingMapper commonRatingMapper;

    private final CommonCommentMapper commonCommentMapper;

    private final LifeUserPersonalizationSettingService lifeUserPersonalizationSettingService;

    private final LifeUserPushDeviceService lifeUserPushDeviceService;

    private final UniPushCloudInvokeService uniPushCloudInvokeService;

    private final StoreUserMapper storeUserMapper;

    private final DynamicsRecommendCacheService dynamicsRecommendCacheService;

    private final LifeDynamicsIdentityHelper dynamicsIdentityHelper;

    private final StoreLikeRecordIdentityHelper lifeLikeIdentityHelper;

    private final ClockInRecommendCacheService clockInRecommendCacheService;

    /**
     * 系统app通知开关
     */
    @Value("${alien.unipush.enabled:false}")
    private boolean uniPushOn;

    /**
     * 点赞操作
     * <p>
     * 检查是否已点赞，如果未点赞则插入点赞记录并更新对应表的点赞数
     * </p>
     *
     * @param userId  用户ID
     * @param huifuId 被点赞对象ID（评论ID/动态ID/活动ID等）
     * @param type    点赞类型（1-评论 2-社区动态 3-活动 4-推荐菜 5-店铺打卡 6-二手商品 7-律师评分 8-点赞员工）
     * @return 更新影响的行数，0表示已点赞或操作失败
     */
    public int like(String userId, String huifuId, String type) {
        log.info("执行点赞操作，userId={}，huifuId={}，type={}", userId, huifuId, type);
        
        // 参数校验
        if (!StringUtils.hasText(userId)) {
            log.warn("点赞失败，用户ID为空");
            return 0;
        }
        if (!StringUtils.hasText(huifuId)) {
            log.warn("点赞失败，被点赞对象ID为空");
            return 0;
        }
        if (!StringUtils.hasText(type)) {
            log.warn("点赞失败，点赞类型为空");
            return 0;
        }
        
        try {
            StoreLikerScope likerScope = lifeLikeIdentityHelper.resolveFromDianzanId(userId);
            LambdaQueryWrapper<LifeLikeRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LifeLikeRecord::getType, type)
                    .eq(LifeLikeRecord::getHuifuId, huifuId)
                    .eq(LifeLikeRecord::getDeleteFlag, CommonConstant.DELETE_FLAG_UNDELETE);
            lifeLikeIdentityHelper.applyLikerFilter(queryWrapper, likerScope);
            List<LifeLikeRecord> recordList = lifeLikeRecordMapper.selectList(queryWrapper);
            
            // 如果已有点赞记录，直接返回0（表示已点赞）
            if (!CollectionUtils.isEmpty(recordList)) {
                log.info("用户已点赞，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return 0;
            }
            
            // 插入点赞记录
            LifeLikeRecord lifeLikeRecord = new LifeLikeRecord();
            lifeLikeRecord.setDianzanId(userId);
            lifeLikeIdentityHelper.normalizeBeforeSave(lifeLikeRecord);
            lifeLikeRecord.setCreatedTime(new Date());
            lifeLikeRecord.setHuifuId(huifuId);
            lifeLikeRecord.setType(type);
            int insertResult = lifeLikeRecordMapper.insert(lifeLikeRecord);
            
            if (insertResult <= 0) {
                log.warn("插入点赞记录失败，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return 0;
            }
            
            // 根据类型更新对应表的点赞数
            int updateResult = updateLikeCountByType(huifuId, type);
            // DB 已成功更新点赞计数后，仅尽力同步推荐 Redis（动态/打卡）；异常已捕获，不改变返回值及后续通知逻辑
            if (updateResult > 0) {
                try {
                    dynamicsRecommendCacheService.trySyncLikeCache(userId, huifuId, type, true, 1);
                } catch (Exception e) {
                    log.error("推荐动态缓存同步失败(点赞)，不影响主流程 userId={} huifuId={} type={}", userId, huifuId, type, e);
                }
                try {
                    clockInRecommendCacheService.trySyncLikeCache(userId, huifuId, type, true, 1);
                } catch (Exception e) {
                    log.error("推荐打卡缓存同步失败(点赞)，不影响主流程 userId={} huifuId={} type={}", userId, huifuId, type, e);
                }
            }

            // 动态点赞：按「被点赞动态的发布者」的个性化设置决定是否通知（接收方是否愿意收点赞类通知）
            if (updateResult > 0 && CommonConstant.LIKE_TYPE_DYNAMICS.equals(type)) {
                Integer receiverLifeUserId = resolveLifeUserIdFromDynamicsAuthorPhoneId(huifuId);
                boolean suppressNotice = receiverLifeUserId != null
                        && lifeUserPersonalizationSettingService.shouldSuppressLikeRelatedNotice(receiverLifeUserId);
                if (!suppressNotice) {
                    try {
                        insertNotice(userId, huifuId, type);
                    } catch (Exception e) {
                        log.error("动态点赞站内信保存失败, huifuId={}", huifuId, e);
                    }

                    // 发送系统通知开关
                    if(uniPushOn){
                        try {
                            sendDynamicsLikeAppPushByDynamicsId(Integer.parseInt(huifuId.trim()));
                        } catch (NumberFormatException e) {
                            log.warn("动态点赞 App 推送跳过：huifuId 非合法动态 id, huifuId={}", huifuId);
                        } catch (Exception e) {
                            log.warn("动态点赞 App 推送失败, huifuId={}, err={}", huifuId, e.getMessage());
                        }
                    }
                }
            }
            
            log.info("点赞操作完成，userId={}，huifuId={}，type={}，更新结果={}", userId, huifuId, type, updateResult);
            return updateResult;
        } catch (Exception e) {
            log.error("点赞操作异常，userId={}，huifuId={}，type={}，异常信息：{}", userId, huifuId, type, e.getMessage(), e);
            return 0;
        }
    }
    
    /**
     * 根据类型更新对应表的点赞数
     *
     * @param huifuId 被点赞对象ID
     * @param type    点赞类型
     * @return 更新影响的行数
     */
    private int updateLikeCountByType(String huifuId, String type) {
        try {
            if (CommonConstant.LIKE_TYPE_COMMENT.equals(type)) {
                // 类型1：评论
                LambdaUpdateWrapper<StoreComment> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreComment::getId, huifuId)
                        .setSql("like_count = like_count + 1");
                return storeCommentMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_DYNAMICS.equals(type)) {
                // 类型2：社区动态
                LambdaUpdateWrapper<LifeUserDynamics> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(LifeUserDynamics::getId, huifuId)
                        .setSql("dianzan_count = dianzan_count + 1");
                return lifeUserDynamicsMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_ACTIVITY.equals(type)) {
                // 类型3：活动
                LambdaUpdateWrapper<LifeActivity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(LifeActivity::getId, huifuId)
                        .setSql("dianzan_count = dianzan_count + 1");
                return lifeActivityMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_MENU.equals(type)) {
                // 类型4：推荐菜
                LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreMenu::getId, huifuId)
                        .setSql("like_count = like_count + 1");
                return storeRecommendMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_CLOCK_IN.equals(type)) {
                // 类型5：店铺打卡
                LambdaUpdateWrapper<StoreClockIn> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreClockIn::getId, huifuId)
                        .setSql("like_count = like_count + 1");
                return storeClockInMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_SECOND_GOODS.equals(type)) {
                // 类型6：二手商品
                LambdaUpdateWrapper<SecondGoods> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(SecondGoods::getId, huifuId)
                        .setSql("like_count = like_count + 1");
                return secondGoodsMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_STAFF.equals(type)) {
                // 类型8：点赞员工
                LambdaUpdateWrapper<StoreStaffConfig> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreStaffConfig::getId, huifuId)
                        .setSql("like_count = like_count + 1");
                return storeStaffConfigMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_STORE.equals(type)) {
                // 类型1：评论
                LambdaUpdateWrapper<StoreComment> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreComment::getId, huifuId)
                        .setSql("like_count = like_count + 1");
                return storeCommentMapper.update(null, updateWrapper);
            } else if (CommonConstant.RATING_LIKE.equals(type)) {
                // 11-评价点赞：更新评价表点赞数
                return commonRatingMapper.update(null, new UpdateWrapper<CommonRating>()
                        .setSql("like_count = like_count + 1")
                        .eq("id", huifuId));
            } else if (CommonConstant.COMMENT_LIKE.equals(type) || CommonConstant.DYNAMIC_LIKE.equals(type) || CommonConstant.CLOCK_IN_LIKE.equals(type) || CommonConstant.SECOND_HAND_LIKE.equals(type) || CommonConstant.STORE_DYNAMIC_LIKE.equals(type)) {
                // 12-评论点赞：更新评论表点赞数
                return commonCommentMapper.update(null, new UpdateWrapper<CommonComment>()
                        .setSql("like_count = like_count + 1")
                        .eq("id", huifuId));
            } else {
                log.warn("未知的点赞类型，type={}，huifuId={}", type, huifuId);
                return 0;
            }
        } catch (Exception e) {
            log.error("更新点赞数异常，type={}，huifuId={}，异常信息：{}", type, huifuId, e.getMessage(), e);
            return 0;
        }
    }

    /**
     * 根据动态主键查发布者 phoneId，仅当为 C 端 user_ 前缀时解析为 life_user.id；门店动态 store_ 无 C 端个性化表则返回 null（不拦截通知）。
     */
    private Integer resolveLifeUserIdFromDynamicsAuthorPhoneId(String dynamicsIdStr) {
        if (!StringUtils.hasText(dynamicsIdStr)) {
            return null;
        }
        try {
            int dynamicsId = Integer.parseInt(dynamicsIdStr.trim());
            LifeUserDynamics dynamics = lifeUserDynamicsMapper.selectById(dynamicsId);
            if (dynamics == null) {
                return null;
            }
            if (dynamics.getPhoneUserType() != null
                    && dynamics.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_USER
                    && dynamics.getPhoneRefId() != null) {
                return dynamics.getPhoneRefId();
            }
            return null;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 发送通知
     */
    private void insertNotice(String userId, String huifuId, String type) {
        if ("2".equals(type)) {
            LifeNotice lifeNotice = new LifeNotice();
            lifeNotice.setSenderId(userId);
            lifeNotice.setBusinessId(Integer.parseInt(huifuId));
            lifeNotice.setNoticeType(0);
            lifeNotice.setTitle("动态通知");
            lifeNotice.setContext("点赞了你的动态");
            LifeUserDynamics lifeUserDynamics = lifeUserDynamicsMapper.selectById(Integer.parseInt(huifuId));
            lifeNotice.setReceiverId(lifeUserDynamics == null
                    ? null
                    : dynamicsIdentityHelper.resolveComparablePhoneId(lifeUserDynamics));
            lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
            lifeNoticeMapper.insert(lifeNotice);
        }
    }

    /**
     * 仅发起 App 推送（uniCloud），与 {@link #insertNotice} 独立；未配置、无 cid 时静默返回。
     */
    private void sendDynamicsLikeAppPushByDynamicsId(int dynamicsId) {
        LifeUserDynamics dynamics = lifeUserDynamicsMapper.selectById(dynamicsId);
        sendDynamicsLikeAppPushOnly(dynamics, "动态通知", "点赞了你的动态", dynamicsId);
    }

    private void sendDynamicsLikeAppPushOnly(LifeUserDynamics dynamics, String title, String content, int dynamicsId) {
        if (dynamics == null) {
            return;
        }
        String phoneId = dynamicsIdentityHelper.resolveComparablePhoneId(dynamics);
        if (!StringUtils.hasText(phoneId)) {
            return;
        }
        List<String> cids = resolvePushClientIdsForDynamicsAuthor(phoneId);
        if (CollectionUtils.isEmpty(cids)) {
            return;
        }
        Map<String, Object> payload = new HashMap<>(12);
        payload.put("scene", "dynamics_like");
        payload.put("dynamicsId", dynamicsId);
        payload.put("noticeType", 0);
        payload.put("path", DYNAMICS_LIKE_PUSH_OPEN_PATH);
        uniPushCloudInvokeService.sendToClientIds(cids, title, content, payload);
    }

    private List<String> resolvePushClientIdsForDynamicsAuthor(String phoneId) {
        if (phoneId.startsWith("user_")) {
            String phone = phoneId.substring("user_".length());
            if (!StringUtils.hasText(phone)) {
                return Collections.emptyList();
            }
            LifeUser u = lifeUserMapper.selectOne(new LambdaQueryWrapper<LifeUser>()
                    .eq(LifeUser::getUserPhone, phone)
                    .eq(LifeUser::getDeleteFlag, 0)
                    .last("LIMIT 1"));
            if (u == null) {
                return Collections.emptyList();
            }
            return lifeUserPushDeviceService.listPushClientIdsByUserId(u.getId(), PushDeviceOwnerType.USER.getCode());
        }
        if (phoneId.startsWith("store_")) {
            String phone = phoneId.substring("store_".length());
            if (!StringUtils.hasText(phone)) {
                return Collections.emptyList();
            }
            StoreUser su = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>()
                    .eq(StoreUser::getPhone, phone)
                    .eq(StoreUser::getDeleteFlag, 0)
                    .last("LIMIT 1"));
            if (su == null) {
                return Collections.emptyList();
            }
            return lifeUserPushDeviceService.listPushClientIdsByUserId(su.getId(), PushDeviceOwnerType.STORE.getCode());
        }
        return Collections.emptyList();
    }

    /**
     * 取消点赞操作
     * <p>
     * 检查是否已点赞，如果已点赞则删除点赞记录并更新对应表的点赞数
     * </p>
     *
     * @param userId  用户ID
     * @param huifuId 被取消点赞对象ID（评论ID/动态ID/活动ID等）
     * @param type    点赞类型（1-评论 2-社区动态 3-活动 4-推荐菜 5-店铺打卡 6-二手商品 7-律师评分 8-点赞员工）
     * @return 更新影响的行数，0表示未点赞或操作失败
     */
    public int cancelLike(String userId, String huifuId, String type) {
        log.info("执行取消点赞操作，userId={}，huifuId={}，type={}", userId, huifuId, type);
        
        // 参数校验
        if (!StringUtils.hasText(userId)) {
            log.warn("取消点赞失败，用户ID为空");
            return 0;
        }
        if (!StringUtils.hasText(huifuId)) {
            log.warn("取消点赞失败，被取消点赞对象ID为空");
            return 0;
        }
        if (!StringUtils.hasText(type)) {
            log.warn("取消点赞失败，点赞类型为空");
            return 0;
        }
        
        try {
            StoreLikerScope likerScope = lifeLikeIdentityHelper.resolveFromDianzanId(userId);
            LambdaQueryWrapper<LifeLikeRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LifeLikeRecord::getHuifuId, huifuId)
                    .eq(LifeLikeRecord::getType, type)
                    .eq(LifeLikeRecord::getDeleteFlag, CommonConstant.DELETE_FLAG_UNDELETE);
            lifeLikeIdentityHelper.applyLikerFilter(queryWrapper, likerScope);
            List<LifeLikeRecord> recordList = lifeLikeRecordMapper.selectList(queryWrapper);
            
            // 如果没有点赞记录，直接返回0（表示未点赞）
            if (CollectionUtils.isEmpty(recordList)) {
                log.info("用户未点赞，无需取消，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return 0;
            }
            
            // 删除点赞记录（逻辑删除）
            LambdaUpdateWrapper<LifeLikeRecord> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LifeLikeRecord::getHuifuId, huifuId)
                    .eq(LifeLikeRecord::getType, type)
                    .eq(LifeLikeRecord::getDeleteFlag, CommonConstant.DELETE_FLAG_UNDELETE);
            lifeLikeIdentityHelper.applyLikerFilter(updateWrapper, likerScope);
            int deleteResult = lifeLikeRecordMapper.delete(updateWrapper);
            
            if (deleteResult <= 0) {
                log.warn("删除点赞记录失败，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return 0;
            }
            
            // 根据类型更新对应表的点赞数
            int updateResult = decreaseLikeCountByType(huifuId, type);
            // DB 已成功扣减点赞计数后，仅尽力同步推荐 Redis；异常已捕获，不改变返回值
            if (updateResult > 0) {
                try {
                    dynamicsRecommendCacheService.trySyncLikeCache(userId, huifuId, type, false, -1);
                } catch (Exception e) {
                    log.error("推荐动态缓存同步失败(取消点赞)，不影响主流程 userId={} huifuId={} type={}", userId, huifuId, type, e);
                }
                try {
                    clockInRecommendCacheService.trySyncLikeCache(userId, huifuId, type, false, -1);
                } catch (Exception e) {
                    log.error("推荐打卡缓存同步失败(取消点赞)，不影响主流程 userId={} huifuId={} type={}", userId, huifuId, type, e);
                }
            }

            log.info("取消点赞操作完成，userId={}，huifuId={}，type={}，更新结果={}", userId, huifuId, type, updateResult);
            return updateResult;
        } catch (Exception e) {
            log.error("取消点赞操作异常，userId={}，huifuId={}，type={}，异常信息：{}", userId, huifuId, type, e.getMessage(), e);
            return 0;
        }
    }
    
    /**
     * 根据类型减少对应表的点赞数
     *
     * @param huifuId 被取消点赞对象ID
     * @param type    点赞类型
     * @return 更新影响的行数
     */
    private int decreaseLikeCountByType(String huifuId, String type) {
        try {
            if (CommonConstant.LIKE_TYPE_COMMENT.equals(type)) {
                // 类型1：评论
                LambdaUpdateWrapper<StoreComment> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreComment::getId, huifuId)
                        .gt(StoreComment::getLikeCount, 0)
                        .setSql("like_count = like_count - 1");
                return storeCommentMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_DYNAMICS.equals(type)) {
                // 类型2：社区动态
                LambdaUpdateWrapper<LifeUserDynamics> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(LifeUserDynamics::getId, huifuId)
                        .gt(LifeUserDynamics::getDianzanCount, 0)
                        .setSql("dianzan_count = dianzan_count - 1");
                return lifeUserDynamicsMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_ACTIVITY.equals(type)) {
                // 类型3：活动
                LambdaUpdateWrapper<LifeActivity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(LifeActivity::getId, huifuId)
                        .gt(LifeActivity::getDianzanCount, 0)
                        .setSql("dianzan_count = dianzan_count - 1");
                return lifeActivityMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_MENU.equals(type)) {
                // 类型4：推荐菜
                LambdaUpdateWrapper<StoreMenu> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreMenu::getId, huifuId)
                        .gt(StoreMenu::getLikeCount, 0)
                        .setSql("like_count = like_count - 1");
                return storeRecommendMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_CLOCK_IN.equals(type)) {
                // 类型5：店铺打卡
                LambdaUpdateWrapper<StoreClockIn> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreClockIn::getId, huifuId)
                        .gt(StoreClockIn::getLikeCount, 0)
                        .setSql("like_count = like_count - 1");
                return storeClockInMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_SECOND_GOODS.equals(type)) {
                // 类型6：二手商品
                LambdaUpdateWrapper<SecondGoods> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(SecondGoods::getId, huifuId)
                        .gt(SecondGoods::getLikeCount, 0)
                        .setSql("like_count = like_count - 1");
                return secondGoodsMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_STAFF.equals(type)) {
                // 类型8：点赞员工
                LambdaUpdateWrapper<StoreStaffConfig> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreStaffConfig::getId, Integer.parseInt(huifuId))
                        .setSql("like_count = IF(like_count > 0, like_count - 1, 0)");
                return storeStaffConfigMapper.update(null, updateWrapper);
            } else if (CommonConstant.LIKE_TYPE_STORE.equals(type)) {
            // 类型8：点赞店铺
                LambdaUpdateWrapper<StoreComment> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreComment::getId, huifuId)
                        .gt(StoreComment::getLikeCount, 0)
                        .setSql("like_count = like_count - 1");
                return storeCommentMapper.update(null, updateWrapper);
            }  else if (CommonConstant.RATING_LIKE.equals(type)) {
                // 11-评价点赞：更新评价表点赞数
                return commonRatingMapper.update(null, new UpdateWrapper<CommonRating>()
                        .setSql("like_count = like_count - 1")
                        .eq("id", huifuId));
            } else if (CommonConstant.COMMENT_LIKE.equals(type) || CommonConstant.DYNAMIC_LIKE.equals(type) || CommonConstant.CLOCK_IN_LIKE.equals(type) || CommonConstant.SECOND_HAND_LIKE.equals(type) || CommonConstant.STORE_DYNAMIC_LIKE.equals(type)) {
                // 12-评论点赞：更新评论表点赞数
                return commonCommentMapper.update(null, new UpdateWrapper<CommonComment>()
                        .setSql("like_count = like_count - 1")
                        .eq("id", huifuId));
            }
            else {
                log.warn("未知的点赞类型，type={}，huifuId={}", type, huifuId);
                return 0;
            }
        } catch (Exception e) {
            log.error("减少点赞数异常，type={}，huifuId={}，异常信息：{}", type, huifuId, e.getMessage(), e);
            return 0;
        }
    }

    public int addOrUpdateStore(LifeComment store) {
        if (StringUtils.isEmpty(store.getId())) {
            Date nowDate = new Date(System.currentTimeMillis());
            store.setPinglunTime(new java.sql.Timestamp(nowDate.getTime()));
            if (StringUtils.isEmpty(store.getHuifuId())) {
                store.setHuifuId(store.getId());
            }
            return lifeCommentMapper.insert(store);
        } else {
            return lifeCommentMapper.updateById(store);
        }
    }

    public Map<String, List<LifePinglunVo>> getAppealByStoreId(String userId, String storeId, String idHuifu, String pinglunLevel, String pinglunDays, String pinglunLeibie) {
        LambdaUpdateWrapper<LifeComment> wrapper = new LambdaUpdateWrapper<>();
        if (userId != null && !userId.isEmpty()) {
            wrapper.eq(LifeComment::getUserId, userId);
        }
        if (storeId != null && !storeId.isEmpty()) {
            wrapper.eq(LifeComment::getStoreId, storeId);
        }
        if (pinglunLevel != null && !pinglunLevel.isEmpty()) {
            List<String> list = Arrays.stream(pinglunLevel.split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());
            wrapper.in(LifeComment::getPinglunLevel, list);
        }
        if (pinglunLeibie != null && !pinglunLeibie.isEmpty()) {
            wrapper.eq(LifeComment::getPinglunLeibie, pinglunLeibie);
        }
        wrapper.orderByDesc(LifeComment::getPinglunTime);
        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);
            }
        }
        Map<String, List<LifePinglunVo>> listMap;
        listMap = lifePinglunVos.stream().filter(item -> !StringUtils.isEmpty(item.getHuifuId())).collect(Collectors.groupingBy(LifePinglunVo::getHuifuId));
        if (!StringUtils.isEmpty(idHuifu) && !CollectionUtils.isEmpty(listMap)) {
            listMap.forEach((key, value) -> {
                value.sort(Comparator.comparing(LifePinglunVo::getPinglunTime));
            });
            if (idHuifu.equals("1")) {
                listMap = listMap.entrySet().stream()
                        .filter(entry -> entry.getValue().size() > 1)
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
            } else if (idHuifu.equals("0")) {
                listMap = listMap.entrySet().stream()
                        .filter(entry -> entry.getValue().size() == 1)
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
            }
        }
        if (!StringUtils.isEmpty(pinglunDays) && !CollectionUtils.isEmpty(lifePingluns)) {
            Integer days = Integer.valueOf(pinglunDays);
            Iterator<Map.Entry<String, List<LifePinglunVo>>> iterator = listMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<LifePinglunVo>> entry = iterator.next();
                List<LifePinglunVo> lifePinglunList = entry.getValue();
                if (!lifePinglunList.isEmpty()) {
                    Date firstPinglunTime = lifePinglunList.get(0).getPinglunTime();
                    LocalDate firstLocalDate = firstPinglunTime.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();
                    LocalDate currentDate = LocalDate.now();
                    long daysBetween = ChronoUnit.DAYS.between(firstLocalDate, currentDate);
                    if (daysBetween > days) {
                        iterator.remove();
                    }
                }
            }
        }
        return listMap;
    }

    /**
     * 分页查询商家端顾客评论
     *
     * @param pageNum     页数
     * @param pageSize    页容
     * @param storeId     店铺id
     * @param isReply     是否回复,0:全部;1:已回复;2:未回复;
     * @param commentType 评论类别,0:全部;1:好评;2:中评;3:差评;
     * @param date        查询日期
     * @return IPage<LifeComment>
     */
    public IPage<LifeComment> getStoreComment(Integer pageNum, Integer pageSize, Integer storeId, Integer isReply, Integer commentType, String date) {
        IPage<LifeComment> iPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LifeComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != storeId, LifeComment::getStoreId, storeId);
        wrapper.gt(LifeComment::getPinglunTime, date);
        return lifeCommentMapper.selectPage(iPage, wrapper);
    }
}
