陶杰
2024-08-22 ee9032d9baf5f33e376d2d2699136e0a7b26bec7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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<BrowseHistory> historyList = browseHistoryMapper.selectList(new QueryWrapper<BrowseHistory>()
                    .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);
        }
    }
}