package com.mzl.flower.service.customer; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.mzl.flower.config.exception.ValidationException; import com.mzl.flower.config.security.SecurityUtils; import com.mzl.flower.entity.customer.BrowseHistory; import com.mzl.flower.mapper.customer.BrowseHistoryMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional @Slf4j public class BrowseService { private final BrowseHistoryMapper browseHistoryMapper; public BrowseService(BrowseHistoryMapper browseHistoryMapper) { this.browseHistoryMapper = browseHistoryMapper; } @Async public synchronized void addBrowseHistory(String userId, Long flowerId) { try { if (flowerId == null || flowerId == 0) { //throw new ValidationException("鲜花商品ID不能为空"); return; } // 添加浏览记录逻辑 List historyList = browseHistoryMapper.selectList(new QueryWrapper() .eq("user_id", userId) .eq("flower_id", flowerId) .orderByDesc("browse_count") ); BrowseHistory history = null; if (historyList != null && historyList.size() > 0) { history = historyList.get(0); for (int i = 1; i < historyList.size(); i++) { BrowseHistory h = historyList.get(i); history.setBrowseCount(history.getBrowseCount() + h.getBrowseCount()); browseHistoryMapper.deleteById(h.getId()); } } if (history == null) { history = new BrowseHistory(); history.setUserId(userId); history.setFlowerId(flowerId); history.setBrowseCount(1); history.create(userId); browseHistoryMapper.insert(history); } else { history.update(userId); history.setBrowseCount(history.getBrowseCount() + 1); browseHistoryMapper.updateById(history); } } catch (Exception e) { log.error(e.getMessage(), e); } } }