zhangmei
2025-02-28 1fe1ac0e09132e0147e48007986be235e4130aa1
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
package com.ruoyi.system.service.impl;
 
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.basic.PageInfo;
import com.ruoyi.common.constant.AmountConstant;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TencentMailUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.dto.OfflinePayCheckDto;
import com.ruoyi.system.dto.SmsByBillDto;
import com.ruoyi.system.dto.TBillDto;
import com.ruoyi.system.dto.TbillSaveDto;
import com.ruoyi.system.mapper.TBillMapper;
import com.ruoyi.system.model.*;
import com.ruoyi.system.query.TBillQuery;
import com.ruoyi.system.query.TInvoiceToBillQuery;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.TBillVO;
import com.taxi591.bankapi.dto.ChargeBillRequest;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.*;
import java.util.stream.Collectors;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;
import java.util.function.Consumer;
 
/**
 * <p>
 * 租金账单 服务实现类
 * </p>
 *
 * @author xiaochen
 * @since 2025-01-17
 */
@Service
@Slf4j
public class TBillServiceImpl extends ServiceImpl<TBillMapper, TBill> implements TBillService {
 
    @Autowired
    RedisCache redisCache;
 
    @Autowired
    TBillMapper tBillMapper;
 
    @Autowired
    TBillDetailService tBillDetailService;
 
    @Autowired
    TFlowManagementService tFlowManagementService;
 
    @Autowired
    TBankFlowService tBankFlowService;
 
    @Autowired
    TBillConfirmService tBillConfirmService;
 
    @Autowired
    TPayOrderService tPayOrderService;
 
    @Autowired
    TOrderBillService orderBillService;
 
    @Autowired
    TInvoiceToBillService tInvoiceToBillService;
 
 
    @Resource
    SmsUtil smsUtil;
 
    @Resource
    TencentMailUtil mailUtil;
 
    public PageInfo<TBillDto> queryPage(TBillQuery query){
        PageInfo<TBill> pageInfo = new PageInfo<>(query.getPageNum(), query.getPageSize());
        PageInfo<TBillDto> info = tBillMapper.page(pageInfo, query);
        return info;
    }
 
    @Override
    public List<String> getBillIds(TBillQuery query) {
        List<TBillDto> billDtos = tBillMapper.getBillList(query);
        return billDtos.stream().map(TBillDto::getId).collect(Collectors.toList());
    }
 
    @Override
    public PageInfo<TBillDto> invoiceList(TBillQuery query) {
        PageInfo<TBillDto> pageInfo = new PageInfo<>(query.getPageNum(), query.getPageSize());
        List<TBillDto> list = tBillMapper.invoiceList(query,pageInfo);
        pageInfo.setRecords(list);
        return pageInfo;
    }
 
    private static final String[] ignorePro = {"payableFeesMoney","payableFeesPenalty","payFeesMoney","outstandingMoney"};
 
    /**
     *
     * 更新类型  1.仅更新信息及状态 2.更新信息、金额及状态
     * 为1时,仅更新非金额之外的信息及状态
     * 为2时,传入的金额,是需要增加或减少的金额,非计算后的金额
     * 当账单状态为已缴费后,不做任何更新
     * @param tBill
     * @param type
     * @return
     */
    public TBill lockAndUpdateInfo(@NotNull TBill tBill, @NotNull Integer type){
        if (StringUtils.isEmpty(tBill.getId())){
            throw new ServiceException("账单主键ID不能为空");
        }
        String requestId = UUID.fastUUID().toString();
        String lockkey = CacheConstants.BILL_UPDATE_LOCK_KEY + tBill.getId();
        boolean isok = redisCache.trylockLoop(lockkey, requestId, 60);
        if (isok){
            try {
                TBill save = new TBill();
                TBill presist = getById(tBill.getId());
                //如果账单是已缴费状态,本方法不再进行更新账单
                if (presist.getPayFeesStatus().equals("3")){
                    throw new ServiceException("该账单已缴费完成");
                }
                switch (type){
                    // 仅更新除金额字段外的属性
                    case 1:
                    {
                        BeanUtils.copyProperties(tBill,save,ignorePro);
                    }
                    break;
                    // 计算并更新金额、存入违约金、已缴费金额会自动计算欠费,如计算出无欠费则会更新状态为已缴费
                    case 2:
                    {
                        BeanUtils.copyProperties(tBill,save);
 
                        // 处理应缴费 ,注意一般情况下不会修改该金额
                        if (tBill.getPayableFeesMoney()!=null){
                            presist.setPayableFeesMoney(presist.getPayableFeesMoney()!=null?presist.getPayableFeesMoney():BigDecimal.ZERO);
                            BigDecimal result = presist.getPayableFeesMoney().add(tBill.getPayableFeesMoney());
                            save.setPayableFeesMoney(result);
                            //计算欠费 = 应缴费(新)+违约金-已缴费
                            BigDecimal outstand = save.getPayableFeesMoney()
                                    .add(presist.getPayableFeesPenalty())
                                    .subtract(presist.getPayFeesMoney());
                            save.setOutstandingMoney(outstand);
                        }
                        //处理应缴违约金 ,不能和缴费金额一起传
                        if (tBill.getPayableFeesPenalty()!=null){
                            presist.setPayableFeesPenalty(presist.getPayableFeesPenalty()!=null?presist.getPayableFeesPenalty():BigDecimal.ZERO);
                            BigDecimal result = presist.getPayableFeesPenalty().add(tBill.getPayableFeesPenalty());
                            save.setPayableFeesPenalty(result);
                            //计算欠费 = 应缴费+违约金(新)-已缴费
                            BigDecimal outstand = presist.getPayableFeesMoney()
                                    .add(save.getPayableFeesPenalty())
                                    .subtract(presist.getPayFeesMoney());
                            save.setOutstandingMoney(outstand);
                        }
                        //处理缴费金额
                        if (tBill.getPayFeesMoney()!=null){
                            presist.setPayFeesMoney(presist.getPayFeesMoney()!=null?presist.getPayFeesMoney():BigDecimal.ZERO);
                            BigDecimal result = presist.getPayFeesMoney().add(tBill.getPayFeesMoney());
                            save.setPayFeesMoney(result);
                            //缴费后的欠费 =(应缴费+违约金)-已缴费金额
                            BigDecimal outstand = save.getPayableFeesMoney()
                                    .add(presist.getPayableFeesPenalty())
                                    .subtract(save.getPayFeesMoney());
                            save.setOutstandingMoney(outstand);
                            //抵扣金额就是缴费金额
                            save.setDeductionMoney(tBill.getPayableFeesMoney());
                            save.setPreOutstand(presist.getOutstandingMoney());
                            if (outstand.compareTo(BigDecimal.ZERO)<=0){
                                save.setPayFeesStatus("3");
                            }
                        }
                    }
                    break;
 
                }
                updateById(save);
                return save;
            }finally {
                redisCache.unlock(lockkey,requestId);
            }
        }
        return null;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean lockAndUpdateByAmountBatch(List<TBill> bills, BigDecimal amount, Consumer<TBill> consumer) {
        List<TBill> result = bills.stream().sorted(Comparator.comparing(TBill::getCreateTime))
                .collect(Collectors.toList());
        BigDecimal remain = amount;
        for (TBill bill : result) {
            //如果剩余金额小于账单欠费金额,则
            if (remain.compareTo(bill.getOutstandingMoney())<=0){
                TBill param = new TBill();
                param.setId(bill.getId());
                param.setPayFeesMoney(remain);
                TBill tBill = lockAndUpdateInfo(param, 2);
                if (consumer!=null){
                    consumer.accept(tBill);
                }
                break;
            }
            remain = remain.subtract(bill.getOutstandingMoney());
            TBill param = new TBill();
            param.setId(bill.getId());
            param.setPayFeesMoney(bill.getOutstandingMoney());
            TBill tBill = lockAndUpdateInfo(param, 2);
            if (consumer!=null){
                consumer.accept(tBill);
            }
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBill(TbillSaveDto bill) {
        save(bill);
        if (bill.getBillType().equals("3")){
            if (bill.getDetails()==null || bill.getDetails().size()==0){
                throw new ServiceException("生活费用列表不能为空");
            }
            for (TBillDetail detail : bill.getDetails()) {
                detail.setBillId(bill.getId());
                tBillDetailService.save(detail);
            }
        }
    }
 
    @Override
    public boolean checkOfflinePay(OfflinePayCheckDto dto) {
        List<TBill> tBills = listByIds(dto.getBillIds());
        TBillConfirm confirm = tBillConfirmService.getById(dto.getConfirmId());
        lockAndUpdateByAmountBatch(tBills,dto.getAmount(),(bill)->{
            TFlowManagement save = new TFlowManagement();
            save.setPayType(3);
            save.setPayer(dto.getPayer());
            save.setPayTime(dto.getPayTime()==null?DateUtils.dateToLocalDateTime(confirm.getPayTime()):dto.getPayTime());
            save.setBankSerialNumber(dto.getBankSerilNum());
            save.setFlowType(2);
            save.setPaymentBillId(bill.getId());
            save.setDeductionMoney(bill.getDeductionMoney());
            save.setFlowMoney(dto.getAmount());
            save.setRemainingMoney(bill.getOutstandingMoney());
            save.setPreOutstand(bill.getPreOutstand());
            tFlowManagementService.save(save);
        });
        TBankFlow bankFlow = new TBankFlow();
        bankFlow.setPayType(3);
        bankFlow.setPayer(dto.getPayer());
        bankFlow.setPayTime(dto.getPayTime()==null?DateUtils.dateToLocalDateTime(confirm.getPayTime()):dto.getPayTime());
        bankFlow.setBankSerialNumber(dto.getBankSerilNum());
        bankFlow.setFlowMoney(dto.getAmount());
        bankFlow.setFlowStatus(1);
        tBankFlowService.save(bankFlow);
        return false;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completePay(ChargeBillRequest billRequest) {
        String orderNo = billRequest.getMessage().getInfo().getInput1();
        String uuid = UUID.fastUUID().toString();
        boolean lock = redisCache.trylockLoop(CacheConstants.COMPLETE_PAY_LOCK_KEY + orderNo, uuid, 60);
        if (lock){
            TPayOrder order = tPayOrderService.getById(orderNo);
            if (order==null){
                throw new ServiceException("订单不存在");
            }
            if (StringUtils.isNotEmpty(order.getPayNo())){
                log.info("订单号已处理:{}",orderNo);
                return;
            }
            /**
             * 更新订单状态
             */
            TPayOrder save = new TPayOrder();
            save.setId(order.getId());
            save.setStatus(1);
            save.setPayNo(billRequest.getMessage().getInfo().getTraceNo());
            save.setPayType(billRequest.getMessage().getHead().getChannel());
            try {
                save.setPayTime(DateUtils.parseDate(billRequest.getMessage().getHead().getTimeStamp(),"yyyyMMddHHmmssSSS"));
            } catch (ParseException e) {
                throw new ServiceException("日期格式化错误");
            }
            save.setCallbackTime(new Date());
            BigDecimal payAmount = new BigDecimal(billRequest.getMessage().getInfo().getPayBillAmt());
            save.setActPayAmount(payAmount
                    .multiply(AmountConstant.b100).longValue());
            save.setStatus(1);
            save.setPayInfo(billRequest.getMessage().toString());
            tPayOrderService.updateById(save);
            /**
             * 更新账单状态
             */
            List<TOrderBill> orderBills = orderBillService.getByOrderNo(order.getId());
            List<TBill> bills = orderBills.stream().map(ob -> getById(ob.getBillId())).collect(Collectors.toList());
            lockAndUpdateByAmountBatch(bills,payAmount,(bill)->{
                TFlowManagement saveFlow = new TFlowManagement();
                saveFlow.setPayType(1);
                saveFlow.setPayer(order.getUserId());
                saveFlow.setPayTime(DateUtils.dateToLocalDateTime(save.getPayTime()));
                saveFlow.setBankSerialNumber(save.getPayNo());
                saveFlow.setFlowType(2);
                saveFlow.setPaymentBillId(bill.getId());
                saveFlow.setDeductionMoney(bill.getDeductionMoney());
                saveFlow.setFlowMoney(payAmount);
                saveFlow.setRemainingMoney(bill.getOutstandingMoney());
                saveFlow.setPreOutstand(bill.getPreOutstand());
                tFlowManagementService.save(saveFlow);
            });
            TBankFlow bankFlow = new TBankFlow();
            bankFlow.setPayType(1);
            bankFlow.setPayer(order.getUserId());
            bankFlow.setPayTime(DateUtils.dateToLocalDateTime(save.getPayTime()));
            bankFlow.setBankSerialNumber(save.getPayNo());
            bankFlow.setFlowMoney(payAmount);
            bankFlow.setFlowStatus(1);
            tBankFlowService.save(bankFlow);
 
        }
 
    }
 
    /**
     * 根据发票编号查询账单列表
     * @param invoiceId
     * @return
     */
    @Override
    public PageInfo<TBillDto> getBillByInvoiceId(String invoiceId){
        PageInfo<TBillDto> pageInfo = new PageInfo<>();
        ArrayList<TBillDto> bills = new ArrayList<>();
        TInvoiceToBillQuery query = new TInvoiceToBillQuery();
        query.setInvoiceId(invoiceId);
        List<TInvoiceToBill> tInvoiceToBills = tInvoiceToBillService.makeQuery(query);
        for (TInvoiceToBill tInvoiceToBill : tInvoiceToBills) {
            TBill bill = getById(tInvoiceToBill.getBillId());
            if (bill != null && bill.getId() != null){
                TBillDto detailByBillId = getDetailByBillId(bill.getId());
                bills.add(detailByBillId);
            }
        }
        pageInfo.setRecords(bills);
        return pageInfo;
    }
 
 
 
    @Override
    public Integer sendSmsByBillIds(SmsByBillDto dto) {
        int failNum = 0;
        for (String billId : dto.getBillIds()) {
            TBillDto bill = getDetailByBillId(billId);
            if (bill.getSmsLastTime()!=null
                    && (System.currentTimeMillis()-bill.getSmsLastTime().getTime()<smsUtil.getPro().getBillSmsDelayPeriod()*60*1000L)){
                throw new ServiceException("有账单最近一次发送的时间是:"+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,bill.getSmsLastTime()));
            }
            if (StringUtils.isEmpty(bill.getPhone())){
                failNum++;
                continue;
            }
            TBill save = new TBill();
            save.setId(bill.getId());
            try {
                smsUtil.sendSms(bill.getPhone(), "", new String[]{""});
                save.setSmsStatus(1);
            }catch (ServiceException e){
                failNum++;
                save.setSmsStatus(2);
            }
            save.setSmsLastTime(new Date());
            save.setSmsSendUserid(dto.getSendUserId());
            lockAndUpdateInfo(save,1);
        }
        return failNum;
    }
 
    @Override
    public Integer sendMailBatchByBillIds(SmsByBillDto dto) {
        int failNum = 0;
        for (String billId : dto.getBillIds()) {
            TBillDto bill = getDetailByBillId(billId);
            if (bill.getSmsLastTime()!=null
                    && (System.currentTimeMillis()-bill.getSmsLastTime().getTime()<mailUtil.getPro().getBillMailDelayPeriod()*60*1000L)){
                throw new ServiceException("有账单最近一次发送的时间是:"+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,bill.getSmsLastTime()));
            }
            if (StringUtils.isEmpty(bill.getEmail())){
                failNum++;
                continue;
            }
            TBill save = new TBill();
            save.setId(bill.getId());
            try {
                mailUtil.send(bill.getEmail(),bill.getHouseName());
                save.setMailStatus(1);
            }catch (ServiceException e){
                failNum++;
                save.setMailStatus(2);
            }
            save.setMailLastTime(new Date());
            save.setMailSendUserid(dto.getSendUserId());
            lockAndUpdateInfo(save,1);
        }
        return failNum;
    }
 
    public TBillDto getDetailByBillId(@NotEmpty String billId) {
        return getBaseMapper().selectDetailByBillId(billId);
    }
 
 
}