liujie
9 天以前 e86d554ee5476d89845f86a49864d990180542b5
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
package com.ruoyi.system.service.impl;
 
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.pojo.dto.FinanceFlowsDTO;
import com.ruoyi.system.pojo.dto.OrderPageDTO;
import com.ruoyi.system.pojo.model.DailyStatistics;
import com.ruoyi.system.pojo.vo.*;
import com.ruoyi.system.service.CompanyTypeService;
import com.ruoyi.system.service.OrderService;
import com.ruoyi.system.wx.RefundCallbackResult;
import com.ruoyi.system.wx.WechatPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
 
    @Resource
    private PermitMapper permitMapper;
 
    @Resource
    private OpeningBankMapper openingBankMapper;
    @Resource
    private BuyerCompanyInfoMapper buyerCompanyInfoMapper;
    @Resource
    private ShareholderMapper shareholderMapper;
    @Resource
    private ScheduleMapper scheduleMapper;
    @Resource
    private CompanyMapper companyMapper;
 
    @Autowired
    private AppUserMapper appUserMapper;
 
    @Resource
    private RedisCache redisCache;
    @Resource
    private QichachaMapper qichachaMapper;
 
    @Resource
    private CompanyTypeService companyTypeService;
 
 
    @Resource
    private AccountDetailMapper accountDetailMapper;
 
 
    @Override
    public IPage<OrderPageVO> getOrderPage(OrderPageDTO dto) {
        IPage<OrderPageVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        return this.baseMapper.getOrderPage(page,dto);
    }
 
    @Override
    public OrderDetailVO detail(String id) {
        OrderDetailVO vo = this.baseMapper.getDetailById(id);
        if (null == vo) {
            throw new ServiceException("该公司不存在");
        }
        //许可证集合
        List<Permit> permits = permitMapper.selectList(new LambdaQueryWrapper<Permit>().eq(Permit::getCompanyId, id));
        List<PermitVO> permitVOs = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (Permit permit : permits) {
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate expireDate = LocalDate.parse(permit.getExpireTime(), dateFormatter);
 
            // 如果需要转为 LocalDateTime(添加默认时间)
            LocalDateTime expireTime = expireDate.atTime(23,59,59); // 默认00:00:00
            if (now.isAfter(expireTime)) {
                //过滤 未过期的
                PermitVO permitVO = new PermitVO();
                permitVO.setName(permit.getName());
                permitVO.setLevel(permit.getLevel());
                permitVOs.add(permitVO);
            }
        }
        vo.setPermitVOList(permitVOs);
        //开户行信息集合
        List<OpeningBank> openingBanks = openingBankMapper.selectList(new LambdaQueryWrapper<OpeningBank>().eq(OpeningBank::getCompanyId, id));
        List<OpeningBankVO> openingBankVOs = new ArrayList<>();
        for (OpeningBank openingBank : openingBanks) {
            OpeningBankVO openingBankVO = new OpeningBankVO();
            BeanUtils.copyProperties(openingBank, openingBankVO);
            openingBankVOs.add(openingBankVO);
        }
        vo.setOpeningBankVOList(openingBankVOs);
 
        if (vo.getStatus() != 4 && vo.getStatus() != 5&& vo.getStatus() != 6) {
            return vo;
        }
 
        //状态为办理中和已完成
        //客户信息
        BuyerCompanyInfo buyerCompanyInfo = buyerCompanyInfoMapper.selectOne(new LambdaQueryWrapper<BuyerCompanyInfo>().eq(BuyerCompanyInfo::getOrderId, vo.getOrderId()));
        copyProperties(vo,buyerCompanyInfo);
        //股东占比
        List<Shareholder> shareholders = shareholderMapper.selectList(new LambdaQueryWrapper<Shareholder>().eq(Shareholder::getOrderId, vo.getOrderId()));
        vo.setShareholderList(shareholders);
        //进度汇报
        List<Schedule> schedules = scheduleMapper.selectList(new LambdaQueryWrapper<Schedule>().eq(Schedule::getOrderId, vo.getOrderId()));
        //构建进度汇报结构
        List<Schedule> scheduleVOList = new ArrayList<>();
        for (Schedule schedule : schedules) {
            if (schedule.getParentId() == null) {
                scheduleVOList.add(schedule);
            }else {
                //查找到父类的集合
                for (Schedule schedule1 : scheduleVOList) {
                    if (schedule1.getId().equals(schedule.getParentId())) {
                        schedule1.setSchedule(schedule);
                    }
                }
            }
        }
        vo.setScheduleList(scheduleVOList);
        return vo;
    }
 
    private static void copyProperties(OrderDetailVO vo,BuyerCompanyInfo info){
        vo.setLegalPersonImg(info.getLegalPersonImg());
        vo.setNewName(info.getNewName());
        vo.setBackupsName(info.getBackupsName());
        vo.setBackupsNameOne(info.getBackupsNameOne());
        vo.setBackupsNameTwo(info.getBackupsNameTwo());
        vo.setNewRegisteredCapital(info.getRegisteredCapital());
        vo.setAccount(info.getAccount());
        vo.setAddress(info.getAddress());
        vo.setPassword(info.getPassword());
        vo.setTenancyAgreement(info.getTenancyAgreement());
        vo.setPropertyOwnershipCertificate(info.getPropertyOwnershipCertificate());
        vo.setBusinessScope(info.getBusinessScope());
    }
 
    @Override
    public BusinessVO business(String id) {
        //先查询数据库中的
        Company company = companyMapper.selectById(id);
        if (null == company || company.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }
        BusinessVO vo = new BusinessVO();
        BeanUtils.copyProperties(company, vo);
        vo.setNewRegisteredCapital(company.getRealRegisteredCapital());
        vo.setPlace(company.getCity()+company.getProvince()+company.getArea());
 
        String name = companyTypeService.getById(company.getCompanyCategory()).getName();
        vo.setCompanyCategoryName(name);
 
        //todo 再查企业工商信息 覆盖掉之前的
 
 
        return vo;
    }
 
    @Override
    public R  error(String id) {
        ErrorVO errorVO = new ErrorVO();
        Company company = companyMapper.selectById(id);
        if (null == company || company.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }
        JSONObject result = getQiChaChaCompanyExceptionCheck(company.getCompanyName());
        if("200".equals(result.get("Status"))){
            //查询成功
            JSONObject data = (JSONObject) result.get("Result");
            Integer verifyResult = (Integer) data.get("VerifyResult");
            errorVO.setVerifyResult(verifyResult);
            if (verifyResult==1){
                //该企业有异常数据
                JSONArray list = (JSONArray) data.get("Data");
                errorVO.setData(list);
            }
            return R.ok(errorVO);
        }else {
            //查询失败
            return R.fail(result.get("Message"));
        }
 
    }
 
 
    /**
     * 经营异常核查
     * @param companyName
     * @return
     * VerifyResult  int    数据是否存在(1-存在,0-不存在)
     * Data      List<Object>  数据信息
     * Data:[{
     *     AddReason  列入经营异常名录原因
     *     AddDate    列入日期
     *     RomoveReason  移出经营异常名录原因(保留字段)
     *     RemoveDate   移出日期(保留字段)
     *     DecisionOffice      作出决定机关
     *     RemoveDecisionOffice  移出决定机关(保留字段)
     * }]
     * Status
     * Message
     * OrderNumber
     */
    public  JSONObject getQiChaChaBasicDetailsCompany(String companyName){
        Object cacheObject = redisCache.getCacheObject("qichacha_" +"basic_"+ companyName);
        if(cacheObject != null){
            JSONObject jsonObject = JSONObject.parseObject(cacheObject.toString());
            return jsonObject;
        }
        String url = "https://api.qichacha.com/ECIV4/GetBasicDetailsByName?key=642987ca3faf4a7daeac70463ae22695&keyword="+companyName;
        HttpRequest get = HttpUtil.createGet(url);
        String timeStr = String.valueOf(System.currentTimeMillis() / 1000);
        get.header("Token", SecureUtil.md5("642987ca3faf4a7daeac70463ae22695"+timeStr+"AC776F2957291EAE3B4161702E89A9F3").toUpperCase());
        get.header("Timespan", timeStr);
        HttpResponse execute = get.execute();
        String body = execute.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if("200".equals(jsonObject.get("Status"))){
            //查询成功
            String string = jsonObject.toString();
            redisCache.setCacheObject("qichacha_"+"basic_"+companyName,string,24, TimeUnit.HOURS);
            //统计调用次数
            Qichacha qichacha = new Qichacha();
            qichacha.setTime(LocalDateTime.now());
            qichacha.setType(1);//企业异常查询
            qichachaMapper.insert(qichacha);
 
            return jsonObject;
        }
        return jsonObject;
    }
 
    /**
     * 经营异常核查
     * @param companyName
     * @return
     * VerifyResult  int    数据是否存在(1-存在,0-不存在)
     * Data      List<Object>  数据信息
     * Data:[{
     *     AddReason  列入经营异常名录原因
     *     AddDate    列入日期
     *     RomoveReason  移出经营异常名录原因(保留字段)
     *     RemoveDate   移出日期(保留字段)
     *     DecisionOffice      作出决定机关
     *     RemoveDecisionOffice  移出决定机关(保留字段)
     * }]
     * Status
     * Message
     * OrderNumber
     */
    public  JSONObject getQiChaChaCompanyExceptionCheck(String companyName){
        Object cacheObject = redisCache.getCacheObject("qichacha_" + companyName);
        if(cacheObject != null){
            JSONObject jsonObject = JSONObject.parseObject(cacheObject.toString());
            return jsonObject;
        }
        String url = "https://api.qichacha.com/ExceptionCheck/GetList?key=642987ca3faf4a7daeac70463ae22695&searchKey="+companyName;
        HttpRequest get = HttpUtil.createGet(url);
        String timeStr = String.valueOf(System.currentTimeMillis() / 1000);
        get.header("Token", SecureUtil.md5("642987ca3faf4a7daeac70463ae22695"+timeStr+"AC776F2957291EAE3B4161702E89A9F3").toUpperCase());
        get.header("Timespan", timeStr);
        HttpResponse execute = get.execute();
        String body = execute.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if("200".equals(jsonObject.get("Status"))){
            //查询成功
            String string = jsonObject.toString();
            redisCache.setCacheObject("qichacha_"+companyName,string,24, TimeUnit.HOURS);
            //统计调用次数
            Qichacha qichacha = new Qichacha();
            qichacha.setTime(LocalDateTime.now());
            qichacha.setType(2);//企业异常查询
            qichachaMapper.insert(qichacha);
 
            return jsonObject;
        }
        return jsonObject;
    }
    private  JSONObject getReport(String sign){
        Object cacheObject = redisCache.getCacheObject("shuimu_" + sign);
        if(cacheObject != null){
            JSONObject jsonObject = JSONObject.parseObject(cacheObject.toString());
            return jsonObject;
        }
        HttpRequest post = HttpUtil.createPost("https://shuimui.szsmjr.com/index/index/result");
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("Origin","https://shuimui.szsmjr.com");
        post.addHeaders(stringStringHashMap);
        post.body("{\"sn\":\""+sign+"\"}");
        HttpResponse execute = post.execute();
        String body = execute.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if("1001".equals(jsonObject.get("code"))){
            //查询成功
            String string = jsonObject.toString();
            redisCache.setCacheObject("shuimu_"+sign,string,1, TimeUnit.MINUTES);
            return jsonObject;
        }
        return jsonObject;
    }
    @Override
    public R change(String id) {
//        System.err.println(getReport("ZZD20250508017232394218445"));
        ChangeVO changeVO = new ChangeVO();
       /* Company companyInfo = companyMapper.selectById(id);
        if (null == companyInfo || companyInfo.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }*/
//        JSONObject jsonObject=getReport(companyInfo.getLink().split("=")[1]);
        JSONObject jsonObject=getReport("ZZD20250508017232394218445");
        if (!"1001".equals(jsonObject.getString("code"))){
            return R.fail(jsonObject.get("msg"));
        }
        JSONObject data1 = (JSONObject) jsonObject.get("data");
        JSONObject data2 = (JSONObject) data1.get("data");
        JSONObject company = (JSONObject) data2.get("company");
        // 银税互动
        JSONArray bankAndTaxInteractive = (JSONArray)  company.get("bankAndTaxInteractive");
        changeVO.setBankAndTaxInteractive(bankAndTaxInteractive);
        //股东明细
        JSONArray sharesRatioList = (JSONArray)  company.get("sharesRatioList");
        changeVO.setSharesRatioList(sharesRatioList);
        //法人/股东变更
        JSONArray legalPersonGdChange = (JSONArray) company.get("legalPersonGdChange");
        changeVO.setLegalPersonGdChange(legalPersonGdChange);
 
        return R.ok(changeVO);
    }
 
    @Override
    public R tax(String id) {
        TaxVO taxVO = new TaxVO();
       /* Company companyInfo = companyMapper.selectById(id);
        if (null == companyInfo || companyInfo.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }*/
//        JSONObject jsonObject=getReport(companyInfo.getLink().split("=")[1]);
        JSONObject jsonObject=getReport("ZZD20250508017232394218445");
        if (!"1001".equals(jsonObject.getString("code"))){
            return R.fail(jsonObject.get("msg"));
        }
        JSONObject data1 = (JSONObject) jsonObject.get("data");
        JSONObject data2 = (JSONObject) data1.get("data");
        JSONObject taxInfo = (JSONObject) data2.get("taxInfo");
        //税务处罚
        JSONObject enterprise = (JSONObject) data2.get("enterprise");
        taxVO.setEnterprise(enterprise);
        //滞纳金情况
        JSONArray overdueFineDetailsList = (JSONArray) taxInfo.get("overdueFineDetailsList");
        taxVO.setOverdueFineDetailsList(overdueFineDetailsList);
 
        //近四年纳税信息完税表
        JSONArray taxPrev4yearsTaxInfoDict = (JSONArray) taxInfo.get("taxPrev4yearsTaxInfoDict");
        taxVO.setTaxPrev4yearsTaxInfoDict(taxPrev4yearsTaxInfoDict);
 
        //纳税信用等级
        String taxCreditRating = (String) taxInfo.get("taxCreditRating");
        taxVO.setTaxCreditRating(taxCreditRating);
 
        //纳税人种类
        String taxpayerType = (String) taxInfo.get("taxpayerType");
        taxVO.setTaxpayerType(taxpayerType);
 
        //近12月增税销售额
        JSONObject taxPrevMnMthsAllTaxDclrPrjInfoDict = (JSONObject) taxInfo.get("taxPrevMnMthsAllTaxDclrPrjInfoDict");
 
        JSONObject taxPrev12mthsAllTaxDclrPrjInfoDict = (JSONObject) taxPrevMnMthsAllTaxDclrPrjInfoDict.get("taxPrev12mthsAllTaxDclrPrjInfoDict");
        taxVO.setVatTaxShouldsaleAmt12((BigDecimal) taxPrev12mthsAllTaxDclrPrjInfoDict.get("vatTaxShouldsaleAmt"));
        //近24月增税销售额
        JSONObject taxPrev24mthsAllTaxDclrPrjInfoDict = (JSONObject) taxPrevMnMthsAllTaxDclrPrjInfoDict.get("taxPrev24mthsAllTaxDclrPrjInfoDict");
 
        taxVO.setVatTaxShouldsaleAmt24( (BigDecimal) taxPrev24mthsAllTaxDclrPrjInfoDict.get("vatTaxShouldsaleAmt"));
        JSONObject taxPrevMnMthsTaxInfoDict = (JSONObject) taxInfo.get("taxPrevMnMthsTaxInfoDict");
 
        //近12月纳税总额(元)
        JSONObject taxPrev12mthsTaxInfo = (JSONObject) taxPrevMnMthsTaxInfoDict.get("taxPrev12mthsTaxInfo");
        taxVO.setTaxAmt12( (BigDecimal) taxPrev12mthsTaxInfo.get("taxAmt"));
 
        //近24月纳税总额(元)
        JSONObject taxPrev24mthsTaxInfo = (JSONObject) taxPrevMnMthsTaxInfoDict.get("taxPrev24mthsTaxInfo");
        taxVO.setTaxAmt24( (BigDecimal) taxPrev24mthsTaxInfo.get("taxAmt"));
 
        //近12月增税应纳额(元)
        taxVO.setVatTaxShouldpay( (BigDecimal) taxPrev12mthsAllTaxDclrPrjInfoDict.get("vatTaxShouldpay"));
 
        //近12个月滞纳金金额(元) 次数
        JSONObject taxPrevMnMthsOverdueFineInfoDict = (JSONObject) taxInfo.get("taxPrevMnMthsOverdueFineInfoDict");
        JSONObject taxPrev12mthsOverdueFineInfo = (JSONObject) taxPrevMnMthsOverdueFineInfoDict.get("taxPrev12mthsOverdueFineInfo");
        taxVO.setOverdueFineInfoAmt12( (BigDecimal) taxPrev12mthsOverdueFineInfo.get("overdueFineInfoAmt"));
        taxVO.setOverdueFineInfoCnt12( (Integer) taxPrev12mthsOverdueFineInfo.get("overdueFineInfoCnt"));
 
 
        // 近3个月滞纳金金额(元)
        JSONObject taxPrev3mthsOverdueFineInfo = (JSONObject) taxPrevMnMthsOverdueFineInfoDict.get("taxPrev3mthsOverdueFineInfo");
        taxVO.setOverdueFineInfoCnt3( (Integer) taxPrev3mthsOverdueFineInfo.get("overdueFineInfoCnt"));
 
        //近12月0申报月数(月数)
        JSONObject taxPrevMnMthsAllTaxDclrInfoDict = (JSONObject) taxInfo.get("taxPrevMnMthsAllTaxDclrInfoDict");
        JSONObject taxPrev12mthsAllTaxDclrInfoDict = (JSONObject) taxPrevMnMthsAllTaxDclrInfoDict.get("taxPrev12mthsAllTaxDclrInfoDict");
        taxVO.setVatTax0dclrMonCnt( (Integer) taxPrev12mthsAllTaxDclrInfoDict.get("vatTax0dclrMonCnt"));
 
        return R.ok(taxVO);
    }
 
    @Override
    public R invoice(String id) {
        InvoiceVO vo = new InvoiceVO();
       /* Company companyInfo = companyMapper.selectById(id);
        if (null == companyInfo || companyInfo.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }*/
//        JSONObject jsonObject=getReport(companyInfo.getLink().split("=")[1]);
        JSONObject jsonObject=getReport("ZZD20250508017232394218445");
        if (!"1001".equals(jsonObject.getString("code"))){
            return R.fail(jsonObject.get("msg"));
        }
        JSONObject data1 = (JSONObject) jsonObject.get("data");
        JSONObject data2 = (JSONObject) data1.get("data");
        JSONObject invoiceInfo = (JSONObject) data2.get("invoiceInfo");
        //近45日是否有开票记录
        vo.setAnyPre45daysFpRcd((Boolean) invoiceInfo.get("anyPre45daysFpRcd"));
 
        //近一个月开票金额(元)
        JSONArray f4yPer1mDownFpInfoList = (JSONArray) invoiceInfo.get("f4yPer1mDownFpInfoList");
        JSONObject f4yPer1mDownFpInfo1 = (JSONObject) f4yPer1mDownFpInfoList.get(1);
        vo.setHjjeZc1( ObjectToBigDecimal(f4yPer1mDownFpInfo1.get("hjjeZc")) );
 
 
        JSONObject fpPrevMnMthsDownFpInfoList = (JSONObject) invoiceInfo.get("fpPrevMnMthsDownFpInfoList");
        JSONObject fpPrev3mthsDownFpInfoList = (JSONObject) fpPrevMnMthsDownFpInfoList.get("fpPrev3mthsDownFpInfoList");
        //近3个月开票环比增长率
        vo.setAvgMonJshjYxMomRate3( ObjectToBigDecimal(fpPrev3mthsDownFpInfoList.get("avgMonJshjYxMomRate")) );
        //近3个月开票金额(元)
        vo.setHjjeZc3( ObjectToBigDecimal( fpPrev3mthsDownFpInfoList.get("hjjeZc") ));
 
        JSONObject fpPrev6mthsDownFpInfoList = (JSONObject) fpPrevMnMthsDownFpInfoList.get("fpPrev6mthsDownFpInfoList");
        //近6个月开票环比增长率
        vo.setAvgMonJshjYxMomRate6( ObjectToBigDecimal(fpPrev6mthsDownFpInfoList.get("avgMonJshjYxMomRate")) );
        //近6月开票金额(元)
        vo.setHjjeZc6( ObjectToBigDecimal(fpPrev6mthsDownFpInfoList.get("hjjeZc"))  );
 
 
        JSONObject fpPrev12mthsDownFpInfoList = (JSONObject) fpPrevMnMthsDownFpInfoList.get("fpPrev12mthsDownFpInfoList");
        //近12个月开票环比增长率
        vo.setAvgMonJshjYxMomRate12( ObjectToBigDecimal(fpPrev12mthsDownFpInfoList.get("avgMonJshjYxMomRate")) );
        //近12月开票金额(元)
        vo.setHjjeZc12( ObjectToBigDecimal(fpPrev12mthsDownFpInfoList.get("hjjeZc"))  );
 
        //近24个月开票金额(元)
        JSONObject fpPrev24mthsDownFpInfoList = (JSONObject) fpPrevMnMthsDownFpInfoList.get("fpPrev24mthsDownFpInfoList");
        vo.setHjjeZc24( ObjectToBigDecimal(fpPrev24mthsDownFpInfoList.get("hjjeZc") ));
 
        //近12个月下游客户统计
        vo.setDownCusCnt3( (Integer) fpPrev3mthsDownFpInfoList.get("downCusCnt"));
        //近12个月下游客户统计
        vo.setDownCusCnt12( (Integer) fpPrev12mthsDownFpInfoList.get("downCusCnt"));
 
        //近12个月下游开票张数
        vo.setKpslQb( (Integer) fpPrev12mthsDownFpInfoList.get("kpslQb"));
 
        //近12月作废发票数量占比
        vo.setKpslFpRatio(ObjectToBigDecimal(fpPrev12mthsDownFpInfoList.get("kpslFpRatio")));
 
        //近12月月均开票金额增长率
        vo.setAvgMonJshjYxYoyRate(ObjectToBigDecimal(fpPrev12mthsDownFpInfoList.get("avgMonJshjYxYoyRate")) );
 
        //近12月红冲发票张数占比
        vo.setKpslHpRatio(ObjectToBigDecimal(fpPrev12mthsDownFpInfoList.get("kpslHpRatio")));
 
        //近12个月红冲金额占比
        vo.setHjjeHpRatio(ObjectToBigDecimal(fpPrev12mthsDownFpInfoList.get("hjjeHpRatio")) );
 
        //近12个月最大连续未开票间隔天数(销项)
        vo.setNokpslYxMaxdayCnt((Integer) fpPrev12mthsDownFpInfoList.get("nokpslYxMaxdayCnt"));
 
        //近三年开票信息报表(元)
        vo.setF4yPer1mDownFpInfoList(f4yPer1mDownFpInfoList);
 
        return R.ok(vo);
    }
 
    private BigDecimal ObjectToBigDecimal(Object o) {
        // 处理不同类型的情况
        if ( o instanceof BigDecimal) {
            return (BigDecimal) o;
        } else if (o instanceof Number) {
            // 将其他数字类型(如 Integer、Double)转换为 BigDecimal
            return BigDecimal.valueOf(((Number) o).doubleValue());
 
        }
        return BigDecimal.ZERO;
    }
    @Transactional
    @Override
    public void delete(String id) {
        Company company = companyMapper.selectById(id);
        if (null == company || company.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }
        if (company.getStatus().equals(3)){//已完成
            throw new ServiceException("状态错误,已完成订单不能删除");
        }
 
        if (company.getStatus().equals(4)){//锁定中
            //查看订单状态是否为待确认
            Order order = this.baseMapper.selectOne(new LambdaQueryWrapper<Order>()
                    .eq(Order::getCompanyId, company.getId())
                            .eq(Order::getIsRefund,0)
                    .ne(Order::getStatus,-1));//取消的订单不要
            if (null == order) {
                throw new ServiceException("订单不存在");
            }
            if (!order.getStatus().equals(2)) {//不在待确认状态的
                throw new ServiceException("状态错误,不能删除");
            }
            //删除订单
            this.baseMapper.deleteById(order.getId());
        }
        //删除公司
        company.setIsDelete(1);
        companyMapper.updateById(company);
    }
 
    /**
     * 上下架
     */
    @Override
    public void shelves(String id) {
        Company company = companyMapper.selectById(id);
        if (null == company || company.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }
        if (company.getStatus().equals(3)){//已完成
            throw new ServiceException("状态错误,已完成订单不能修改");
        }
 
        if (company.getStatus().equals(4)){//锁定中
            //查看订单状态是否为待确认
            Order order = this.baseMapper.selectOne(new LambdaQueryWrapper<Order>()
                    .eq(Order::getCompanyId, company.getId())
                    .ne(Order::getStatus,-1)//取消的不要
            );
            if (null == order) {
                throw new ServiceException("订单不存在");
            }
            if (!order.getStatus().equals(2)) {//不在待确认状态的
                throw new ServiceException("状态错误,不能修改");
            }
            //删除订单
            this.baseMapper.deleteById(order.getId());
        }
        //上下架
        if (company.getStatus().equals(1)||company.getStatus().equals(4)){//1-上架中  4-锁定中(待确认)
            company.setStatus(2);//2-下架中
        }else if (company.getStatus().equals(2)){
            company.setStatus(1);
        }
        companyMapper.updateById(company);
 
    }
 
    @Transactional
    @Override
    public void cancel(String id) {
        Company company = companyMapper.selectById(id);
        if (null == company || company.getIsDelete() != 0) {
            throw new ServiceException("公司不存在");
        }
        if (!company.getStatus().equals(4)){// 4-锁定中
            throw new ServiceException("订单状态错误,不能操作");
        }
        //查看订单
        Order order = this.baseMapper.selectOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getCompanyId, company.getId())
                .ne(Order::getStatus,-1));
        if (null == order) {
            throw new ServiceException("订单不存在");
        }
        //检查状态  3已确认(未付款) 4办理中 5卖家已完成
        if (!order.getStatus().equals(3)&&!order.getStatus().equals(4)&&!order.getStatus().equals(5)) {
            throw new ServiceException("订单状态错误,不能操作");
        }
        if (order.getStatus().equals(3)){
            //未付款 直接取消订单
            order.setStatus(-1);
            this.baseMapper.updateById(order);
            //将分佣次数加回
            User user = appUserMapper.selectById(order.getUserId());
            user.setInviteNum(user.getInviteNum()+1);
            appUserMapper.updateById(user);
            //商品状态修改
            company.setStatus(1);
            order.setIsRefund(1);
            order.setRefundTime(LocalDateTime.now());
            companyMapper.updateById(company);
        }else{
            // 判断是否能退
            if(order.getShareUserId()!=null){
                User user = appUserMapper.selectById(order.getShareUserId());
                if(user.getBalance().doubleValue()<order.getCommissionPrice().doubleValue()){
                    throw new ServiceException("退款失败,卖家上级余额不足");
                }
            }
 
 
            R r = refundPayMoney(order);//退款
            if (200 == r.getCode()) {
                //退款申请成功
                log.info("退款申请成功,订单id:{}",order.getId());
            }
        }
    }
 
    @Override
    public R refundPayMoneyCallback(String xmlData ) {
        RefundCallbackResult result = wechatPayService.processRefundCallback(xmlData);
        if (!result.isSuccess()) {
            System.out.println("会员退费错误:"+result.getMsg());
            return R.fail(result.getMsg());
        }
        Order order = this.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, result.getOrderNo()));
        if (null == order || order.getStatus() == -1) {
            return R.ok();
        }
        order.setStatus(-1);
        order.setIsRefund(1);
        order.setRefundTime(LocalDateTime.now());
        this.updateById(order);
        //查找公司
        Company company = companyMapper.selectById(order.getCompanyId());
 
        //取消订单
        order.setStatus(-1);
        order.setIsRefund(1);
        order.setRefundTime(LocalDateTime.now());
        this.baseMapper.updateById(order);
        //将分佣次数加回
        User user = appUserMapper.selectById(order.getUserId());
        User inviter = appUserMapper.selectById(user.getInviteId());
        if (inviter!=null && inviter.getIsDelete()==0){
            inviter.setInviteNum(inviter.getInviteNum()+1);
            appUserMapper.updateById(inviter);
        }
 
        //商品状态修改
        company.setStatus(1);
        companyMapper.updateById(company);
 
        return R.ok();
    }
    /**
     * 返回订单支付金额
     */
    @Autowired
    private WechatPayService wechatPayService;
    @Transactional
    public R refundPayMoney(Order order) {
        //开始退款
        if (BigDecimal.ZERO.compareTo(order.getPrice()) < 0) {//支付的金额是否大于0
            //微信退款
            Map<String,String> map = wechatPayService.refund(order.getOrderNo(), order.getOrderNo(), order.getPrice().toString(), order.getPrice().toString(), "平台取消订单", "/system/order/refundPayMoneyCallback");
 
            if (!"SUCCESS".equals(map.get("return_code"))) {
                return R.fail(map.get("return_msg"));//退款失败
            }
        }
        //查找公司
        Company company = companyMapper.selectById(order.getCompanyId());
 
        //取消订单
        order.setStatus(-1);
        order.setIsRefund(1);
        order.setRefundTime(LocalDateTime.now());
        this.baseMapper.updateById(order);
 
        //将分佣次数加回
        User inviter = appUserMapper.selectById(company.getUserId());
        if (inviter!=null && inviter.getIsDelete()==0){
            inviter.setInviteNum(inviter.getInviteNum()+1);
            appUserMapper.updateById(inviter);
        }
 
        // 分佣退回
        if(order.getShareUserId()!=null && order.getCommissionPrice().doubleValue()>0){
            User user = appUserMapper.selectById(order.getShareUserId());
            user.setBalance(user.getBalance().subtract(order.getCommissionPrice()));
            appUserMapper.updateById(user);
            AccountDetail accountDetail = new AccountDetail();
            accountDetail.setUserId(order.getShareUserId());
            accountDetail.setType(2);
            accountDetail.setCategory(4);
            accountDetail.setSourceId(order.getId());
            accountDetail.setMoney(order.getCommissionPrice());
            accountDetail.setRemark("订单取消分佣退回");
            accountDetailMapper.insert(accountDetail);
        }
 
        //商品状态修改
        company.setStatus(1);
        companyMapper.updateById(company);
 
        return R.ok();
    }
 
 
    @Override
    public TodayStatisticsVO today() {
        LocalDateTime startTime = LocalDate.now().atStartOfDay();
        LocalDateTime endTime =LocalDate.now().atTime(23, 59, 59);
        return this.baseMapper.today(startTime, endTime);
    }
 
    @Override
    public IndexLineChartVO chart(LocalDate startDate, LocalDate endDate) {
        // 查询数据库
        List<DailyStatistics> statisticsList = this.baseMapper.getDailyStatistics(
                startDate.atStartOfDay(),
                endDate.atTime(23, 59, 59)
        );
        // 构建返回对象
        IndexLineChartVO vo = new IndexLineChartVO();
        vo.setDays(new ArrayList<>());
        vo.setTotalList(new ArrayList<>());
        vo.setProfitList(new ArrayList<>());
        // 按日期顺序填充数据
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            String dateStr = currentDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
            vo.getDays().add(currentDate);
 
            // 查找当天数据,若无则默认为0
            Optional<DailyStatistics> statOptional = statisticsList.stream()
                    .filter(s -> s.getDate().equals(dateStr))
                    .findFirst();
 
            DailyStatistics stat = statOptional.orElse(
                    new DailyStatistics(dateStr, BigDecimal.ZERO, BigDecimal.ZERO)
            );
 
            vo.getTotalList().add(stat.getTotalPrice());
            vo.getProfitList().add(stat.getPlatformCommission());
 
            currentDate = currentDate.plusDays(1);
        }
        return vo;
 
    }
 
    @Override
    public FinanceFlowsTopVO financeTop(FinanceFlowsDTO dto) {
        FinanceFlowsTopVO financeFlowsTopVO = this.baseMapper.financeTop(dto);
        return financeFlowsTopVO;
    }
 
    @Override
    public IPage<FinanceFlowsPageVO> flowsPage(FinanceFlowsDTO dto) {
        IPage<FinanceFlowsPageVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Long total  = this.baseMapper.countFlowsPage(dto);
        //分页处理
        dto.setOffset((dto.getPageNum()-1)*dto.getPageSize());
        IPage<FinanceFlowsPageVO> financeFlowsPageVOIPage = this.baseMapper.flowsPage(page, dto);
        financeFlowsPageVOIPage.setTotal(total);
        return financeFlowsPageVOIPage;
    }
 
 
 
}