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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
package com.by4cloud.platformx.business.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by4cloud.platformx.admin.api.entity.SysDept;
import com.by4cloud.platformx.admin.api.feign.RemoteDeptService;
import com.by4cloud.platformx.business.dto.BankStatementUpdateDTO;
import com.by4cloud.platformx.business.dto.BipQueryDTO;
import com.by4cloud.platformx.business.dto.PaymentConfirmAddDTO;
import com.by4cloud.platformx.business.entity.*;
import com.by4cloud.platformx.business.mapper.*;
import com.by4cloud.platformx.business.service.BankStatementService;
import com.by4cloud.platformx.business.service.PaymentConfirmService;
import com.by4cloud.platformx.business.vo.ReceiveBipVo;
import com.by4cloud.platformx.business.vo.ReceiveItemVo;
import com.by4cloud.platformx.business.vo.StatementContractVo;
import com.by4cloud.platformx.common.core.util.R;
import com.by4cloud.platformx.common.data.datascope.DataScope;
import com.by4cloud.platformx.common.security.util.SecurityUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * 银行流水
 *
 * @author syt
 * @date 2026-08-07 16:10:36
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BankStatementServiceImpl extends ServiceImpl<BankStatementMapper, BankStatement> implements BankStatementService {
 
    private final PaymentConfirmService paymentConfirmService;
    private final ContractMapper contractMapper;
    private final BusinessCustomerMapper businessCustomerMapper;
    private final StringRedisTemplate redisTemplate;
    private final RemoteDeptService remoteDeptService;
    private final BankStatementItemMapper bankStatementItemMapper;
    private final ErpRequestRecordMapper erpRequestRecordMapper;
    private final BipViewMapper bipViewMapper;
 
    @Value("${bip.url}")
    private String url;
 
    @Value("${bip.flag}")
    private Boolean bipFlag;
 
    @Value("${dept.sgb}")
    private String sgb;
 
    @Value("${erp.sgb}")
    private String sgbErp;
 
    @Override
    public R edit(BankStatementUpdateDTO updateDTO) {
        BankStatement statement = baseMapper.selectById(updateDTO.getId());
        if (CollUtil.isEmpty(updateDTO.getContractCollectionList())) {
            return R.failed("请选择收款合同后在提交");
        }
        BigDecimal toPaidTotal = updateDTO.getContractCollectionList().stream().map(StatementContractDTO::getToPaidAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (toPaidTotal.compareTo(statement.getTranAmount().subtract(statement.getConfirmAmount())) != 0) {
            return R.failed("确认收款总额必须与交易流水金额一致");
        }
 
        statement.setConfirmAmount(statement.getConfirmAmount().add(toPaidTotal));
        baseMapper.updateById(statement);
 
        updateDTO.getContractCollectionList().stream().forEach(statementContractDTO -> {
            Contract contract = contractMapper.selectById(statementContractDTO.getId());
            R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
            SysDept b = r.getData();
            BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
            BankStatementItem item = new BankStatementItem();
            item.setStatetId(statement.getId());
            item.setBankSeqNo(statement.getBankSeqNo());
            item.setConfirmAmount(statementContractDTO.getToPaidAmount());
            item.setContractId(statementContractDTO.getId());
            ReceiveBipVo bipVo = tranBipVo(statement, item, b, customer);
            item.setBipParam(JSONObject.toJSONString(bipVo));
            bankStatementItemMapper.insert(item);
            PaymentConfirmAddDTO addDTO = new PaymentConfirmAddDTO();
            addDTO.setBusGuestId(statement.getBusGuestId() + "");
            addDTO.setConfirmTime(statement.getTranDate());
            addDTO.setContractNo(contract.getContractNo());
            addDTO.setInOrOut(statement.getDcFlag());
            addDTO.setTransationAmount(statementContractDTO.getToPaidAmount());
            addDTO.setBankSeqNo(statement.getBankSeqNo());
            paymentConfirmService.add(addDTO);
 
        });
 
        //石工泵主动推送系统
        if ((StrUtil.equals(SecurityUtils.getUser().getCompId() + "", sgb)) && StrUtil.isNotEmpty(sgbErp)) {
            pushCollectionSgb(statement, updateDTO.getContractCollectionList());
        }
 
//        //判断是否内部单位
//        CustInfoVo custInfoVo = bipViewMapper.selectBaseInfoByCustName(statement.getPayBankAccName());
//        if (ObjUtil.isNull(custInfoVo)){
//            return R.ok();
//        }
//        //bip推送
//        if (bipFlag&&custInfoVo.getCustCode().equals("01")) {
//            return pushSaveCollection(statement, updateDTO.getContractCollectionList());
//        }
//        log.info("内部往来收款单,客户名称:{},客户类型:{},不用保存收款单",custInfoVo.getCustName(),custInfoVo.getCustclass());
        return R.ok();
    }
 
    private void pushCollectionSgb(BankStatement statement, List<StatementContractDTO> contractCollectionList) {
        JSONObject request = genErpParam(statement, contractCollectionList);
        statement.setPushParam(request.toJSONString());
        log.info("工业泵收款地址:{}", sgbErp + "/apilink/arclose/create?corpsecret=12345678&appserver=appserver1&accountid=888&tradeid=" + IdUtil.fastUUID());
 
//        HttpResponse resp = HttpUtil.createPost(sgbErp + "/apilink/arclose/create?corpsecret=12345678&appserver=appserver1&accountid=888&tradeid="
//                + IdUtil.fastUUID())
//                .header("Content-Type","application/x-www-form-urlencoded")
//                .body(URLEncodeUtil.encode(request.toJSONString(), StandardCharsets.UTF_8))
//                .timeout(30000)
//                // 指定编码格式
//                .charset(StandardCharsets.UTF_8)
//                .execute();
 
            log.info("工业泵收款入参:{}", "=" +request.toJSONString());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "=" + request.toJSONString());
            Request req = new Request.Builder()
                    .url(sgbErp + "/apilink/arclose/create?corpsecret=12345678&appserver=appserver1&accountid=888&tradeid=" + IdUtil.fastUUID())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            String result = "";
            try (Response response = client.newCall(req).execute()){
                if (response.isSuccessful()) {
                    // 仅调用一次string(),结果存入变量复用,后续所有逻辑直接读取该变量
                    result = response.body().string();
                    // 业务逻辑直接使用result,禁止再次调用response.body().string()
                }
            log.info("工业泵收款回参:{}", result);
            saveErpRequestRecord("sgb", "/apilink/arclose/create", request.toJSONString(), result);
            JSONObject respJson = JSONObject.parseObject(result);
            if (respJson.containsKey("errcode") && respJson.getString("errcode").equals("0")) {
                statement.setPushFlag(1);
                statement.setPushVouchNo(respJson.getString("code"));
                baseMapper.updateById(statement);
                return;
            }
            log.error("工业泵收款推送失败:{}", response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
    private void saveErpRequestRecord(String ymj, String medthodName, String toJSONString, String result) {
        ErpRequestRecord record = new ErpRequestRecord();
        record.setErpName(ymj);
        record.setMothedName(medthodName);
        record.setRequestParams(toJSONString);
        record.setResponseParams(result);
        erpRequestRecordMapper.insert(record);
    }
 
    private JSONObject genErpParam(BankStatement statement, List<StatementContractDTO> contractCollectionList) {
        JSONObject req = new JSONObject();
        Map<String, Object> djt = new LinkedHashMap<>();
        Contract contract = contractMapper.selectById(contractCollectionList.get(0).getId());
        BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
        djt.put("dVouchDate", DateUtil.formatDate(statement.getTranDate()));//单据日期
        if (ObjUtil.isNotNull(customer)) {
            djt.put("cDwCode", customer.getErpCompanyCode());//单位编码
        }
        djt.put("cexch_name", "人民币");//单位编码
        djt.put("cOperator", "10123");//录入人编码
        djt.put("cSSCode", "01");//录入人编码
        djt.put("iAmount", statement.getConfirmAmount());//人民币金额
        djt.put("cBankAccount", statement.getReceiveBankAccAcc());//本方银行账号
        djt.put("cBank", statement.getPayBankAccName());//本方银行账号
        djt.put("cContractType", "161");
        if (CollUtil.size(contractCollectionList)==1) {
            Contract contractHeader = contractMapper.selectById(contractCollectionList.get(0).getId());
            djt.put("cContractID", contractHeader.getErpContractNo());
        }
        req.put("单据头", djt);
        JSONObject line = new JSONObject();
        JSONArray array = new JSONArray();
 
        contractCollectionList.stream().forEach(statementContractDTO -> {
            JSONObject djti = new JSONObject();
            djti.put("cCusVen", customer.getErpCompanyCode());//往来单位编码
            djti.put("iAmt_f", statementContractDTO.getToPaidAmount());//本行本币金额
            djti.put("iAmt", statementContractDTO.getToPaidAmount());//本行本币金额
            djti.put("cPersonCode", "00164");//业务员编码
            djti.put("cConID", contract.getErpContractNo());//合同编码
            djti.put("款项类型", "应收款");
            djti.put("cConType","镇江市");
            array.add(djti);
        });
 
        line.put("行", array);
        req.put("单据体", line);
        JSONObject apicontext = new JSONObject();
        apicontext.put("username", "");
        req.put("apicontext", apicontext);
        return req;
    }
 
    private R pushSaveCollection(BankStatement statement, BankStatementItem bankStatementItem) {
        String accessToken = "";
        if (redisTemplate.hasKey("BIP_TOKEN")) {
            accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
        } else {
            accessToken = paymentConfirmService.getAccessToken(accessToken);
        }
        if (StrUtil.isEmpty(accessToken)) {
            log.error("bip accessToken 获取异常");
            return R.failed("bip accessToken 获取异常");
        }
        String finalAccessToken = accessToken;
 
        R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
        log.info("查询单位信息:{}", JSONObject.toJSONString(r.getData()));
        if (!r.isOk()) {
            log.error("查询单位信息异常");
            return R.failed("查询单位信息异常");
        }
        SysDept dept = r.getData();
        JSONObject params = genRequestParam(statement, dept, bankStatementItem);
 
        log.info("收款单集成 Request:{}", params.toJSONString());
        String result = HttpUtil.post(url + "/yonbip/EFI/collection/saveandsubmit?access_token=" + finalAccessToken, params.toJSONString());
        log.info("收款单集成 Response:{}", result);
 
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!resultJson.getString("code").equals("200")) {
            return R.failed(resultJson.getString("message"));
        }
        bankStatementItem.setBipPush("1");
        bankStatementItem.setBipId(resultJson.getJSONObject("data").getLong("id"));
        bankStatementItemMapper.updateById(bankStatementItem);
        return R.ok();
    }
 
    private JSONObject genRequestParam(BankStatement statement, SysDept dept, BankStatementItem statementItem) {
        Contract contract = contractMapper.selectById(statementItem.getContractId());
        BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
        ReceiveBipVo bipVo = BeanUtil.copyProperties(JSONObject.parseObject(statementItem.getBipParam()), ReceiveBipVo.class);
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("billDate", DateUtil.format(statement.getTranDate(), DatePattern.NORM_DATETIME_FORMAT));
        data.put("exchangeRate", "1");//汇率
        data.put("exchangeRateDate", DateUtil.now());//汇率时间
        data.put("objectType", "1");
        data.put("customerCode", customer.getBipCode());//客户编码
        data.put("financeOrgCode", dept.getBipCode());//开票组织编码
        data.put("orgCode", dept.getBipCode());//业务组织编码
        data.put("bustypeCode", "ar_colsale");// TODO 交易类型编码 暂估默认ZGYSFP,装备默认ZBYXGLXT暂时不能用
        data.put("oriCurrencyCode", "CNY");//币种
        data.put("srcBillType", "38");
        data.put("srcBillNo", statement.getBankSeqNo());
        data.put("_status", "Insert");
        JSONArray bodyItem = new JSONArray();
 
        JSONObject item = new JSONObject();
        item.put("oriTaxIncludedAmount", statementItem.getConfirmAmount());
        item.put("contractNo", contract.getContractNo());
        item.put("quickTypeCode", "1");
        item.put("_status", "Insert");
 
        item.put("expenseItemCode", bipVo.getItemList().get(0).getJjsx());//经济事项
        item.put("remarks", bipVo.getItemList().get(0).getZy());//摘要
        JSONObject freeChId = new JSONObject();
        freeChId.put("GX08", bipVo.getItemList().get(0).getHsdy());//核算单元
        freeChId.put("YSYF14", "1");//款项类型 1 预收款 2 应收款
        freeChId.put("JT04", bipVo.getItemList().get(0).getHsjylx());//核算交易类型 0101 集团外部 01020301 三级分子公司间 01020302 三级分公司与子子公司之间
        freeChId.put("JT06", bipVo.getItemList().get(0).getKxmx());//款项明细
        freeChId.put("JT12", bipVo.getItemList().get(0).getCpwlfl());//产品物料分类
 
        item.put("freeChId", freeChId);
 
 
        bodyItem.add(item);
        data.put("bodyItem", bodyItem);
        JSONObject datafreeChId = new JSONObject();
        datafreeChId.put("YSYF_SFZY", bipVo.getSfzy());//是否主营
        datafreeChId.put("fk_038", bipVo.getPzzdr());//凭证制单人
        datafreeChId.put("YSYF_08", bipVo.getSfnbwl());//是否内部往来
        datafreeChId.put("YSYF24", bipVo.getSfjyjs());//是否简易计税
        datafreeChId.put("fk_002", bipVo.getFjzs());//附件1
        datafreeChId.put("GX08", bipVo.getHsdy());//核算单元
        datafreeChId.put("TzMY042", contract.getExpirationDate());//预计回款日期
        data.put("freeChId", datafreeChId);
        data.put("remarks", bipVo.getZy());//摘要
        jsonObject.put("data", data);
        return jsonObject;
    }
 
    @Override
    public R getHistoryById(Long id) {
        MPJLambdaWrapper<BankStatementItem> wrapper = new MPJLambdaWrapper<BankStatementItem>()
                .selectAll(BankStatementItem.class)
                .select(Contract::getContractNo)
                .select(Contract::getPartyA)
                .select(Contract::getAmount)
                .leftJoin(Contract.class, Contract::getId, BankStatementItem::getContractId)
                .eq(BankStatementItem::getCompId, SecurityUtils.getUser().getCompId())
                .eq(BankStatementItem::getStatetId, id)
                .orderByDesc(BankStatementItem::getCreateTime);
        return R.ok(bankStatementItemMapper.selectJoinList(StatementContractVo.class, wrapper));
    }
 
    @Override
    public R delHistoryById(Long id) {
 
        BankStatementItem statement = bankStatementItemMapper.selectById(id);
        BankStatement bankStatement = baseMapper.selectById(statement.getStatetId());
        Contract contract = contractMapper.selectById(statement.getContractId());
        if (ObjUtil.isNull(contract)) {
            return R.failed("合同信息异常");
        }
        BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
        if (ObjUtil.isNull(customer)) {
            return R.failed("客户信息信息异常");
        }
        R<SysDept> r = remoteDeptService.getById(contract.getPartyBId());
        if (!r.isOk()) {
            return r;
        }
        //bip推送
        if (bipFlag) {
            String accessToken = "";
            if (redisTemplate.hasKey("BIP_TOKEN")) {
                accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
            } else {
                accessToken = paymentConfirmService.getAccessToken(accessToken);
            }
            if (StrUtil.isEmpty(accessToken)) {
                log.error("bip accessToken 获取异常");
                return R.failed("bip accessToken 获取异常");
            }
            String finalAccessToken = accessToken;
            JSONObject request = genRefundParam(bankStatement, statement, contract, customer, r.getData());
            log.info("收款退款单-退款单一历史确认请求入参:{}", request.toJSONString());
            String result = HttpUtil.post(url + "/yonbip/EFI/arRefund/saveandsubmit?access_token=" + finalAccessToken, request.toJSONString());
            log.info("收款退款单-退款单一历史确认请求回参:{}", result);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!resultJson.getString("code").equals("200")) {
                return R.failed(resultJson.getString("message"));
            }
        }
        bankStatementItemMapper.deleteById(id);
 
        bankStatement.setConfirmAmount(bankStatement.getConfirmAmount().subtract(statement.getConfirmAmount()));
        baseMapper.updateById(bankStatement);
        return R.ok();
    }
 
    private JSONObject genRefundParam(BankStatement bankStatement, BankStatementItem statement, Contract contract, BusinessCustomer customer, SysDept dept) {
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("billDate", DateUtil.now());
        data.put("exchangeRate", "1");//汇率
        data.put("exchangeRateDate", DateUtil.now());//汇率时间
        data.put("objectType", "1");
        data.put("customerCode", customer.getBipCode());//客户编码
        data.put("financeOrgCode", dept.getBipCode());//开票组织编码
        data.put("orgCode", dept.getBipCode());//业务组织编码
        data.put("bustypeCode", "ar_refsale");//交易类型编码 暂估默认ZGYSFP,销售默认MJHYXGLXT
        data.put("oriCurrencyCode", "CNY");//币种
        data.put("srcBillType", "38");
        data.put("srcBillNo", bankStatement.getBankSeqNo());
        data.put("_status", "Insert");
        JSONArray bodyItem = new JSONArray();
        JSONObject item = new JSONObject();
        item.put("oriTaxIncludedAmount", statement.getConfirmAmount());
        item.put("contractNo", contract.getContractNo());
        item.put("quickTypeCode", "1");
        item.put("_status", "Insert");
        bodyItem.add(item);
        data.put("bodyItem", bodyItem);
        jsonObject.put("data", data);
        return jsonObject;
    }
 
    @Override
    public R backBal(Long id) {
        BankStatement bankStatement = baseMapper.selectById(id);
        BusinessCustomer customer = businessCustomerMapper.selectById(bankStatement.getBusGuestId());
        if (ObjUtil.isNull(customer) || StrUtil.isEmpty(customer.getBipCode())) {
            log.error("查询客户信息异常");
            return R.failed("查询客户信息异常");
        }
        R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
        if (!r.isOk()) {
            log.error("查询单位信息异常");
            return R.failed("查询单位信息异常");
        }
        SysDept dept = r.getData();
        List<BankStatementItem> items = bankStatementItemMapper.selectList(Wrappers.<BankStatementItem>lambdaQuery()
                .eq(BankStatementItem::getStatetId, id));
        if (bipFlag) {
            String accessToken = "";
            if (redisTemplate.hasKey("BIP_TOKEN")) {
                accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
            } else {
                accessToken = paymentConfirmService.getAccessToken(accessToken);
            }
            if (StrUtil.isEmpty(accessToken)) {
                log.error("bip accessToken 获取异常");
                return R.failed("bip accessToken 获取异常");
            }
            String finalAccessToken = accessToken;
            JSONObject request = genBackBalParam(bankStatement, customer, dept, items);
            log.info("收款退款单-退款余额请求入参:{}", request.toJSONString());
            String result = HttpUtil.post(url + "/yonbip/EFI/arRefund/saveandsubmit?access_token=" + finalAccessToken, request.toJSONString());
            log.info("收款退款单-退款余额请求回参:{}", result);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!resultJson.getString("code").equals("200")) {
                return R.failed(resultJson.getString("message"));
            }
        }
        bankStatement.setTranAmount(bankStatement.getConfirmAmount());
        baseMapper.updateById(bankStatement);
        return R.ok();
    }
 
    private JSONObject genBackBalParam(BankStatement bankStatement, BusinessCustomer customer, SysDept dept, List<BankStatementItem> items) {
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("billDate", DateUtil.now());
        data.put("exchangeRate", "1");//汇率
        data.put("exchangeRateDate", DateUtil.now());//汇率时间
        data.put("objectType", "1");
        data.put("customerCode", customer.getBipCode());//客户编码
        data.put("financeOrgCode", dept.getBipCode());//开票组织编码
        data.put("orgCode", dept.getBipCode());//业务组织编码
        data.put("bustypeCode", "ar_refsale");//交易类型编码 暂估默认ZGYSFP,销售默认MJHYXGLXT
        data.put("oriCurrencyCode", "CNY");//币种
        data.put("srcBillType", "38");
        data.put("srcBillNo", bankStatement.getBankSeqNo());
        data.put("_status", "Insert");
        JSONArray bodyItem = new JSONArray();
        JSONObject item = new JSONObject();
        item.put("oriTaxIncludedAmount", bankStatement.getTranAmount().subtract(bankStatement.getConfirmAmount()));
        item.put("quickTypeCode", "1");
        item.put("_status", "Insert");
        bodyItem.add(item);
        data.put("bodyItem", bodyItem);
        jsonObject.put("data", data);
        return jsonObject;
    }
 
    @Override
    public R backAll(Long id) {
        BankStatement bankStatement = baseMapper.selectById(id);
        BusinessCustomer customer = businessCustomerMapper.selectById(bankStatement.getBusGuestId());
        if (ObjUtil.isNull(customer) || StrUtil.isEmpty(customer.getBipCode())) {
            log.error("查询客户信息异常");
            return R.failed("查询客户信息异常");
        }
        R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
        if (!r.isOk()) {
            log.error("查询单位信息异常");
            return R.failed("查询单位信息异常");
        }
        SysDept dept = r.getData();
        List<BankStatementItem> items = bankStatementItemMapper.selectList(Wrappers.<BankStatementItem>lambdaQuery()
                .eq(BankStatementItem::getStatetId, id));
        if (bipFlag) {
            String accessToken = "";
            if (redisTemplate.hasKey("BIP_TOKEN")) {
                accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
            } else {
                accessToken = paymentConfirmService.getAccessToken(accessToken);
            }
            if (StrUtil.isEmpty(accessToken)) {
                log.error("bip accessToken 获取异常");
                return R.failed("bip accessToken 获取异常");
            }
            String finalAccessToken = accessToken;
            JSONObject request = genBackAllParam(bankStatement, customer, dept, items);
            log.info("收款退款单-退款所有请求入参:{}", request.toJSONString());
            String result = HttpUtil.post(url + "/yonbip/EFI/arRefund/saveandsubmit?access_token=" + finalAccessToken, request.toJSONString());
            log.info("收款退款单-退款所有请求回参:{}", result);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!resultJson.getString("code").equals("200")) {
                return R.failed(resultJson.getString("message"));
            }
        }
        bankStatement.setConfirmAmount(new BigDecimal("0"));
        baseMapper.updateById(bankStatement);
        return R.ok();
    }
 
    private JSONObject genBackAllParam(BankStatement bankStatement, BusinessCustomer customer, SysDept dept, List<BankStatementItem> items) {
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("billDate", DateUtil.now());
        data.put("exchangeRate", "1");//汇率
        data.put("exchangeRateDate", DateUtil.now());//汇率时间
        data.put("objectType", "1");
        data.put("customerCode", customer.getBipCode());//客户编码
        data.put("financeOrgCode", dept.getBipCode());//开票组织编码
        data.put("orgCode", dept.getBipCode());//业务组织编码
        data.put("bustypeCode", "ar_refsale");//交易类型编码 暂估默认ZGYSFP,销售默认MJHYXGLXT
        data.put("oriCurrencyCode", "CNY");//币种
        data.put("srcBillType", "38");
        data.put("srcBillNo", bankStatement.getBankSeqNo());
        data.put("_status", "Insert");
        JSONArray bodyItem = new JSONArray();
        JSONObject item = new JSONObject();
        item.put("oriTaxIncludedAmount", bankStatement.getTranAmount());
        item.put("quickTypeCode", "1");
        item.put("_status", "Insert");
        bodyItem.add(item);
        data.put("bodyItem", bodyItem);
        jsonObject.put("data", data);
        return jsonObject;
    }
 
    @Override
    public R backHis(Long id) {
        BankStatement bankStatement = baseMapper.selectById(id);
        BusinessCustomer customer = businessCustomerMapper.selectById(bankStatement.getBusGuestId());
        if (ObjUtil.isNull(customer) || StrUtil.isEmpty(customer.getBipCode())) {
            log.error("查询客户信息异常");
            return R.failed("查询客户信息异常");
        }
        R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
        if (!r.isOk()) {
            log.error("查询单位信息异常");
            return R.failed("查询单位信息异常");
        }
        SysDept dept = r.getData();
        List<BankStatementItem> items = bankStatementItemMapper.selectList(Wrappers.<BankStatementItem>lambdaQuery()
                .eq(BankStatementItem::getStatetId, id));
        if (bipFlag) {
            String accessToken = "";
            if (redisTemplate.hasKey("BIP_TOKEN")) {
                accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
            } else {
                accessToken = paymentConfirmService.getAccessToken(accessToken);
            }
            if (StrUtil.isEmpty(accessToken)) {
                log.error("bip accessToken 获取异常");
                return R.failed("bip accessToken 获取异常");
            }
            String finalAccessToken = accessToken;
            JSONObject request = genBackHisParam(bankStatement, customer, dept, items);
            log.info("收款退款单-退款历史确认请求入参:{}", request.toJSONString());
            String result = HttpUtil.post(url + "/yonbip/EFI/arRefund/saveandsubmit?access_token=" + finalAccessToken, request.toJSONString());
            log.info("收款退款单-退款历史确认请求回参:{}", result);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!resultJson.getString("code").equals("200")) {
                return R.failed(resultJson.getString("message"));
            }
        }
 
        bankStatement.setConfirmAmount(new BigDecimal("0"));
        baseMapper.updateById(bankStatement);
        bankStatementItemMapper.deleteByIds(items.stream().map(item -> item.getId()).collect(Collectors.toList()));
        return R.ok();
    }
 
    private JSONObject genBackHisParam(BankStatement bankStatement, BusinessCustomer customer, SysDept dept, List<BankStatementItem> items) {
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("billDate", DateUtil.now());
        data.put("exchangeRate", "1");//汇率
        data.put("exchangeRateDate", DateUtil.now());//汇率时间
        data.put("objectType", "1");
        data.put("customerCode", customer.getBipCode());//客户编码
        data.put("financeOrgCode", dept.getBipCode());//开票组织编码
        data.put("orgCode", dept.getBipCode());//业务组织编码
        data.put("bustypeCode", "ar_refsale");//交易类型编码 暂估默认ZGYSFP,销售默认MJHYXGLXT
        data.put("oriCurrencyCode", "CNY");//币种
        data.put("srcBillType", "38");
        data.put("srcBillNo", bankStatement.getBankSeqNo());
        data.put("_status", "Insert");
        JSONArray bodyItem = new JSONArray();
        for (BankStatementItem statementItem : items) {
            Contract contract = contractMapper.selectById(statementItem.getContractId());
            JSONObject item = new JSONObject();
            item.put("oriTaxIncludedAmount", statementItem.getConfirmAmount());
            item.put("contractNo", contract.getContractNo());
            item.put("quickTypeCode", "1");
            item.put("_status", "Insert");
            bodyItem.add(item);
        }
        data.put("bodyItem", bodyItem);
        jsonObject.put("data", data);
        return jsonObject;
    }
 
    private ReceiveBipVo tranBipVo(BankStatement statement, BankStatementItem bankStatementItem, SysDept b, BusinessCustomer customer) {
        ReceiveBipVo bipVo = new ReceiveBipVo();
        bipVo.setDjrq(DateUtil.formatDate(statement.getTranDate()));
        bipVo.setKpzz(b.getBipCode());
        bipVo.setYwzz(b.getBipCode());
        R<SysDept> rDept = remoteDeptService.getById(SecurityUtils.getUser().getDeptId());
        if (rDept.isOk()) {
            bipVo.setBm(rDept.getData().getOrgCode());
            bipVo.setHsdy(rDept.getData().getOrgCode());
        }
        bipVo.setYwy(SecurityUtils.getUser().getNickname());
        bipVo.setPzzdr(SecurityUtils.getUser().getNickname());
        bipVo.setJylx("ZBYXGLXT");
        bipVo.setWldxlx("1");
        bipVo.setKh(customer.getCreditCode());
        bipVo.setBz("CNY");
        bipVo.setFjzs("0");
        bipVo.setSfzy("1");
        bipVo.setSfnbwl("1");
        bipVo.setSfjyjs("0");
        bipVo.setDjfx("1");
        List<ReceiveItemVo> list = new ArrayList<>();
        ReceiveItemVo itemVo = new ReceiveItemVo();
        itemVo.setConfirmAmount(bankStatementItem.getConfirmAmount());
        list.add(itemVo);
        bipVo.setItemList(list);
        return bipVo;
    }
 
    @Override
    public Page pageBip(Page page, BipQueryDTO queryDTO) {
        return baseMapper.pageBip(page, queryDTO, DataScope.of("comp_id"));
    }
 
    @Override
    public R saveAndPush(BankStatementUpdateDTO updateDTO) {
        BankStatementItem item = bankStatementItemMapper.selectById(updateDTO.getId());
        item.setBipParam(updateDTO.getBipParam());
        bankStatementItemMapper.updateById(item);
        BankStatement statement = baseMapper.selectById(item.getStatetId());
        return pushSaveCollection(statement, item);
    }
}