“mitao”
2026-04-26 6d0b7fdb91450b9939a0ead1b421910e0c8fee70
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
package com.ruoyi.other.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.other.api.domain.TExchangeCodeDetail;
import com.ruoyi.other.api.domain.TExchangeCodePackage;
import com.ruoyi.other.api.domain.TExchangeCodePackageSpec;
import com.ruoyi.other.api.domain.TExchangeCodeUseRecord;
import com.ruoyi.other.api.dto.ExchangeCodeBindDTO;
import com.ruoyi.other.api.dto.ExchangeCodeConsumeDTO;
import com.ruoyi.other.api.dto.ExchangeCodePackageSaveDTO;
import com.ruoyi.other.api.dto.ExchangeCodePackageSpecDTO;
import com.ruoyi.other.api.vo.ExchangeCodeBindResultVO;
import com.ruoyi.other.api.vo.ExchangeCodeConsumeResultVO;
import com.ruoyi.other.api.vo.ExchangeCodePackageDetailVO;
import com.ruoyi.other.api.vo.ExchangeCodePackageSpecVO;
import com.ruoyi.other.mapper.TExchangeCodeDetailMapper;
import com.ruoyi.other.mapper.TExchangeCodePackageMapper;
import com.ruoyi.other.mapper.TExchangeCodePackageSpecMapper;
import com.ruoyi.other.mapper.TExchangeCodeUseRecordMapper;
import com.ruoyi.other.query.ExchangeCodeBatchInvalidDTO;
import com.ruoyi.other.query.ExchangeCodeDetailQuery;
import com.ruoyi.other.query.ExchangeCodePackageQuery;
import com.ruoyi.other.service.TExchangeCodePackageService;
import com.ruoyi.other.vo.ExchangeCodeBatchInvalidResultVO;
import com.ruoyi.other.vo.ExchangeCodeDetailVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
 
@Service
public class TExchangeCodePackageServiceImpl extends ServiceImpl<TExchangeCodePackageMapper, TExchangeCodePackage>
        implements TExchangeCodePackageService {
 
    private static final Integer STATUS_ENABLE = 1;
    private static final Integer STATUS_DISABLE = 2;
    private static final Integer CODE_STATUS_UNBOUND = 1;
    private static final Integer CODE_STATUS_BOUND = 2;
    private static final Integer CODE_STATUS_INVALID = 3;
    private static final DateTimeFormatter BATCH_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
 
    @Resource
    private TExchangeCodePackageSpecMapper packageSpecMapper;
 
    @Resource
    private TExchangeCodeDetailMapper codeDetailMapper;
 
    @Resource
    private TExchangeCodeUseRecordMapper useRecordMapper;
 
    @Override
    public PageInfo<TExchangeCodePackage> pageList(ExchangeCodePackageQuery query) {
        PageInfo<TExchangeCodePackage> pageInfo = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        List<TExchangeCodePackage> records = this.baseMapper.pageList(pageInfo, query);
        pageInfo.setRecords(records);
        return pageInfo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePackage(ExchangeCodePackageSaveDTO dto) {
        validateSaveDTO(dto, false);
        TExchangeCodePackage entity = buildPackageEntity(dto, new TExchangeCodePackage());
        this.save(entity);
        saveSpecsAndCodes(entity.getId(), dto.getSpecList(), dto.getInventory(), null);
        refreshPackageStats(entity.getId());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePackage(ExchangeCodePackageSaveDTO dto) {
        if (dto.getId() == null) {
            throw new ServiceException("卡包ID不能为空");
        }
        validateSaveDTO(dto, true);
        TExchangeCodePackage old = this.getById(dto.getId());
        if (old == null) {
            throw new ServiceException("卡包不存在");
        }
        if (dto.getInventory() < old.getInventory()) {
            throw new ServiceException("编辑时库存只能增加");
        }
        TExchangeCodePackage entity = buildPackageEntity(dto, old);
        this.updateById(entity);
        packageSpecMapper.delete(new QueryWrapper<TExchangeCodePackageSpec>().eq("package_id", dto.getId()));
        saveSpecsAndCodes(dto.getId(), dto.getSpecList(), dto.getInventory(), old.getInventory());
        refreshPackageStats(dto.getId());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePackage(String ids) {
        if (!StringUtils.hasText(ids)) {
            throw new ServiceException("卡包ID不能为空");
        }
        List<Long> idList = Arrays.stream(ids.split(","))
                .filter(StringUtils::hasText)
                .map(Long::valueOf)
                .collect(Collectors.toList());
        if (idList.isEmpty()) {
            throw new ServiceException("卡包ID不能为空");
        }
        Long boundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                .in("package_id", idList)
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0));
        if (boundCount != null && boundCount > 0) {
            throw new ServiceException("存在已绑定兑换码,不允许删除");
        }
        this.removeByIds(idList);
        packageSpecMapper.delete(new QueryWrapper<TExchangeCodePackageSpec>().in("package_id", idList));
        codeDetailMapper.delete(new QueryWrapper<TExchangeCodeDetail>().in("package_id", idList));
    }
 
    @Override
    public ExchangeCodePackageDetailVO getDetail(Long id) {
        TExchangeCodePackage entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("卡包不存在");
        }
        refreshPackageStats(id);
        entity = this.getById(id);
        ExchangeCodePackageDetailVO detailVO = new ExchangeCodePackageDetailVO();
        BeanUtils.copyProperties(entity, detailVO);
        List<TExchangeCodePackageSpec> specs = packageSpecMapper.selectList(new QueryWrapper<TExchangeCodePackageSpec>()
                .eq("package_id", id)
                .orderByAsc("sort", "id"));
        List<ExchangeCodePackageSpecVO> specVOList = new ArrayList<>();
        for (TExchangeCodePackageSpec spec : specs) {
            ExchangeCodePackageSpecVO vo = new ExchangeCodePackageSpecVO();
            BeanUtils.copyProperties(spec, vo);
            Long boundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                    .eq("package_spec_id", spec.getId())
                    .eq("status", CODE_STATUS_BOUND)
                    .eq("del_flag", 0));
            Long unboundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                    .eq("package_spec_id", spec.getId())
                    .eq("status", CODE_STATUS_UNBOUND)
                    .eq("del_flag", 0));
            vo.setBoundCount(boundCount == null ? 0 : boundCount.intValue());
            vo.setUnboundCount(unboundCount == null ? 0 : unboundCount.intValue());
            specVOList.add(vo);
        }
        detailVO.setSpecList(specVOList);
        return detailVO;
    }
 
    @Override
    public PageInfo<ExchangeCodeDetailVO> codePage(ExchangeCodeDetailQuery query) {
        PageInfo<ExchangeCodeDetailVO> pageInfo = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        List<ExchangeCodeDetailVO> records = codeDetailMapper.pageList(pageInfo, query);
        pageInfo.setRecords(records);
        return pageInfo;
    }
 
    @Override
    public List<ExchangeCodeDetailVO> exportCodes(ExchangeCodeDetailQuery query) {
        return codeDetailMapper.exportList(query);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeCodeBatchInvalidResultVO batchInvalidate(ExchangeCodeBatchInvalidDTO dto) {
        if (dto.getPackageId() == null || dto.getDetailIds() == null || dto.getDetailIds().isEmpty()) {
            throw new ServiceException("请选择需要失效的兑换码");
        }
        int success = 0;
        int skip = 0;
        List<TExchangeCodeDetail> details = codeDetailMapper.selectBatchIds(dto.getDetailIds());
        for (TExchangeCodeDetail detail : details) {
            if (!Objects.equals(detail.getPackageId(), dto.getPackageId())) {
                continue;
            }
            if (Objects.equals(detail.getStatus(), CODE_STATUS_UNBOUND)) {
                detail.setStatus(CODE_STATUS_INVALID);
                detail.setInvalidTime(LocalDateTime.now());
                detail.setInvalidReason("后台批量失效");
                codeDetailMapper.updateById(detail);
                success++;
            } else {
                skip++;
            }
        }
        refreshPackageStats(dto.getPackageId());
        return new ExchangeCodeBatchInvalidResultVO(success, skip);
    }
 
    @Override
    public List<ExchangeCodeDetailVO> listDownloadableCodes(Long packageId, boolean onlyUnbound) {
        ExchangeCodeDetailQuery query = new ExchangeCodeDetailQuery();
        query.setPackageId(packageId);
        if (onlyUnbound) {
            query.setStatus(CODE_STATUS_UNBOUND);
        }
        return exportCodes(query);
    }
 
    @Override
    public ExchangeCodeDetailVO getCodeDetail(Long id) {
        TExchangeCodeDetail detail = codeDetailMapper.selectById(id);
        if (detail == null || Boolean.TRUE.equals(detail.getDelFlag())) {
            throw new ServiceException("兑换码不存在");
        }
        ExchangeCodeDetailVO vo = new ExchangeCodeDetailVO();
        BeanUtils.copyProperties(detail, vo);
        if (detail.getPackageSpecId() != null) {
            TExchangeCodePackageSpec spec = packageSpecMapper.selectById(detail.getPackageSpecId());
            if (spec != null) {
                vo.setAmount(spec.getAmount());
                vo.setQuantity(spec.getQuantity());
            }
        }
        return vo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeCodeBindResultVO bindExchangeCode(ExchangeCodeBindDTO dto, Long userId, String phone) {
        if (!StringUtils.hasText(dto.getCode()) || !StringUtils.hasText(dto.getPassword())) {
            throw new ServiceException("兑换码或密码不能为空");
        }
        TExchangeCodeDetail detail = codeDetailMapper.selectOne(new QueryWrapper<TExchangeCodeDetail>()
                .eq("code", dto.getCode())
                .eq("password", dto.getPassword())
                .last("limit 1"));
        if (detail == null) {
            throw new ServiceException("兑换码或密码错误");
        }
        TExchangeCodePackage exchangePackage = this.getById(detail.getPackageId());
        if (exchangePackage == null || !Objects.equals(exchangePackage.getStatus(), STATUS_ENABLE)) {
            throw new ServiceException("卡包已下架");
        }
        if (exchangePackage.getExpireTime() != null && exchangePackage.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException("已失效");
        }
        if (Objects.equals(detail.getStatus(), CODE_STATUS_INVALID)) {
            throw new ServiceException("卡号失效");
        }
        if (Objects.equals(detail.getStatus(), CODE_STATUS_BOUND)) {
            throw new ServiceException("兑换码已绑定");
        }
        String bindPhone = StringUtils.hasText(dto.getPhone()) ? dto.getPhone() : phone;
        if (!StringUtils.hasText(bindPhone)) {
            throw new ServiceException("绑定手机号不能为空");
        }
        if (Objects.equals(exchangePackage.getUnlimitedReceiveLimit(), 0) && exchangePackage.getReceiveLimit() != null) {
            Long bindCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                    .eq("package_id", exchangePackage.getId())
                    .eq("bind_phone", bindPhone)
                    .eq("status", CODE_STATUS_BOUND)
                    .eq("del_flag", 0));
            if (bindCount >= exchangePackage.getReceiveLimit()) {
                throw new ServiceException("该手机号领取次数已达上限");
            }
        }
        detail.setStatus(CODE_STATUS_BOUND);
        detail.setBindUserId(userId);
        detail.setBindPhone(bindPhone);
        detail.setBindTime(LocalDateTime.now());
        codeDetailMapper.updateById(detail);
        refreshPackageStats(exchangePackage.getId());
        ExchangeCodeBindResultVO resultVO = new ExchangeCodeBindResultVO();
        resultVO.setDetailId(detail.getId());
        resultVO.setPackageId(exchangePackage.getId());
        resultVO.setPackageName(exchangePackage.getPackageName());
        resultVO.setBindPhone(bindPhone);
        return resultVO;
    }
 
    @Override
    public Map<Long, BigDecimal> getUserExchangeCodeBalanceMap(List<Long> userIds) {
        Map<Long, BigDecimal> result = new HashMap<>();
        if (userIds == null || userIds.isEmpty()) {
            return result;
        }
        List<TExchangeCodeDetail> details = codeDetailMapper.selectList(new QueryWrapper<TExchangeCodeDetail>()
                .in("bind_user_id", userIds)
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0));
        for (TExchangeCodeDetail detail : details) {
            BigDecimal remainAmount = getDetailRemainAmount(detail);
            if (remainAmount.compareTo(BigDecimal.ZERO) > 0) {
                result.merge(detail.getBindUserId(), remainAmount, BigDecimal::add);
            }
        }
        return result;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeCodeConsumeResultVO consumeBalance(ExchangeCodeConsumeDTO dto) {
        if (dto == null || dto.getUserId() == null || dto.getOrderId() == null || dto.getAmount() == null) {
            throw new ServiceException("扣减参数不能为空");
        }
        ExchangeCodeConsumeResultVO resultVO = new ExchangeCodeConsumeResultVO();
        BigDecimal requestedAmount = dto.getAmount().setScale(2, RoundingMode.HALF_UP);
        if (requestedAmount.compareTo(BigDecimal.ZERO) <= 0) {
            resultVO.setDeductedAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));
            return resultVO;
        }
        List<TExchangeCodeUseRecord> existingRecords = useRecordMapper.selectList(new QueryWrapper<TExchangeCodeUseRecord>()
                .eq("order_id", dto.getOrderId())
                .eq("del_flag", 0));
        if (!existingRecords.isEmpty()) {
            BigDecimal deducted = existingRecords.stream()
                    .map(TExchangeCodeUseRecord::getUsedAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .setScale(2, RoundingMode.HALF_UP);
            resultVO.setDeductedAmount(deducted);
            return resultVO;
        }
        BigDecimal remainingNeed = requestedAmount;
        BigDecimal deductedAmount = BigDecimal.ZERO;
        List<TExchangeCodeDetail> details = codeDetailMapper.selectList(new QueryWrapper<TExchangeCodeDetail>()
                .eq("bind_user_id", dto.getUserId())
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0)
                .orderByAsc("bind_time", "id"));
        for (TExchangeCodeDetail detail : details) {
            if (remainingNeed.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
            BigDecimal remainAmount = getDetailRemainAmount(detail);
            if (remainAmount.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            BigDecimal useAmount = remainAmount.min(remainingNeed).setScale(2, RoundingMode.HALF_UP);
            detail.setUsedAmount(defaultMoney(detail.getUsedAmount()).add(useAmount).setScale(2, RoundingMode.HALF_UP));
            codeDetailMapper.updateById(detail);
            TExchangeCodeUseRecord record = new TExchangeCodeUseRecord();
            record.setDetailId(detail.getId());
            record.setOrderId(dto.getOrderId());
            record.setUserId(dto.getUserId());
            record.setUsedAmount(useAmount);
            useRecordMapper.insert(record);
            remainingNeed = remainingNeed.subtract(useAmount);
            deductedAmount = deductedAmount.add(useAmount);
        }
        resultVO.setDeductedAmount(deductedAmount.setScale(2, RoundingMode.HALF_UP));
        return resultVO;
    }
 
    private BigDecimal getDetailRemainAmount(TExchangeCodeDetail detail) {
        if (detail == null || detail.getPackageSpecId() == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        TExchangeCodePackageSpec spec = packageSpecMapper.selectById(detail.getPackageSpecId());
        if (spec == null || spec.getAmount() == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        BigDecimal remainAmount = spec.getAmount().subtract(defaultMoney(detail.getUsedAmount()));
        return remainAmount.compareTo(BigDecimal.ZERO) < 0
                ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)
                : remainAmount.setScale(2, RoundingMode.HALF_UP);
    }
 
    private TExchangeCodePackage buildPackageEntity(ExchangeCodePackageSaveDTO dto, TExchangeCodePackage entity) {
        entity.setPackageName(dto.getPackageName());
        entity.setCoverPicture(dto.getCoverPicture());
        entity.setDetailsPicture(dto.getDetailsPicture());
        entity.setExchangeDescription(dto.getExchangeDescription());
        entity.setRemark(dto.getRemark());
        entity.setInventory(dto.getInventory());
        entity.setUnlimitedReceiveLimit(dto.getUnlimitedReceiveLimit());
        entity.setReceiveLimit(Objects.equals(dto.getUnlimitedReceiveLimit(), 1) ? null : dto.getReceiveLimit());
        entity.setFinanceReceivedAmount(defaultMoney(dto.getFinanceReceivedAmount()));
        entity.setGiftAmount(defaultMoney(dto.getGiftAmount()));
        entity.setTotalAmount(defaultMoney(dto.getTotalAmount()));
        entity.setExpireTime(dto.getExpireTime());
        entity.setStatus(dto.getStatus());
        return entity;
    }
 
    private void validateSaveDTO(ExchangeCodePackageSaveDTO dto, boolean editing) {
        if (!StringUtils.hasText(dto.getPackageName())) {
            throw new ServiceException("请输入卡包名称");
        }
        if (dto.getInventory() == null || dto.getInventory() <= 0) {
            throw new ServiceException("库存必须大于0");
        }
        if (dto.getExpireTime() != null && dto.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException("截止领取时间不能早于当前时间");
        }
        if (!Objects.equals(dto.getUnlimitedReceiveLimit(), 1)
                && (dto.getReceiveLimit() == null || dto.getReceiveLimit() <= 0)) {
            throw new ServiceException("请输入领取限制次数");
        }
        if (dto.getSpecList() == null || dto.getSpecList().isEmpty()) {
            throw new ServiceException("请至少添加一个规格");
        }
        if (dto.getStatus() == null) {
            dto.setStatus(STATUS_DISABLE);
        }
        BigDecimal finance = defaultMoney(dto.getFinanceReceivedAmount());
        BigDecimal gift = defaultMoney(dto.getGiftAmount());
        BigDecimal total = defaultMoney(dto.getTotalAmount());
        if (finance.add(gift).compareTo(total) != 0) {
            throw new ServiceException("财务实收 + 赠送金额 必须等于规格总金额");
        }
        BigDecimal specTotal = BigDecimal.ZERO;
        int quantityTotal = 0;
        for (ExchangeCodePackageSpecDTO spec : dto.getSpecList()) {
            if (spec.getAmount() == null || spec.getAmount().compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("规格金额不正确");
            }
            if (spec.getQuantity() == null || spec.getQuantity() <= 0) {
                throw new ServiceException("规格数量必须大于0");
            }
            BigDecimal subtotal = spec.getAmount().multiply(BigDecimal.valueOf(spec.getQuantity()))
                    .setScale(2, RoundingMode.HALF_UP);
            spec.setSubtotalAmount(subtotal);
            specTotal = specTotal.add(subtotal);
            quantityTotal += spec.getQuantity();
        }
        if (specTotal.compareTo(total) != 0) {
            throw new ServiceException("总额必须等于所有规格金额乘数量之和");
        }
        if (quantityTotal != dto.getInventory()) {
            throw new ServiceException(editing ? "编辑后的库存必须等于规格数量总和" : "库存必须等于规格数量总和");
        }
        allocateDiscount(dto.getSpecList(), gift, total);
    }
 
    private void allocateDiscount(List<ExchangeCodePackageSpecDTO> specList, BigDecimal giftAmount, BigDecimal totalAmount) {
        if (giftAmount.compareTo(BigDecimal.ZERO) == 0 || totalAmount.compareTo(BigDecimal.ZERO) == 0) {
            for (ExchangeCodePackageSpecDTO spec : specList) {
                spec.setDiscountAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));
            }
            return;
        }
        BigDecimal allocated = BigDecimal.ZERO;
        for (int i = 0; i < specList.size(); i++) {
            ExchangeCodePackageSpecDTO spec = specList.get(i);
            BigDecimal discount;
            if (i == specList.size() - 1) {
                discount = giftAmount.subtract(allocated).setScale(2, RoundingMode.HALF_UP);
            } else {
                discount = spec.getSubtotalAmount().multiply(giftAmount)
                        .divide(totalAmount, 2, RoundingMode.HALF_UP);
                allocated = allocated.add(discount);
            }
            spec.setDiscountAmount(discount);
        }
    }
 
    private void saveSpecsAndCodes(Long packageId, List<ExchangeCodePackageSpecDTO> specList, Integer inventory, Integer oldInventory) {
        List<TExchangeCodePackageSpec> specEntities = new ArrayList<>();
        for (int i = 0; i < specList.size(); i++) {
            ExchangeCodePackageSpecDTO spec = specList.get(i);
            TExchangeCodePackageSpec entity = new TExchangeCodePackageSpec();
            entity.setPackageId(packageId);
            entity.setAmount(spec.getAmount());
            entity.setQuantity(spec.getQuantity());
            entity.setSubtotalAmount(spec.getSubtotalAmount());
            entity.setDiscountAmount(spec.getDiscountAmount());
            entity.setSort(spec.getSort() == null ? i + 1 : spec.getSort());
            packageSpecMapper.insert(entity);
            specEntities.add(entity);
        }
        int needCreate = oldInventory == null ? inventory : inventory - oldInventory;
        if (needCreate <= 0) {
            return;
        }
        String batchNo = "PKG" + LocalDateTime.now().format(BATCH_FORMATTER);
        List<TExchangeCodePackageSpec> expandList = new ArrayList<>();
        for (TExchangeCodePackageSpec spec : specEntities) {
            for (int i = 0; i < spec.getQuantity(); i++) {
                expandList.add(spec);
            }
        }
        if (expandList.isEmpty()) {
            expandList = Collections.nCopies(needCreate, null);
        }
        for (int i = 0; i < needCreate; i++) {
            TExchangeCodePackageSpec spec = expandList.get(i % expandList.size());
            TExchangeCodeDetail detail = new TExchangeCodeDetail();
            detail.setPackageId(packageId);
            detail.setPackageSpecId(spec == null ? null : spec.getId());
            detail.setCode(generateCode(packageId, i));
            detail.setPassword(generatePassword());
            detail.setStatus(CODE_STATUS_UNBOUND);
            detail.setBatchNo(batchNo);
            codeDetailMapper.insert(detail);
        }
    }
 
    private void refreshPackageStats(Long packageId) {
        TExchangeCodePackage entity = this.getById(packageId);
        if (entity == null) {
            return;
        }
        Long boundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                .eq("package_id", packageId)
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0));
        Long invalidCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                .eq("package_id", packageId)
                .eq("status", CODE_STATUS_INVALID)
                .eq("del_flag", 0));
        entity.setBoundCount(boundCount.intValue());
        entity.setInvalidCount(invalidCount.intValue());
        entity.setUnboundCount(entity.getInventory() - entity.getBoundCount() - entity.getInvalidCount());
        this.baseMapper.updateById(entity);
    }
 
    private String generateCode(Long packageId, int seq) {
        return "CD" + packageId + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss")) + String.format("%03d", seq);
    }
 
    private String generatePassword() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 8).toUpperCase();
    }
 
    private BigDecimal defaultMoney(BigDecimal amount) {
        return amount == null ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)
                : amount.setScale(2, RoundingMode.HALF_UP);
    }
}