101captain
2021-10-13 dca045c2e07a14b534038c2f3a4c76cf7a8f769c
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
68
69
70
71
72
package com.panzhihua.common.listen;
 
import static java.util.Objects.isNull;
 
import java.util.ArrayList;
import java.util.List;
 
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.panzhihua.common.exceptions.ServiceException;
import com.panzhihua.common.model.vos.R;
import com.panzhihua.common.model.vos.community.warehouse.WarehouseDonatesExcelVO;
import com.panzhihua.common.service.community.CommunityService;
import com.panzhihua.common.utlis.StringUtils;
 
import lombok.extern.slf4j.Slf4j;
 
/**
 * @title: WarehouseDonatesExcelListen
 * @projectName: 成都呐喊信息技术有限公司-智慧社区项目
 * @description: 爱心义仓物品捐赠导入监听
 * @author: hans
 * @date: 2021/10/09 17:45
 */
@Slf4j
public class WarehouseDonatesExcelListen extends AnalysisEventListener<WarehouseDonatesExcelVO> {
 
    private static final int BATCH_COUNT = 3000;
    private CommunityService communityService;
    private Long communityId;
    private Long registerBy;
    private List<WarehouseDonatesExcelVO> list = new ArrayList<>();
 
    public WarehouseDonatesExcelListen(CommunityService communityService, Long communityId, Long registerBy) {
        this.communityService = communityService;
        this.communityId = communityId;
        this.registerBy = registerBy;
    }
 
    @Override
    public void invoke(WarehouseDonatesExcelVO warehouseDonatesExcelVO, AnalysisContext analysisContext) {
        if (StringUtils.isEmpty(warehouseDonatesExcelVO.getItem())) {
            throw new ServiceException("捐赠物品名称不可为空");
        }
        Integer quantity = warehouseDonatesExcelVO.getQuantity();
        if (isNull(quantity) || quantity <= 0) {
            throw new ServiceException("捐赠数量有误");
        }
        if (StringUtils.isEmpty(warehouseDonatesExcelVO.getName())) {
            warehouseDonatesExcelVO.setIsAnonymous("是");
        }
        warehouseDonatesExcelVO.setCommunityId(this.communityId);
        warehouseDonatesExcelVO.setStatus(2);
        warehouseDonatesExcelVO.setSurplusQuantity(quantity);
        warehouseDonatesExcelVO.setRegisterBy(this.registerBy);
        warehouseDonatesExcelVO.setSigningBy(this.registerBy);
        list.add(warehouseDonatesExcelVO);
        // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
        if (list.size() >= BATCH_COUNT) {
            doAfterAllAnalysed(analysisContext);
            list.clear();
        }
    }
 
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        R r = this.communityService.batchImportWarehouseDonates(list);
        if (!R.isOk(r)) {
            throw new ServiceException(r.getMsg());
        }
    }
}