fix
Helius
2021-07-23 bfb8d3b963f9653ac420b965f1eecadb887ca537
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package com.xzx.gc.order.service;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzx.gc.common.constant.*;
import com.xzx.gc.common.exception.RestException;
import com.xzx.gc.common.utils.*;
import com.xzx.gc.common.utils.ali.SmsUtil;
import com.xzx.gc.entity.*;
import com.xzx.gc.model.JsonResult;
import com.xzx.gc.model.admin.*;
import com.xzx.gc.model.order.QueryRuleManageDetailDTO;
import com.xzx.gc.model.order.SettlePageDTO;
import com.xzx.gc.model.order.UpdateRoyaltyRuleDTO;
import com.xzx.gc.order.mapper.*;
import com.xzx.gc.util.DoubleUtil;
import com.xzx.gc.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
@Service
@Transactional
@Slf4j
public class WeightItemPriceService {
 
    @Autowired
    private WeightItemPriceMapper weightItemPriceMapper;
 
    @Autowired
    private OtherUserService otherUserService;
 
    @Autowired
    private SysMessageMapper sysMessageMapper;
 
    @Autowired
    private CityPartnerService cityPartnerService;
    @Autowired
    private PartnerAccountService partnerAccountService;
    @Autowired
    private AccountMapper accountMapper;
 
    @Autowired
    private AccountService accountService;
 
    @Autowired
    private CityPartnerMapper cityPartnerMapper;
 
    @Autowired
    private BusinessUtil businessUtil;
 
    @Autowired
    private WeightItemPriceLogMapper weightItemPriceLogMapper;
 
    @Autowired
    private RedPaperRuleMapper redPaperRuleMapper;
 
    @Autowired
    private PackageGoodsInfoService packageGoodsInfoService;
 
    @Autowired
    private RebateWeightPriceMapper rebateWeightPriceMapper;
 
    @Autowired
    private RebateWeightPriceLogMapper rebateWeightPriceLogMapper;
 
    @Autowired
    private RedPaperRuleService redPaperRuleService;
 
    @Autowired
    private IdUtils idUtils;
    @Autowired
    private PayInfoMapper payInfoMapper;
 
    @Autowired
    private OrderSettleDeductService orderSettleDeductService;
 
    @Autowired
    private OrderSettleService orderSettleService;
 
    @Autowired
    private SessionUtil sessionUtil;
 
 
    public void addBatch(List<WeightItemPrice> list) {
        String now = DateUtil.now();
        for (WeightItemPrice weightItemPrice : list) {
            weightItemPrice.setCreateTime(now);
            //未审核
            weightItemPrice.setStatus("1");
        }
        weightItemPriceMapper.insertList(list);
    }
 
    public void updateById(WeightItemPrice weightItemPrice) {
        weightItemPriceMapper.updateByPrimaryKeySelective(weightItemPrice);
    }
 
    /**
     * 明细列表 不包含异常的且金额>0
     *
     * @param dto
     * @return
     */
    public List<WeightItemPrice> queryRuleManageDetail(QueryRuleManageDetailDTO dto) {
        //处理时间格式
        dto.setStartTime(DateUtils.changeTimeBigin(dto.getStartTime()));
        dto.setEndTime(DateUtils.changeTimeEnd(dto.getEndTime()));
        List<WeightItemPrice> royaltyList = weightItemPriceMapper.queryWeightItemList(dto);
        return royaltyList;
    }
 
    /**
     * 结算提成
     *
     * @param model
     */
    public void updateRoyaltyRule(UpdateRoyaltyRuleDTO model) {
        //明细
        List<WeightItemPrice> weightList = model.getRoyaltyList();
        if (CollUtil.isEmpty(weightList)) {
            throw new RestException("未选择任何明细");
        }
 
        //总金额
        BigDecimal sumMoney = BigDecimal.ZERO;
        //异常金额
        BigDecimal expeptionMoney = BigDecimal.ZERO;
        //实际金额
        BigDecimal money;
 
        String receiver = model.getReceiver();
        OtherUserInfo receiverInfo = otherUserService.findById(receiver);
        String partnerId = receiverInfo.getPartnerId();
        CityPartner cityPartner = cityPartnerService.findById(Convert.toInt(partnerId));
 
        RedPaperRule one = redPaperRuleService.findByPackageIdAndRuleType(UserEnum.提成规则.getValue(), weightList.get(0).getPackageId());
        if (one == null) {
            throw new RestException("当前打包站提成规则未开启");
        }
        for (WeightItemPrice itemModel : weightList) {
            //更新状态
            WeightItemPrice weightItemPrice = new WeightItemPrice();
            weightItemPrice.setId(Convert.toLong(itemModel.getId()));
            weightItemPrice.setUpdateTime(DateUtil.now());
            weightItemPrice.setStatus(itemModel.getStatus());
            updateById(weightItemPrice);
 
            if (!OrderEnum.异常.getValue().equals(itemModel.getStatus())) {
                sumMoney = sumMoney.add(new BigDecimal(itemModel.getSettleMoney()));
            } else {
                expeptionMoney = expeptionMoney.add(new BigDecimal(itemModel.getSettleMoney()));
            }
        }
 
        //扣除项
        OrderSettleDeduct orderSettleDeduct = model.getOrderSettleDeduct();
        BigDecimal deductMoney = BigDecimal.ZERO;
        if (orderSettleDeduct != null) {
            deductMoney = NumberUtil.add(Convert.toBigDecimal(orderSettleDeduct.getFrockMoney(), BigDecimal.ZERO), Convert.toBigDecimal(orderSettleDeduct.getHouseMoney(), BigDecimal.ZERO)
                    , Convert.toBigDecimal(orderSettleDeduct.getInsuranceMoney(), BigDecimal.ZERO), Convert.toBigDecimal(orderSettleDeduct.getPowerMoney(), BigDecimal.ZERO),
                    Convert.toBigDecimal(orderSettleDeduct.getVehicleMoney(), BigDecimal.ZERO));
            money = NumberUtil.sub(sumMoney, deductMoney);
        } else {
            money = sumMoney;
        }
 
        List<WeightItemPrice> collect = weightList.stream().filter(x -> !x.getStatus().equals(OrderEnum.异常.getValue())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
 
            String startTime = model.getStartTime();
            String endTime = model.getEndTime();
 
 
            //按入库时间升序
            CollUtil.sort(collect, (o1, o2) -> {
                if (DateUtil.compare(DateUtil.parse(o1.getStorageTime(), DateUtils.DATE_FORMAT_YMD), DateUtil.parse(o2.getStorageTime(), DateUtils.DATE_FORMAT_YMD)) > 0) {
                    return -1;
                } else if (DateUtil.compare(DateUtil.parse(o1.getStorageTime(), DateUtils.DATE_FORMAT_YMD), DateUtil.parse(o2.getStorageTime(), DateUtils.DATE_FORMAT_YMD)) == 0) {
                    return 0;
                } else {
                    return 1;
                }
            });
 
            String status = collect.get(0).getStatus();
 
            if (StrUtil.isBlank(startTime)) {
                startTime = CollUtil.getFirst(collect).getStorageTime();
            }
 
            if (StrUtil.isBlank(endTime)) {
                endTime = CollUtil.getLast(collect).getStorageTime();
            }
 
            startTime = DateUtil.parse(startTime).toString(DateUtils.DATE_FORMAT_YMD);
            endTime = DateUtil.parse(endTime).toString(DateUtils.DATE_FORMAT_YMD);
            //新增提成表
            OrderSettle orderSettle = new OrderSettle();
            String settleId = idUtils.generate("JS", 9);
            orderSettle.setId(settleId);
            orderSettle.setCreateUserId(sessionUtil.getCurrentUser().getId() + "");
            orderSettle.setUserId(receiver);
            orderSettle.setSumMoney(sumMoney.toString());
            orderSettle.setDeductMoney(deductMoney.toString());
            orderSettle.setMoney(money.toString());
            orderSettle.setExceptionMoney(expeptionMoney.toString());
            orderSettle.setTimeList(startTime + "~" + endTime);
            orderSettle.setStatus(Convert.toShort(status));
            orderSettleService.add(orderSettle);
 
            //结算扣款
            if (orderSettleDeduct != null) {
                orderSettleDeduct.setSettleId(settleId);
                orderSettleDeductService.add(orderSettleDeduct);
            }
 
            //需要操作环保比
            if (OrderEnum.已结算并支付.getValue().equals(status)) {
 
                //回收员加钱
                AccountInfo accountInfo = accountService.findByUserId(receiver);
                Map payMap = new HashMap();
                String payOrderId = idUtils.generate("ZF", 0);
                payMap.put("payOrderId", payOrderId);
                payMap.put("createUserId", accountInfo.getUserId());
                payMap.put("money", money);
                payMap.put("accountId", accountInfo.getAccountId());
                payMap.put("payType", PayEnum.提成.getValue());
                payMap.put("status", PayEnum.已支付.getValue());
                payMap.put("createTime", DateUtil.now());
                payInfoMapper.payInfoAdd(payMap);
                accountService.addOtherUserAccount(accountInfo, CommonEnum.提成.getValue(), payOrderId, money.toString());
 
                //回收员消息
                String message = "您已经结算:+" + money + "元,提成单号:" + settleId + ",请注意查收.";
                sysMessageMapper.insertMessage(message, receiver, "", "1", "提成", DateUtil.now());
 
                //合伙人扣钱
                partnerAccountService.addPartnerAccountLog(money.toString(), cityPartner, settleId);
                String message1 = "您已经结算:-" + money + "元,提成单号:" + settleId + ",请注意检查.";
                sysMessageMapper.insertMessage(message1, cityPartner.getUserId(), "", "1", "提成", DateUtil.now());
            }
 
            //发送提成短信
            Map<String, String> map = new HashMap<>();
            map.put("name", receiverInfo.getName());
            map.put("sumMoney", orderSettle.getSumMoney());
            map.put("time", orderSettle.getTimeList());
            map.put("money", orderSettle.getMoney());
            map.put("insuranceMoney", "0");
            map.put("vehicleMoney", "0");
            map.put("frockMoney", "0");
            map.put("houseMoney", "0");
            map.put("powerMoney", "0");
            if (orderSettleDeduct != null) {
                map.put("insuranceMoney", orderSettleDeduct.getInsuranceMoney());
                map.put("vehicleMoney", orderSettleDeduct.getVehicleMoney());
                map.put("frockMoney", orderSettleDeduct.getFrockMoney());
                map.put("houseMoney", orderSettleDeduct.getHouseMoney());
                map.put("powerMoney", orderSettleDeduct.getPowerMoney());
            }
            String content = StrUtil.format("{name},辛苦了.结算周期:{time},应付款总额:{sumMoney},扣除费用:保险:{insuranceMoney},车辆管理费:{vehicleMoney},工装:{frockMoney},扣除杂项:仓库房租:{houseMoney}仓库电费:{powerMoney},实际付款:{money}", map);
            SmsUtil.sendPoint(receiverInfo.getMobilePhone(), content);
        }
 
    }
 
 
    /**
     * 提成列表
     *
     * @param model
     * @return
     */
    public Map<String, Object> queryRoyaltyManage(SettlementModel model) {
        Map<String, Object> map = new HashMap<>();
        List<String> partnerIds = cityPartnerService.queryPartnerByCurrent();
        model.setPartnerIds(partnerIds);
        model.setStartTime(DateUtils.changeTimeBigin(model.getStartTime()));
        model.setEndTime(DateUtils.changeTimeEnd(model.getEndTime()));
 
        PageHelper.startPage(model.getPage(), model.getLimit());
        List<SettlementModel> list = weightItemPriceMapper.queryRoyaltyManage(model);
        PageInfo<SettlementModel> pageInfo = new PageInfo<>(list);
 
 
        //格式化金额
        for (SettlementModel seModel : list) {
            QueryRuleManageDetailDTO dto = new QueryRuleManageDetailDTO();
            dto.setReceiver(seModel.getReceiver());
            dto.setEndTime(model.getEndTime());
            dto.setStartTime(model.getStartTime());
            List<WeightItemPrice> allList = weightItemPriceMapper.queryWeightItemList(dto);
            List<WeightItemPrice> royaltyList = allList.stream().filter(x -> x.getStatus().equals(OrderEnum.未结算.getValue())).collect(Collectors.toList());
            seModel.setRoyaltyList(royaltyList);
 
 
            //已结算
            BigDecimal settlementMoney = BigDecimal.ZERO;
            //未结算
            BigDecimal royaltyMoney = BigDecimal.ZERO;
            for (WeightItemPrice weightItemPrice : allList) {
                String status = weightItemPrice.getStatus();
                String settleMoney = weightItemPrice.getSettleMoney();
                if (OrderEnum.未结算.getValue().equals(status)) {
                    royaltyMoney = NumberUtil.add(royaltyMoney, Convert.toBigDecimal(settleMoney, BigDecimal.ZERO));
                } else {
                    settlementMoney = NumberUtil.add(settlementMoney, Convert.toBigDecimal(settleMoney, BigDecimal.ZERO));
                }
 
            }
 
            seModel.setSettlementMoney(DoubleUtil.roundTwo(settlementMoney.toString()));
            seModel.setRoyaltyMoney(DoubleUtil.roundTwo(royaltyMoney.toString()));
        }
 
        map.put("data", list);
        map.put("count", pageInfo.getTotal());
        map.put("code", 0);
        return map;
    }
 
 
    /**
     * 自动结算
     */
    @Scheduled(cron = "${ruleTime}")
    public void updateSettleMoneyForRule() {
        if (!SpringUtil.isCloud()) {
            log.debug("开始定时更新提成金额");
            List<WeightItemPriceModel> wpList = weightItemPriceMapper.queryWpList();
            for (WeightItemPriceModel modelWp : wpList) {
                String packageId = modelWp.getPackageId();
                RedPaperRule one = redPaperRuleService.findByPackageIdAndRuleType(UserEnum.提成规则.getValue(), packageId);
                if (one != null) {
                    BigDecimal wpA = new BigDecimal(modelWp.getWeight());
                    BigDecimal rate = new BigDecimal(modelWp.getPackagePrice()).subtract(new BigDecimal(modelWp.getGoodsPrice()));
                    String settleMoney = DoubleUtil.roundTwo(wpA.multiply(rate).toString());
                    //更新未结算的金额
                    WeightItemPrice weightItemPrice = new WeightItemPrice();
                    weightItemPrice.setId(Convert.toLong(modelWp.getId()));
                    weightItemPrice.setSettleMoney(settleMoney);
                    updateById(weightItemPrice);
                }
            }
            log.debug("开始定时更新提成金额完成");
        }
 
    }
 
 
    /**
     * 添加修改提成规则
     *
     * @param model
     * @return
     */
    public JsonResult addRoyaltyRule(XzxUserRebateRuleModel model) {
 
 
        //修改
        if (null != model.getId()) {
            rebateWeightPriceMapper.deleteByRuleId(model.getId() + "");
            RedPaperRule rule = new RedPaperRule();
            rule.setId(model.getId());
            rule.setDelFlag(Convert.toShort(Constants.DEL_FLAG));
            redPaperRuleService.update(rule);
        }else {
            //新增
            List<RedPaperRule> redPaperRules = redPaperRuleService.queryRoyalRuleList(model.getPartnerId() + "", model.getPackageId());
            if(CollUtil.isNotEmpty(redPaperRules)){
                throw new RestException("当前打包站已存在提成规则");
            }
 
        }
        Integer ruleId = addRule(model);
        return JsonResult.success(ruleId);
    }
 
    private Integer addRule(XzxUserRebateRuleModel model) {
        //添加
        RedPaperRule rule = new RedPaperRule();
        rule.setStartTime(model.getStartTime());
        rule.setEndTime(model.getEndTime());
        rule.setRuleName(model.getRuleName());
        rule.setCreateTime(cn.hutool.core.date.DateUtil.now());
        rule.setDelFlag((short) 0);
        rule.setRuleType(UserEnum.提成规则.getValue());
        rule.setStatus(model.getStatus());
        rule.setApplicableObject("1");
        rule.setProductType(model.getProductType());
        rule.setPackageId(model.getPackageId());
        rule.setPartnerId(model.getPartnerId());
        rule.setTiming(model.getTiming());
        redPaperRuleService.save(rule);
        List<RebateWeightPriceModel> royaltyRuleList = model.getRoyaltyRuleList();
        for (RebateWeightPriceModel model1 : royaltyRuleList) {
            model1.setRuleId(rule.getId() + "");
            model1.setPackageId(model.getPackageId());
            //设置分类价格
            setMoney(model, model1);
            rebateWeightPriceMapper.addRoyaltyRule(model1);
        }
        return rule.getId();
    }
 
    private void setMoney(XzxUserRebateRuleModel model, RebateWeightPriceModel model1) {
        //设置分类价格
        PackageGoodsInfo byPackageIdAndItemType = packageGoodsInfoService.findByPackageIdAndItemType(model.getPackageId(), model1.getProductType());
        if (byPackageIdAndItemType == null) {
            throw new RestException("打包站分类" + BusinessSimpleUtil.getItemTypeName(model1.getProductType()) + "不存在");
        } else {
            model1.setMoney(businessUtil.changeMoney(byPackageIdAndItemType.getPutStoragePrice()));
        }
    }
 
 
    public List<OrderSettle> settlePage(SettlePageDTO settlePageDTO) {
        List<OrderSettle> byUserId = orderSettleService.findByUserId(settlePageDTO.getReceiver());
        for (OrderSettle orderSettle : byUserId) {
            OrderSettleDeduct bySettleId = orderSettleDeductService.findBySettleId(orderSettle.getId());
            orderSettle.setOrderSettleDeduct(bySettleId);
        }
 
        return byUserId;
    }
}