rk
昨天 3aef471b170a703b501ddb4d9d2a12791d07ff28
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
package com.doumee.service.business.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doumee.core.constants.Constants;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.model.PageData;
import com.doumee.core.model.PageWrap;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.CategoryMapper;
import com.doumee.dao.business.PricingRuleMapper;
import com.doumee.dao.business.model.Category;
import com.doumee.dao.business.model.PricingRule;
import com.doumee.dao.dto.LocalStoragePricingItemDTO;
import com.doumee.dao.dto.LocalStoragePricingSaveDTO;
import com.doumee.dao.dto.RemoteDeliveryPricingItemDTO;
import com.doumee.dao.dto.RemoteDeliveryPricingSaveDTO;
import com.doumee.dao.dto.EstimatedDeliverySaveDTO;
import com.doumee.dao.dto.StoreDepositItemDTO;
import com.doumee.dao.dto.StoreDepositSaveDTO;
import com.doumee.dao.dto.RevenueShareItemDTO;
import com.doumee.dao.dto.RevenueShareSaveDTO;
import com.doumee.dao.vo.LocalStoragePricingVO;
import com.doumee.dao.vo.RemoteDeliveryPricingVO;
import com.doumee.dao.vo.EstimatedDeliveryVO;
import com.doumee.dao.vo.StoreDepositVO;
import com.doumee.dao.vo.RevenueShareVO;
import com.doumee.service.business.PricingRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 计价规则配置Service实现
 * @author rk
 * @date 2026/04/08
 */
@Service
public class PricingRuleServiceImpl implements PricingRuleService {
 
    @Autowired
    private PricingRuleMapper pricingRuleMapper;
 
    @Autowired
    private CategoryMapper categoryMapper;
 
    @Override
    public Integer create(PricingRule pricingRule) {
        pricingRuleMapper.insert(pricingRule);
        return pricingRule.getId();
    }
 
    @Override
    public void deleteById(Integer id) {
        pricingRuleMapper.deleteById(id);
    }
 
    @Override
    public void delete(PricingRule pricingRule) {
        UpdateWrapper<PricingRule> deleteWrapper = new UpdateWrapper<>(pricingRule);
        pricingRuleMapper.delete(deleteWrapper);
    }
 
    @Override
    public void deleteByIdInBatch(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        pricingRuleMapper.deleteBatchIds(ids);
    }
 
    @Override
    public void updateById(PricingRule pricingRule) {
        pricingRuleMapper.updateById(pricingRule);
    }
 
    @Override
    public void updateByIdInBatch(List<PricingRule> pricingRules) {
        if (CollectionUtils.isEmpty(pricingRules)) {
            return;
        }
        for (PricingRule pricingRule : pricingRules) {
            this.updateById(pricingRule);
        }
    }
 
    @Override
    public PricingRule findById(Integer id) {
        PricingRule pricingRule = pricingRuleMapper.selectById(id);
        if (Objects.isNull(pricingRule)) {
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        return pricingRule;
    }
 
    @Override
    public PricingRule findOne(PricingRule pricingRule) {
        QueryWrapper<PricingRule> wrapper = new QueryWrapper<>(pricingRule);
        return pricingRuleMapper.selectOne(wrapper);
    }
 
    @Override
    public List<PricingRule> findList(PricingRule pricingRule) {
        QueryWrapper<PricingRule> wrapper = new QueryWrapper<>(pricingRule);
        return pricingRuleMapper.selectList(wrapper);
    }
 
    @Override
    public PageData<PricingRule> findPage(PageWrap<PricingRule> pageWrap) {
        IPage<PricingRule> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<PricingRule> queryWrapper = new QueryWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        pageWrap.getModel().setDeleted(Constants.ZERO);
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.lambda().eq(PricingRule::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getDeleted() != null) {
            queryWrapper.lambda().eq(PricingRule::getDeleted, pageWrap.getModel().getDeleted());
        }
        if (pageWrap.getModel().getCreateUser() != null) {
            queryWrapper.lambda().eq(PricingRule::getCreateUser, pageWrap.getModel().getCreateUser());
        }
        if (pageWrap.getModel().getCreateTime() != null) {
            queryWrapper.lambda().ge(PricingRule::getCreateTime, Utils.Date.getStart(pageWrap.getModel().getCreateTime()));
            queryWrapper.lambda().le(PricingRule::getCreateTime, Utils.Date.getEnd(pageWrap.getModel().getCreateTime()));
        }
        if (pageWrap.getModel().getUpdateUser() != null) {
            queryWrapper.lambda().eq(PricingRule::getUpdateUser, pageWrap.getModel().getUpdateUser());
        }
        if (pageWrap.getModel().getUpdateTime() != null) {
            queryWrapper.lambda().ge(PricingRule::getUpdateTime, Utils.Date.getStart(pageWrap.getModel().getUpdateTime()));
            queryWrapper.lambda().le(PricingRule::getUpdateTime, Utils.Date.getEnd(pageWrap.getModel().getUpdateTime()));
        }
        if (pageWrap.getModel().getRemark() != null) {
            queryWrapper.lambda().eq(PricingRule::getRemark, pageWrap.getModel().getRemark());
        }
        if (pageWrap.getModel().getCityId() != null) {
            queryWrapper.lambda().eq(PricingRule::getCityId, pageWrap.getModel().getCityId());
        }
        if (pageWrap.getModel().getType() != null) {
            queryWrapper.lambda().eq(PricingRule::getType, pageWrap.getModel().getType());
        }
        if (pageWrap.getModel().getFieldA() != null) {
            queryWrapper.lambda().eq(PricingRule::getFieldA, pageWrap.getModel().getFieldA());
        }
        if (pageWrap.getModel().getFieldB() != null) {
            queryWrapper.lambda().eq(PricingRule::getFieldB, pageWrap.getModel().getFieldB());
        }
        if (pageWrap.getModel().getFieldC() != null) {
            queryWrapper.lambda().eq(PricingRule::getFieldC, pageWrap.getModel().getFieldC());
        }
        if (pageWrap.getModel().getFieldD() != null) {
            queryWrapper.lambda().eq(PricingRule::getFieldD, pageWrap.getModel().getFieldD());
        }
        if (pageWrap.getModel().getFieldE() != null) {
            queryWrapper.lambda().eq(PricingRule::getFieldE, pageWrap.getModel().getFieldE());
        }
        for (PageWrap.SortData sortData : pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                queryWrapper.orderByDesc(sortData.getProperty());
            } else {
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return PageData.from(pricingRuleMapper.selectPage(page, queryWrapper));
    }
 
    @Override
    public long count(PricingRule pricingRule) {
        QueryWrapper<PricingRule> wrapper = new QueryWrapper<>(pricingRule);
        return pricingRuleMapper.selectCount(wrapper);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveLocalStoragePricing(LocalStoragePricingSaveDTO request) {
        // 校验分类数据完整性
        Set<Integer> requestCategoryIds = request.getItems().stream()
                .map(LocalStoragePricingItemDTO::getCategoryId)
                .collect(Collectors.toSet());
        validateCategoryType4(requestCategoryIds);
 
        // 逐项 upsert
        Date now = new Date();
        for (LocalStoragePricingItemDTO item : request.getItems()) {
            // 查询已有规则
            QueryWrapper<PricingRule> qw = new QueryWrapper<>();
            qw.lambda()
                    .eq(PricingRule::getType, Constants.ZERO)
                    .eq(PricingRule::getFieldA, String.valueOf(item.getCategoryId()))
                    .eq(PricingRule::getCityId, request.getCityId())
                    .eq(PricingRule::getDeleted, Constants.ZERO)
                    .last("limit 1");
            PricingRule existing = pricingRuleMapper.selectOne(qw);
 
            if (existing != null) {
                // 更新
                existing.setFieldB(item.getUnitPrice());
                existing.setUpdateTime(now);
                pricingRuleMapper.updateById(existing);
            } else {
                // 新建
                PricingRule rule = new PricingRule();
                rule.setType(Constants.ZERO);
                rule.setFieldA(String.valueOf(item.getCategoryId()));
                rule.setFieldB(item.getUnitPrice());
                rule.setCityId(request.getCityId());
                rule.setDeleted(Constants.ZERO);
                rule.setCreateTime(now);
                rule.setUpdateTime(now);
                pricingRuleMapper.insert(rule);
            }
        }
    }
 
    @Override
    public List<LocalStoragePricingVO> listLocalStoragePricing(Integer cityId) {
        // 1. 查询所有 Category type=4, deleted=0
        Category categoryQuery = new Category();
        categoryQuery.setType(Constants.FOUR);
        categoryQuery.setDeleted(Constants.ZERO);
        List<Category> allCategories = categoryMapper.selectList(new QueryWrapper<>(categoryQuery));
        Map<Integer, String> categoryNameMap = allCategories.stream()
                .collect(Collectors.toMap(Category::getId, Category::getName));
 
        // 2. 查询已有规则
        QueryWrapper<PricingRule> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(PricingRule::getType, Constants.ZERO)
                .eq(PricingRule::getCityId, cityId)
                .eq(PricingRule::getDeleted, Constants.ZERO);
        List<PricingRule> rules = pricingRuleMapper.selectList(qw);
        Map<String, PricingRule> existingMap = rules.stream()
                .collect(Collectors.toMap(PricingRule::getFieldA, r -> r));
 
        // 3. 基于所有分类组装 VO,无规则则返回空记录
        return allCategories.stream().map(category -> {
            LocalStoragePricingVO vo = new LocalStoragePricingVO();
            vo.setCategoryId(category.getId());
            vo.setCategoryName(category.getName());
            vo.setCityId(cityId);
 
            PricingRule rule = existingMap.get(String.valueOf(category.getId()));
            if (rule != null) {
                vo.setPricingRuleId(rule.getId());
                vo.setUnitPrice(rule.getFieldB());
            }
            return vo;
        }).collect(Collectors.toList());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveRemoteDeliveryPricing(RemoteDeliveryPricingSaveDTO request) {
        // 校验分类数据完整性
        Set<Integer> requestCategoryIds = request.getItems().stream()
                .map(RemoteDeliveryPricingItemDTO::getCategoryId)
                .collect(Collectors.toSet());
        Map<Integer, String> categoryMap = validateCategoryType4(requestCategoryIds);
 
        // 逐项 upsert
        Date now = new Date();
        for (RemoteDeliveryPricingItemDTO item : request.getItems()) {
            QueryWrapper<PricingRule> qw = new QueryWrapper<>();
            qw.lambda()
                    .eq(PricingRule::getType, Constants.ONE)
                    .eq(PricingRule::getFieldA, String.valueOf(item.getCategoryId()))
                    .eq(PricingRule::getCityId, request.getCityId())
                    .eq(PricingRule::getDeleted, Constants.ZERO)
                    .last("limit 1");
            PricingRule existing = pricingRuleMapper.selectOne(qw);
 
            if (existing != null) {
                existing.setFieldB(item.getStartDistance());
                existing.setFieldC(item.getStartPrice());
                existing.setFieldD(item.getExtraDistance());
                existing.setFieldE(item.getExtraPrice());
                existing.setUpdateTime(now);
                pricingRuleMapper.updateById(existing);
            } else {
                PricingRule rule = new PricingRule();
                rule.setType(Constants.ONE);
                rule.setFieldA(String.valueOf(item.getCategoryId()));
                rule.setFieldB(item.getStartDistance());
                rule.setFieldC(item.getStartPrice());
                rule.setFieldD(item.getExtraDistance());
                rule.setFieldE(item.getExtraPrice());
                rule.setCityId(request.getCityId());
                rule.setDeleted(Constants.ZERO);
                rule.setCreateTime(now);
                rule.setUpdateTime(now);
                pricingRuleMapper.insert(rule);
            }
        }
    }
 
    @Override
    public List<RemoteDeliveryPricingVO> listRemoteDeliveryPricing(Integer cityId) {
        // 1. 查询所有 Category type=4, deleted=0
        Category categoryQuery = new Category();
        categoryQuery.setType(Constants.FOUR);
        categoryQuery.setDeleted(Constants.ZERO);
        List<Category> allCategories = categoryMapper.selectList(new QueryWrapper<>(categoryQuery));
        Map<Integer, String> categoryNameMap = allCategories.stream()
                .collect(Collectors.toMap(Category::getId, Category::getName));
 
        // 2. 查询已有规则
        QueryWrapper<PricingRule> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(PricingRule::getType, Constants.ONE)
                .eq(PricingRule::getCityId, cityId)
                .eq(PricingRule::getDeleted, Constants.ZERO);
        List<PricingRule> rules = pricingRuleMapper.selectList(qw);
        Map<String, PricingRule> existingMap = rules.stream()
                .collect(Collectors.toMap(PricingRule::getFieldA, r -> r));
 
        // 3. 基于所有分类组装 VO,无规则则返回空记录
        return allCategories.stream().map(category -> {
            RemoteDeliveryPricingVO vo = new RemoteDeliveryPricingVO();
            vo.setCategoryId(category.getId());
            vo.setCategoryName(category.getName());
            vo.setCityId(cityId);
 
            PricingRule rule = existingMap.get(String.valueOf(category.getId()));
            if (rule != null) {
                vo.setPricingRuleId(rule.getId());
                vo.setStartDistance(rule.getFieldB());
                vo.setStartPrice(rule.getFieldC());
                vo.setExtraDistance(rule.getFieldD());
                vo.setExtraPrice(rule.getFieldE());
            }
            return vo;
        }).collect(Collectors.toList());
    }
 
    /**
     * 校验请求中的 categoryId 与分类表 type=4 数据完全匹配
     * @param requestCategoryIds 请求中的 categoryId 集合
     * @return 分类表 id->name 映射
     */
    private Map<Integer, String> validateCategoryType4(Set<Integer> requestCategoryIds) {
        Category categoryQuery = new Category();
        categoryQuery.setType(Constants.FOUR);
        categoryQuery.setDeleted(Constants.ZERO);
        List<Category> allType4Categories = categoryMapper.selectList(new QueryWrapper<>(categoryQuery));
 
        Map<Integer, String> categoryMap = allType4Categories.stream()
                .collect(Collectors.toMap(Category::getId, Category::getName));
        Set<Integer> allCategoryIds = categoryMap.keySet();
 
        // 校验:请求中存在但分类表中不存在的 categoryId
        List<String> invalidIds = requestCategoryIds.stream()
                .filter(id -> !allCategoryIds.contains(id))
                .map(String::valueOf)
                .collect(Collectors.toList());
        if (!invalidIds.isEmpty()) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),
                    "以下物品规格不存在: " + String.join(", ", invalidIds));
        }
 
        // 校验:分类表中存在但请求中缺失的 categoryId
        List<String> missingNames = allCategoryIds.stream()
                .filter(id -> !requestCategoryIds.contains(id))
                .map(id -> categoryMap.get(id) + "(" + id + ")")
                .collect(Collectors.toList());
        if (!missingNames.isEmpty()) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),
                    "缺少以下物品规格的定价配置: " + String.join(", ", missingNames));
        }
 
        return categoryMap;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEstimatedDelivery(EstimatedDeliverySaveDTO request) {
        if (request.getItems() == null || request.getItems().isEmpty()) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "时效配置列表不能为空");
        }
        Date now = new Date();
        for (EstimatedDeliverySaveDTO.EstimatedDeliveryItem item : request.getItems()) {
            // 查询已有规则 type=2, fieldA, cityId, deleted=0
            QueryWrapper<PricingRule> qw = new QueryWrapper<>();
            qw.lambda()
                    .eq(PricingRule::getType, Constants.TWO)
                    .eq(PricingRule::getFieldA, String.valueOf(item.getFieldA()))
                    .eq(PricingRule::getCityId, request.getCityId())
                    .eq(PricingRule::getDeleted, Constants.ZERO)
                    .last("limit 1");
            PricingRule existing = pricingRuleMapper.selectOne(qw);
 
            if (existing != null) {
                existing.setFieldB(item.getStartDistance());
                existing.setFieldC(item.getStartTime());
                existing.setFieldD(item.getContinueDistance());
                existing.setFieldE(item.getContinueTime());
                existing.setUpdateTime(now);
                pricingRuleMapper.updateById(existing);
            } else {
                PricingRule rule = new PricingRule();
                rule.setType(Constants.TWO);
                rule.setFieldA(String.valueOf(item.getFieldA()));
                rule.setFieldB(item.getStartDistance());
                rule.setFieldC(item.getStartTime());
                rule.setFieldD(item.getContinueDistance());
                rule.setFieldE(item.getContinueTime());
                rule.setCityId(request.getCityId());
                rule.setDeleted(Constants.ZERO);
                rule.setCreateTime(now);
                rule.setUpdateTime(now);
                pricingRuleMapper.insert(rule);
            }
        }
    }
 
    @Override
    public List<EstimatedDeliveryVO> getEstimatedDelivery(Integer cityId) {
        QueryWrapper<PricingRule> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(PricingRule::getType, Constants.TWO)
                .in(PricingRule::getFieldA, "1", "2")
                .eq(PricingRule::getCityId, cityId)
                .eq(PricingRule::getDeleted, Constants.ZERO)
                .orderByAsc(PricingRule::getFieldA);
        List<PricingRule> rules = pricingRuleMapper.selectList(qw);
 
        // 将已有规则按fieldA分组
        Map<String, PricingRule> ruleMap = new HashMap<>();
        for (PricingRule rule : rules) {
            ruleMap.put(rule.getFieldA(), rule);
        }
 
        // 固定返回2条:fieldA=1(标速达), fieldA=2(极速达),无数据时返回空对象
        List<EstimatedDeliveryVO> voList = new ArrayList<>();
        for (int fieldA = 1; fieldA <= 2; fieldA++) {
            EstimatedDeliveryVO vo = new EstimatedDeliveryVO();
            vo.setCityId(cityId);
            vo.setFieldA(fieldA);
            PricingRule rule = ruleMap.get(String.valueOf(fieldA));
            if (rule != null) {
                vo.setPricingRuleId(rule.getId());
                vo.setStartDistance(rule.getFieldB());
                vo.setStartTime(rule.getFieldC());
                vo.setContinueDistance(rule.getFieldD());
                vo.setContinueTime(rule.getFieldE());
            }
            voList.add(vo);
        }
        return voList;
    }
 
    @Override
    public BigDecimal calculateEstimatedTime(Integer cityId, Integer fieldA, BigDecimal distance) {
        if (cityId == null || fieldA == null || distance == null) {
            return null;
        }
        QueryWrapper<PricingRule> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(PricingRule::getType, Constants.TWO)
                .eq(PricingRule::getFieldA, String.valueOf(fieldA))
                .eq(PricingRule::getCityId, cityId)
                .eq(PricingRule::getDeleted, Constants.ZERO)
                .last("limit 1");
        PricingRule rule = pricingRuleMapper.selectOne(qw);
        if (rule == null) {
            return null;
        }
        // fieldB=起送里程, fieldC=起送时长, fieldD=续送里程, fieldE=续送时长
        BigDecimal startDistance = new BigDecimal(rule.getFieldB());
        BigDecimal startTime = new BigDecimal(rule.getFieldC());
        BigDecimal continueDistance = new BigDecimal(rule.getFieldD());
        BigDecimal continueTime = new BigDecimal(rule.getFieldE());
 
        // 距离 <= 起送里程 → 直接返回起送时长
        if (distance.compareTo(startDistance) <= 0) {
            return startTime;
        }
        // 超出部分:向上取整 * 续送时长 + 起送时长
        BigDecimal extraDistance = distance.subtract(startDistance);
        BigDecimal extraCount = extraDistance.divide(continueDistance, 0, RoundingMode.CEILING);
        return startTime.add(extraCount.multiply(continueTime));
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveStoreDeposit(StoreDepositSaveDTO request) {
        // 校验:必须包含 fieldType=0(企业) 和 fieldType=1(个人) 各一条
        Set<Integer> fieldTypes = request.getItems().stream()
                .map(StoreDepositItemDTO::getFieldType)
                .collect(Collectors.toSet());
        if (!fieldTypes.contains(Constants.ZERO) || !fieldTypes.contains(Constants.ONE)) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),
                    "必须包含企业(0)和个人(1)两条数据");
        }
        if (request.getItems().size() != 2) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),
                    "有且仅有2条数据");
        }
 
        Date now = new Date();
        for (StoreDepositItemDTO item : request.getItems()) {
            QueryWrapper<PricingRule> qw = new QueryWrapper<>();
            qw.lambda()
                    .eq(PricingRule::getType, Constants.THREE)
                    .eq(PricingRule::getFieldA, String.valueOf(item.getFieldType()))
                    .eq(PricingRule::getCityId, request.getCityId())
                    .eq(PricingRule::getDeleted, Constants.ZERO)
                    .last("limit 1");
            PricingRule existing = pricingRuleMapper.selectOne(qw);
 
            if (existing != null) {
                existing.setFieldB(item.getDepositAmount());
                existing.setUpdateTime(now);
                pricingRuleMapper.updateById(existing);
            } else {
                PricingRule rule = new PricingRule();
                rule.setType(Constants.THREE);
                rule.setFieldA(String.valueOf(item.getFieldType()));
                rule.setFieldB(item.getDepositAmount());
                rule.setCityId(request.getCityId());
                rule.setDeleted(Constants.ZERO);
                rule.setCreateTime(now);
                rule.setUpdateTime(now);
                pricingRuleMapper.insert(rule);
            }
        }
    }
 
    @Override
    public List<StoreDepositVO> listStoreDeposit(Integer cityId) {
        // 查询已有规则
        QueryWrapper<PricingRule> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(PricingRule::getType, Constants.THREE)
                .eq(PricingRule::getCityId, cityId)
                .eq(PricingRule::getDeleted, Constants.ZERO);
        List<PricingRule> rules = pricingRuleMapper.selectList(qw);
 
        // 构建已存在数据的映射 fieldA -> rule
        Map<String, PricingRule> existingMap = rules.stream()
                .collect(Collectors.toMap(PricingRule::getFieldA, r -> r));
 
        // 固定返回2条:企业(0)、个人(1)
        List<StoreDepositVO> result = new ArrayList<>();
        String[] typeNames = {"企业", "个人"};
        for (int i = 0; i <= 1; i++) {
            StoreDepositVO vo = new StoreDepositVO();
            vo.setFieldType(i);
            vo.setFieldTypeName(typeNames[i]);
            vo.setCityId(cityId);
 
            PricingRule rule = existingMap.get(String.valueOf(i));
            if (rule != null) {
                vo.setPricingRuleId(rule.getId());
                vo.setDepositAmount(rule.getFieldB());
            }
            result.add(vo);
        }
        return result;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveRevenueShare(RevenueShareSaveDTO request) {
        // 校验:必须包含 fieldType 0-4 各一条
        Set<Integer> fieldTypes = request.getItems().stream()
                .map(RevenueShareItemDTO::getFieldType)
                .collect(Collectors.toSet());
        if (fieldTypes.size() != Constants.FIVE) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),
                    "必须包含企业寄(0)、个人寄(1)、企业取(2)、个人取(3)、配送员(4)共5条数据");
        }
        for (int i = 0; i <= Constants.FOUR; i++) {
            if (!fieldTypes.contains(i)) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),
                        "缺少类型" + i + "的数据");
            }
        }
 
        Date now = new Date();
        for (RevenueShareItemDTO item : request.getItems()) {
            QueryWrapper<PricingRule> qw = new QueryWrapper<>();
            qw.lambda()
                    .eq(PricingRule::getType, Constants.FOUR)
                    .eq(PricingRule::getFieldA, String.valueOf(item.getFieldType()))
                    .eq(PricingRule::getCityId, request.getCityId())
                    .eq(PricingRule::getDeleted, Constants.ZERO)
                    .last("limit 1");
            PricingRule existing = pricingRuleMapper.selectOne(qw);
 
            if (existing != null) {
                existing.setFieldB(item.getRatio());
                existing.setUpdateTime(now);
                pricingRuleMapper.updateById(existing);
            } else {
                PricingRule rule = new PricingRule();
                rule.setType(Constants.FOUR);
                rule.setFieldA(String.valueOf(item.getFieldType()));
                rule.setFieldB(item.getRatio());
                rule.setCityId(request.getCityId());
                rule.setDeleted(Constants.ZERO);
                rule.setCreateTime(now);
                rule.setUpdateTime(now);
                pricingRuleMapper.insert(rule);
            }
        }
    }
 
    @Override
    public List<RevenueShareVO> listRevenueShare(Integer cityId) {
        // 查询已有规则
        QueryWrapper<PricingRule> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(PricingRule::getType, Constants.FOUR)
                .eq(PricingRule::getCityId, cityId)
                .eq(PricingRule::getDeleted, Constants.ZERO);
        List<PricingRule> rules = pricingRuleMapper.selectList(qw);
 
        // 构建已存在数据的映射 fieldA -> rule
        Map<String, PricingRule> existingMap = rules.stream()
                .collect(Collectors.toMap(PricingRule::getFieldA, r -> r));
 
        // 固定返回5条:企业寄(0)、个人寄(1)、企业取(2)、个人取(3)、配送员(4)
        List<RevenueShareVO> result = new ArrayList<>();
        String[] typeNames = {"企业寄", "个人寄", "企业取", "个人取", "配送员"};
        for (int i = 0; i <= Constants.FOUR; i++) {
            RevenueShareVO vo = new RevenueShareVO();
            vo.setFieldType(i);
            vo.setFieldTypeName(typeNames[i]);
            vo.setCityId(cityId);
 
            PricingRule rule = existingMap.get(String.valueOf(i));
            if (rule != null) {
                vo.setPricingRuleId(rule.getId());
                vo.setRatio(rule.getFieldB());
            }
            result.add(vo);
        }
        return result;
    }
 
}