Air
2024-11-04 29c405353029f033e187e8dc033b93385365ee43
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
package com.nova.sankuai.infra.utils.hht;
 
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nova.sankuai.domain.api.aliyunIP.AliyunUtil;
import com.nova.sankuai.domain.api.aliyunIP.CustomerIpInfo;
import com.nova.sankuai.domain.api.hht.HhtIncomeResponse;
import com.nova.sankuai.domain.api.hjqb.HjqbResponse;
import com.nova.sankuai.domain.entity.*;
import com.nova.sankuai.domain.enums.capitalInfo.CapitalInfoTypeCodeEnum;
import com.nova.sankuai.domain.vo.capitalresult.LvdiPushResultVo;
import com.nova.sankuai.infra.config.CommonException;
import com.nova.sankuai.infra.mapper.CityMapper;
import com.nova.sankuai.infra.mapper.CustomerCapitalResultMapper;
import com.nova.sankuai.infra.mapper.CustomerMapper;
import com.nova.sankuai.infra.utils.RbUtil;
import com.nova.sankuai.infra.utils.ResultJson;
import com.nova.sankuai.infra.utils.UserUtil;
import com.nova.sankuai.security.HttpClientUtil;
import com.nova.sankuai.security.UserDetail;
import com.nova.sankuai.service.IChannelInfoService;
import com.nova.sankuai.service.ICustomerScyIncomeService;
import com.nova.sankuai.service.ICustomerUserService;
import com.nova.sankuai.service.IPlatformCapitalService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
 
import static java.util.Map.Entry.comparingByKey;
import static java.util.stream.Collectors.toMap;
 
/**
 * 好汇推对接
 */
@Component
@RequiredArgsConstructor
public class HhtUtil {
    private static final Logger log = LoggerFactory.getLogger("capitalLogger");
 
    private static final String CHARSET_NAME = "utf8";
 
    private static final Long capitalId = 41L;
 
    @Value("${hht.zkUrl}")
    private String zkUrl;
 
    @Value("${hht.jkUrl}")
    private String jkUrl;
 
    @Value("${hht.channelCode}")
    private String channelCode;
 
    @Value("${hht.version}")
    private String version;
 
    @Value("${hht.aesKey}")
    private String aesKey;
 
    @Value("${hht.secretKey}")
    private String secretKey;
 
    @Value("${hht.personalAuthorizationUrl}")
    private String personalAuthorizationUrl;
 
    private String getJobAage(String workStartTime, String workEndTime) {
        if (StringUtils.isBlank(workStartTime)) {// 若为空,则不取该条数据
            return "";
        }
        workStartTime = workStartTime.substring(0, 10);
        LocalDate endDate = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(workStartTime, formatter);
        if (StringUtils.isNotBlank(workEndTime)) {
            workEndTime = workEndTime.substring(0, 10);
            endDate = LocalDate.parse(workEndTime, formatter);
        } else {
            endDate = LocalDate.now();
        }
 
 
        long month = ChronoUnit.MONTHS.between(startDate, endDate);
 
        // F:0-6个月 G:6-12个月 H:12个月以上
        if (month < 6) {
            return "F";
        } else if (month >= 6 && month < 12) {
            return "G";
        }
 
        return "H";
    }
 
    private final CustomerMapper customerMapper;
    private final CustomerCapitalResultMapper capitalResultMapper;
    private final IPlatformCapitalService platformCapitalService;
    private final ICustomerUserService customerUserService;
    private final ICustomerScyIncomeService customerZcyIncomeService;
    private final CityMapper cityMapper;
 
 
    //I:3万-5万 J:5万-10万 K:10万-30万 M:30万-50万 N:50万-100万
    public static String checkValue(double value) {
        if (value >= 30000 && value < 50000) {
            return "I"; // 3万到5万
        } else if (value >= 50000 && value < 100000) {
            return "J"; // 5万到10万
        } else if (value >= 100000 && value < 300000) {
            return "K"; // 10万到30万
        } else if  (value >= 300000 && value < 500000) {
            return "L"; // 30万到50万
        } else if (value >= 500000 && value < 1000000) {
            return "M"; // 50万到100万
        }else {
            return "I";
        }
    }
 
    private final IChannelInfoService channelInfoService;
 
    private JSONObject getParam(Customer customer) {
        // 获取source_channel
        Integer sourceChannel = customer.getSourceChannel();
        Integer version2Type = 0;//判断是否2.0开关子参数
        if (!Objects.isNull(sourceChannel)) {
            ChannelInfo channelInfo = channelInfoService.getOne(new LambdaQueryWrapper<ChannelInfo>().eq(ChannelInfo::getCode, sourceChannel).last(" limit 1 "));
            version2Type = channelInfo.getVersion2Type();
        }
 
        Random random = new Random();
        String[] values;
        int randomIndex;
 
        JSONObject param = new JSONObject();
 
        /*社保*/
        String soci = "BB";
        /*公积金*/
        String accu = "FF";
        /*信用卡 WW:无信用卡   MMM:1万及以下  NNN:1万以上*/
        String creditCard = "WW";
 
        if (version2Type == 1) { //线上放款
            /*社保  在"Z:连续6个月以下 AA:连续6个月"中随机匹配*/
            values = new String[]{"Z", "AA"};
            soci = values[random.nextInt(values.length)];
 
            /*公积金 均在"DD:连续6个月以下 FF:连续6个月"中随机匹配*/
            values = new String[]{"DD", "EE"};
            accu = values[random.nextInt(values.length)];
 
            /*信用卡 均在"MMM:1万及以下  NNN:1万以上"中随机匹配*/
            values = new String[]{"MMM", "NNN"};
            creditCard = values[random.nextInt(values.length)];
 
 
        }else { //银行直贷
            /*社保  Z:连续6个月以下 AA:连续6个月 BB:无本地社保*/
            Integer social = customer.getSocialSecurity();
            int soc = Objects.isNull(social) ? 0 : social.intValue();
            if (soc == 1) {
                soci = "Z";
            } else if (soc == 2) {
                soci = "AA";
            }
 
            /*公积金 DD:连续6个月以下 EE:连续6个月 FF:无本地公积金*/
            Integer accumulation = customer.getProvidentFund();
            int at = Objects.isNull(accumulation) ? 0 : accumulation.intValue();
            if (at == 1) accu = "DD";
            else if (at == 2) accu = "EE";
 
            /*信用卡 WW:无信用卡   MMM:1万及以下  NNN:1万以上*/
            Integer cc = customer.getCreditCard();
            int ccV = Objects.isNull(cc) ? 0 : cc.intValue();
 
            if (ccV == 3) {
                creditCard = "MMM";
            } else if (ccV == 4 || ccV == 5) {
                creditCard = "NNN";
            }
        }
        param.put("socialSecurity", soci);
        param.put("providentFund", accu);
        param.put("creditCard", creditCard);
 
        param.put("name", customer.getName());
 
        param.put("ip", !StringUtils.isEmpty(customer.getClientIp()) ? customer.getClientIp() : "127.0.0.1");
 
        /*系统类型
        android :安卓   ios:苹果*/
        param.put("osType", !StringUtils.isEmpty(customer.getOs()) ? customer.getOs() : "android");
 
        /*系统版本 如Android 6.0 iPhone OS 13_2_3 等*/
        param.put("osVersion", !StringUtils.isEmpty(customer.getDeviceOsVersion()) ? customer.getDeviceOsVersion() : "Android 14");
 
        /*性别
        SM:男  SW:女*/
        String sex = RbUtil.getGenderByIDCard(customer.getIdCard());
        param.put("sex", "男".equals(sex) ? "SM" : "SW");
        /*年龄 10-99的正整数。如34*/
        param.put("age", RbUtil.calculateAgeFromIdNumber(customer.getIdCard()));
 
        /*用户所在城市区划代码 */
        String cityCode = customer.getCity();
        if (StringUtils.isEmpty(cityCode)) {
            City cityInfo = cityMapper.selectOne(new LambdaQueryWrapper<City>().
                    likeRight(City::getName, customer.getCityName()).last(" limit 1 "));
            if (cityInfo != null) {
                cityCode = cityInfo.getCityId();
            }
        }
        if (StringUtils.isEmpty(cityCode)) {
            cityCode = "310100";
        }
        param.put("cityCode", cityCode.substring(0, 6));
 
        /*职业身份  A:上班族   B:个体户 C:自由职业 BS:企业主*/
        Integer pi = customer.getProfessionInfo();
        int professionInfo = 1;// 默认自由职业
        String job = "";
        if (!Objects.isNull(pi)) {
            professionInfo = pi.intValue();
        }
        if (professionInfo == 1) {
            job = "C";
        } else if (professionInfo == 2) {
            job = "A";
        } else if (professionInfo == 3) {
            job = "BS";
        }else {
            values = new String[]{"A", "B", "C", "BS"};
            randomIndex = random.nextInt(values.length);
            job = values[randomIndex];
        }
        param.put("profession", job);
 
        if ("A".equals(job)) {
            /*工资发放方式 D:银行卡 E:现金*/
            values = new String[]{"D", "E"};
            randomIndex = random.nextInt(values.length);
            param.put("payType", values[randomIndex]);
            /* 工龄 F:0-6个月 G:6-12个月 H:12个月以上*/
            values = new String[]{"F", "G", "H"};
            randomIndex = random.nextInt(values.length);
            param.put("workingAge", values[randomIndex]);
        }
        /*当职业身份为B时必填 */
        if ("B".equals(job)) {
            /*营业执照信息  BBB:有营业执照 CCC:无营业执照*/
            values = new String[]{"BBB", "CCC"};
            randomIndex = random.nextInt(values.length);
            param.put("license", values[randomIndex]);
        }
        /*当职业身份为BS时必填 */
        if ("BS".equals(job)) {
            /*企业注册时长  RT1:1年以内 RT2:2-3年 RT3:3-5年 RT4:5年以上*/
           values = new String[]{"RT1", "RT2", "RT3", "RT4"};
            // 随机选择一个索引
            randomIndex = random.nextInt(values.length);
            // 获取随机选择的值
            param.put("registerTime", values[randomIndex]);
            /*企业纳税总金额 TAXES1:0元-5000元 TAXES2:5000元-10万元 TAXES3:10万元-100万元 TAXES4:100万元以上*/
            values = new String[]{"TAXES1", "TAXES2", "TAXES3", "TAXES4"};
            randomIndex = random.nextInt(values.length);
            param.put("taxes", values[randomIndex]);
            /* 企业开票月份数 INVOICING1:18个月以上 INVOICING2:12个月以上 INVOICING3:9个月以上 INVOICING4:9个月以下*/
            values = new String[]{"INVOICING1", "INVOICING2", "INVOICING3", "INVOICING4"};
            randomIndex = random.nextInt(values.length);
            param.put("invoicing", values[randomIndex]);
        }
 
        /*借款金额(借多少) I:3万-5万 J:5万-10万 K:10万-30万 M:30万-50万 N:50万-100万*/
        param.put("loan", checkValue(customer.getLoanAmount()));
        /*借款时间(借多久) L:3个月 O:6个月  P:12个月 Q:24个月 R:36个月*/
        values = new String[]{"L", "O", "P", "Q", "R"};
        randomIndex = random.nextInt(values.length);
        param.put("loanTime", values[randomIndex]);
        /*文化程度 S:小学 T:初中 U:高中 V:中专 W:专科 X:本科及以上*/
        String et = customer.getEducation();
        String education = "S";
        if ("01".equals(et)) {
            values = new String[]{"S", "T", "U", "V"};
            education = values[random.nextInt(values.length)];
        } else if ("02".equals(et)) {
            education = "W";
        } else{
            education = "X";
        }
        param.put("education", education);
 
 
        /**
         * 房产 GG:有房产,接受抵押
        HH:有房产,不接受抵押
        II:无房产
         无论选什么,均在"GG:有房产,接受抵押HH:有房产,不接受抵押"中随机匹配
         */
        values = new String[]{"GG", "HH"};
        param.put("estate",  values[random.nextInt(values.length)]);
        /**
         * 当房产为:GG,HH时必填
          房产类型 EEE:商品房 FFF:自建房
          随机生成"EEE:商品房 FFF:自建房"
         */
        values = new String[]{"EEE", "FFF"};
        param.put("estateType", values[random.nextInt(values.length)]);
       /* 车产
              JJ:有车,可接受抵押
              KK:有车,不接受抵押
              LL:无车产
              无论选什么,均在"JJ:有车,可接受抵押 KK:有车,不接受抵押"中随机匹配
        */
        values = new String[]{"JJ", "KK"};
        param.put("car", values[random.nextInt(values.length)]);
        /*当车产为:JJ,KK时必填
        车产类型 GGG:全款车 HHH:贷款车
        随机生成"GGG:全款车 HHH:贷款车"
        */
        values = new String[]{"GGG", "HHH"};
        param.put("carType", values[random.nextInt(values.length)]);
        /*当车产为:JJ,KK时必填
        车产估值 III:估值9万以上 JJJ:估值9万以下
        随机生成"III:估值9万以上 JJJ:估值9万以下"
        */
        values = new String[]{"III", "JJJ"};
        param.put("carAmount", values[random.nextInt(values.length)]);
        /*个人保险 NN:无保单 KKK:6个月及以下  LLL:6个月以上
        * "无论选什么,均在""KKK:6个月及以下LLL:6个月以上""中随机匹配"
        * */
        values = new String[]{"KKK", "LLL"};
        param.put("personalInsurance", values[random.nextInt(values.length)]);
        /*芝麻分 OO:600以下 PP:600-650 DDD:650-700 QQ:700以上 RR:无*/
        Integer customerSesame = customer.getSesame();
        int cus = Objects.isNull(customerSesame) ? 1 : customerSesame.intValue();
        String sesame = "PP";// 默认 1 无
        if (cus == 2) {
            sesame = "PP";
        } else if (cus == 3) {
            sesame = "DDD";
        } else if (cus == 4) {
            sesame = "QQ";
        }
        param.put("creditScore", sesame);
        /*微粒贷借款额度 UU:无 SS:5000以下 TT:5000以上*/
        values = new String[]{"SS", "TT"};
        param.put("wldLoan", values[random.nextInt(values.length)]);
 
        values = new String[]{"YY", "ZZ", "AAA"};
        /*信用记录 XX:无贷款记录 YY:信用良好,无逾期 ZZ:1年内逾期少于3次 AAA:1年内逾期超过3次*/
        //param.put("creditRecord", values[random.nextInt(values.length)]);
        param.put("creditRecord", "YY");
        /*京东白条 QQQ:无京东白条 OOO:5000及以下 PPP:5000以上*/
        values = new String[]{"OOO", "PPP"};
        param.put("jdWhite", values[random.nextInt(values.length)]);
        /* 花呗  TTT:无花呗 RRR:5000及以下 SSS:5000以上*/
        values = new String[]{"RRR", "SSS"};
        param.put("aliBei", values[random.nextInt(values.length)]);
 
        return param;
    }
 
    /**
     * 中诚易数据推送到好汇推操作
     */
    public boolean zcyPushToHht(Customer customer, String logNumber) {
        boolean isSucc = false;
        log.info("日志编号:" + logNumber + ",手机号:{},中诚易数据推送到好汇推流程开始", customer.getPhone());
        try {
            JSONObject param = getParam(customer);
 
            isSucc = push(customer, param, logNumber);
            Integer hht = 0;
            if (!isSucc) {
                log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据推送到好汇推失败", customer.getPhone());
            } else {
                hht = 1;
            }
            saveStatus(customer, hht);
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据推送到好汇推失败", customer.getPhone());
        }
        return isSucc;
    }
 
    /**
     * 我来贷数据推送到好汇推操作
     */
    public boolean wldPushToHht(Customer customer, String logNumber) {
        boolean isSucc = false;
        log.info("日志编号:" + logNumber + ",手机号:{},【我来贷】数据推送到好汇推流程开始", customer.getPhone());
        try {
            JSONObject param = getParam(customer);
 
            isSucc = push(customer, param, logNumber);
            Integer hht = 0;
            if (!isSucc) {
                log.error("日志编号:" + logNumber + ",手机号:{},【我来贷】数据推送到好汇推失败", customer.getPhone());
            } else {
                hht = 1;
            }
            saveStatus(customer, hht);
            if (isSucc) {
                isSucc = wldIncomeToHht(customer, param, logNumber);
            }
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + ",手机号:{},【我来贷】数据推送到好汇推失败:{}", customer.getPhone(), ex.getMessage());
            isSucc = false;
        }
        return isSucc;
    }
 
    /**
     * 我来贷进件数据给好汇推操作
     */
    public boolean wldIncomeToHht(Customer customer, JSONObject param, String logNumber) {
        boolean isSucc = false;
        log.info("日志编号:{},手机号:{},【我来贷】数据进件到好汇推流程开始", logNumber, customer.getPhone());
        try {
            Integer hht = 3;
            isSucc = getWldPushResult(logNumber, param, customer);
            if (!isSucc) {
                log.error("日志编号:{},手机号:{},【我来贷】数据进件到好汇推失败", logNumber, customer.getPhone());
            } else {
                hht = 4;
                log.info("日志编号:{},手机号:{},【我来贷】数据进件到好汇推成功", logNumber, customer.getPhone());
            }
            saveStatus(customer, hht);
        } catch (Exception ex) {
            log.error("日志编号:{},手机号:{},【我来贷】数据进件到好汇推失败: {}", logNumber, customer.getPhone(), ex.getMessage());
        }
        return isSucc;
    }
 
 
    public LvdiPushResultVo hhtPush(CustomerUser customerUser, String channelCode) {
        String logNumber = IdUtil.randomUUID();
        log.info("日志编号:" + logNumber + "好汇推 channelCode:" + channelCode + " 推送流程开始");
        Customer customer = customerMapper.getLatestCustomerRecord(customerUser.getPhone());
        CustomerCapitalResult capitalResult = capitalResultMapper.selectOne(new LambdaQueryWrapper<CustomerCapitalResult>()
                .eq(CustomerCapitalResult::getCustomerUserId, customerUser.getId())
                .eq(CustomerCapitalResult::getCustomerRecordId, customer.getId())
                .eq(CustomerCapitalResult::getCapitalInfoCode, CapitalInfoTypeCodeEnum.HHT.getCode()));
        if (capitalResult == null) {
            log.info("日志编号:" + logNumber + " 手机号:" + customerUser.getPhone() + " 好汇推数据库结果不存在, customerUser id:" +
                    customerUser.getId() + " customer id:" + customer.getId());
            throw new CommonException("资方对接结果不存在");
        }
 
        JSONObject param = getParam(customer);
 
        // 开始撞库
        boolean isSucc = push(customer, param, logNumber);
        if (!isSucc) {
            return null;
        }
 
        // 开始进件操作
        // 转成 LvdiPushResultVo
        LvdiPushResultVo result = new LvdiPushResultVo();
        result.setCheckResult(true);
        result.setUrlType("1");// APP下载链接
        return result;
    }
 
 
    /**
     * 撞库
     * @param customer
     * @param body
     * @param logNumber
     * @return
     */
    private boolean push(Customer customer, JSONObject body, String logNumber) {
        // 撞库签名参数
        String timestamp = String.valueOf(System.currentTimeMillis());
        JSONObject zkJsonObject = new JSONObject();
        String md5Phone = DigestUtils.md5DigestAsHex(customer.getPhone().getBytes()).toUpperCase();
        zkJsonObject.put("md5Phone", md5Phone);
        zkJsonObject.put("timestamp", timestamp);
 
        // 撞库签名
        body.put("sign", getSignStr(zkJsonObject));
        body.put("md5Phone", md5Phone);
        body.put("timestamp", timestamp);
        log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【好汇推】撞库请求的参数:{}", body);
 
        JSONObject jsonData = new JSONObject();
        jsonData.put("channelCode", channelCode);
        jsonData.put("version", version);
        // 撞库内容加密
        jsonData.put("content", encrypt(body.toJSONString()));
 
        String result = null;
        try {
            // 撞库
            result = HttpClientUtil.getInstance().postJsonData(zkUrl, jsonData.toJSONString());
            log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【好汇推】撞库返回参数:{}", result);
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【好汇推】撞库失败,传参:{} ex:{}", customer.getPhone(), jsonData, ex.getMessage());
        }
        try {
            HhtIncomeResponse res = JSON.parseObject(result, HhtIncomeResponse.class);
            if ("000000".equals(res.getHead().getReturnCode())) {
                log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【好汇推】推送成功");
                // 解析 返回的body
                String signsResult = JSON.toJSONString(res.getBody());
                log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【好汇推】推送成功: 返回的body转字符串: {}", signsResult);
                if (res.getBody().getResult()) {
                    PlatformCapital platformCapital = JSON.parseObject(signsResult, PlatformCapital.class);
                    // 删除同一资方的同一用户数据
                    LambdaQueryWrapper<PlatformCapital> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(PlatformCapital::getCustomerId, customer.getId());
                    wrapper.eq(PlatformCapital::getCapitalId, capitalId);
                    platformCapitalService.remove(wrapper);
                    // 录入到数据库
                    platformCapital.setCustomerId(customer.getId());
                    platformCapital.setCapitalId(capitalId);
                    platformCapital.setLogoUrl(res.getBody().getLogo());
                    platformCapitalService.save(platformCapital);
                    return true;
                }
            } else {
                log.error("日志编号:" + logNumber + " 手机号为:{},【好汇推】推送失败:返回参数:{},jsonData:{}", customer.getPhone(), res,jsonData);
            }
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【好汇推】推送原始返回参数转换失败,jsonData:{} ex:{}", customer.getPhone(), jsonData , ex.getMessage());
        }
        return false;
    }
 
    /**
     * 中诚易进件数据给好汇推操作
     */
    public void zcyIncomeToHht(Customer customer, String logNumber) {
        log.info("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到好汇推流程开始", customer.getPhone());
        try {
            Integer hht = 3;
            ResultJson<LvdiPushResultVo> rs = getPushResult(logNumber, customer);
            if (rs == null) {
                log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到好汇推失败", customer.getPhone());
            } else {
                hht = 4;
                log.info("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到好汇推成功", customer.getPhone());
            }
            saveStatus(customer, hht);
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到好汇推失败", customer.getPhone());
        }
    }
 
    private void saveStatus(Customer customer, Integer hht) {
        // 录入或更新到customer_scy_income表
        LambdaQueryWrapper<CustomerScyIncome> wr = new LambdaQueryWrapper<>();
        wr.eq(CustomerScyIncome::getCustomerZcyId, customer.getId());
        wr.last(" limit 1 ");
        CustomerScyIncome csi = customerZcyIncomeService.getOne(wr);
        if (Objects.isNull(csi)) {
            csi = new CustomerScyIncome();
        }
        csi.setCustomerZcyId(customer.getId());
        csi.setHht(hht);
        customerZcyIncomeService.saveOrUpdate(csi);
    }
    /**
     * 进件
     */
    public ResultJson<?> income(HttpServletRequest request) {
        String logNumber = IdUtil.randomUUID();
        log.info("日志编号:" + logNumber + " 【好汇推】进件流程开始");
        String token = request.getHeader("Authorization");
        UserDetail user = UserUtil.getUser(token);
        if (user == null) {
            log.info("日志编号:" + logNumber + " 好汇推进件失败,原因:用户Token无效");
            throw new CommonException("用户Token无效");
        }
 
 
        Customer customer = customerMapper.getLatestCustomerRecord(user.getPhone());
        LambdaQueryWrapper<CustomerUser> wr = new LambdaQueryWrapper<>();
        wr.eq(CustomerUser::getPhone, user.getPhone());
        wr.eq(CustomerUser::getDeleteFlag, 0);
        wr.last(" limit 1 ");
        CustomerUser customerUser = customerUserService.getOne(wr);
        if (customerUser == null) {
            log.info("日志编号:" + logNumber + " 手机号:" + user.getPhone() + " 好汇推进件失败,原因:用户不存在");
            throw new CommonException("用户不存在");
        }
        CustomerCapitalResult capitalResult = capitalResultMapper.selectOne(new LambdaQueryWrapper<CustomerCapitalResult>()
                .eq(CustomerCapitalResult::getCustomerUserId, customerUser.getId())
                .eq(CustomerCapitalResult::getCustomerRecordId, customer.getId())
                .eq(CustomerCapitalResult::getCapitalInfoCode, CapitalInfoTypeCodeEnum.HHT.getCode()));
        if (capitalResult == null) {
            log.info("日志编号:" + logNumber + " 手机号:" + customerUser.getPhone() + "进件失败,原因:【好汇推】数据库结果不存在, customerUser id:" +
                    customerUser.getId() + " customer id:" + customer.getId());
            throw new CommonException("资方对接结果不存在");
        }
        return getPushResult(logNumber, customer);
    }
 
    @Nullable
    private ResultJson<LvdiPushResultVo> getPushResult(String logNumber, Customer customer) {
        // 判断是否数据库中是否有数据,有过数据就不推送了
        LambdaQueryWrapper<PlatformCapital> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PlatformCapital::getCustomerId, customer.getId());
        wrapper.eq(PlatformCapital::getCapitalId, capitalId);
        wrapper.last(" limit 1 ");
        PlatformCapital platformCapital = platformCapitalService.getOne(wrapper);
        if (Objects.isNull(platformCapital)) {// 若没有数据
            log.info("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "进件失败,原因:【好汇推】推送结果不存在, customer id:" + customer.getId());
            throw new CommonException("资方推送结果不存在");
        }
        if (platformCapital.getIncomeStatus() == 1) {// 已进件成功
            log.info("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "进件失败,原因:【好汇推】已经进件成功过,不再进件, customer id:" + customer.getId());
            return null;
        }
        JSONObject param = getParam(customer);
        String phone = customer.getPhone();
 
        /*身份证号 等*/
        String idCardNo = customer.getIdCard();
        param.put("idCardNo", idCardNo);
 
        // 进件签名
        String timestamp = String.valueOf(System.currentTimeMillis());
        JSONObject orderJsonObject = new JSONObject();
        orderJsonObject.put("channelUserId", customer.getPhone());
        orderJsonObject.put("timestamp", timestamp);
        orderJsonObject.put("name", customer.getName());
        orderJsonObject.put("phone", customer.getPhone());
 
        param.put("sign", getSignStr(orderJsonObject));
        param.put("channelUserId", customer.getPhone());
        param.put("timestamp", timestamp);
        param.put("phone", customer.getPhone());
        String protoclUrl = StringUtils.replace(personalAuthorizationUrl, "id_str", platformCapital.getId() + "");
        param.put("personalAuthorizationUrl", protoclUrl);
 
        log.info("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "【好汇推】,进件参数:{}", param);
 
        // 进件内容加密
        JSONObject jsonData = new JSONObject();
        jsonData.put("content", encrypt(param.toJSONString()));
        jsonData.put("channelCode", channelCode);
        jsonData.put("version", version);
        log.info("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "开始进件给资方【好汇推】,参数:{}", jsonData);
        String result = null;
        try {
            // 进件
            result = HttpClientUtil.getInstance().postJsonData(jkUrl, jsonData.toJSONString());
            log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【好汇推】进件原始返回参数:{}", result);
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【好汇推】进件失败,传参:{} ex:{}", customer.getPhone(), jsonData, ex);
        }
        if (StringUtils.isBlank(result)) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【好汇推】进件返回数据为空,传参:{} ", customer.getPhone(), jsonData);
        }
        try {
            HhtIncomeResponse res = JSON.parseObject(result, HhtIncomeResponse.class);
            if ("000000".equals(res.getHead().getReturnCode())) {
                if (res.getHead().getResult()) {
                    log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【好汇推】进件成功");
                    // 更新数据库
                    platformCapital.setIncomeStatus(1);
                    platformCapitalService.updateById(platformCapital);
                    LvdiPushResultVo rs = new LvdiPushResultVo();
                    rs.setCheckResult(true);
                    rs.setUrlType("1");// APP下载链接
                    return ResultJson.ok(rs);
                }
 
            } else {
                log.error("日志编号:" + logNumber + " 手机号为:{},【好汇推】进件失败:{},jsonData:{}", customer.getPhone(), res.getHead().getReturnMessage(),jsonData);
            }
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【好汇推】进件原始返回参数转换失败,jsonData:{} ex:{}", customer.getPhone(), jsonData , ex);
        }
        return null;
    }
 
    private boolean getWldPushResult(String logNumber, JSONObject param, Customer customer) {
        // 判断是否数据库中是否有数据,有过数据就不推送了
        LambdaQueryWrapper<PlatformCapital> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PlatformCapital::getCustomerId, customer.getId());
        wrapper.eq(PlatformCapital::getCapitalId, capitalId);
        wrapper.last(" limit 1 ");
        PlatformCapital platformCapital = platformCapitalService.getOne(wrapper);
        if (Objects.isNull(platformCapital)) {// 若没有数据
            log.info("日志编号:{} 手机号:{}进件失败,原因:【好汇推】推送结果不存在, customer id: {}", logNumber, customer.getPhone(), customer.getId());
            return false;
        }
        if (platformCapital.getIncomeStatus() == 1) {// 已进件成功
            log.info("日志编号:{} 手机号:{}进件失败,原因:【好汇推】已经进件成功过,不再进件, customer id: {}", logNumber, customer.getPhone(),  customer.getId());
            return false;
        }
 
        /*身份证号 等*/
        String idCardNo = customer.getIdCard();
        param.put("idCardNo", idCardNo);
 
        // 进件签名
        String timestamp = String.valueOf(System.currentTimeMillis());
        JSONObject orderJsonObject = new JSONObject();
        orderJsonObject.put("channelUserId", customer.getPhone());
        orderJsonObject.put("timestamp", timestamp);
        orderJsonObject.put("name", customer.getName());
        orderJsonObject.put("phone", customer.getPhone());
 
        param.put("sign", getSignStr(orderJsonObject));
        param.put("channelUserId", customer.getPhone());
        param.put("timestamp", timestamp);
        param.put("phone", customer.getPhone());
        String protoclUrl = StringUtils.replace(personalAuthorizationUrl, "id_str", platformCapital.getId() + "");
        protoclUrl = StringUtils.replace(protoclUrl, "getProtocolInfo", "getProtocolInfoWld");
        param.put("personalAuthorizationUrl", protoclUrl);
 
        log.info("日志编号:{} 手机号:{}【好汇推】,进件参数:{}", logNumber, customer.getPhone(), param);
 
        // 进件内容加密
        JSONObject jsonData = new JSONObject();
        jsonData.put("content", encrypt(param.toJSONString()));
        jsonData.put("channelCode", channelCode);
        jsonData.put("version", version);
        log.info("日志编号:{} 手机号:{}开始进件给资方【好汇推】,参数:{}", logNumber, customer.getPhone(), jsonData);
        String result = null;
        try {
            // 进件
            result = HttpClientUtil.getInstance().postJsonData(jkUrl, jsonData.toJSONString());
            log.info("日志编号:{}, 手机号为:{},【好汇推】进件原始返回参数:{}", logNumber, customer.getPhone(), result);
        } catch (Exception ex) {
            log.error("日志编号:{}, 手机号为:{},【好汇推】进件失败,传参:{} ex:{}", logNumber, customer.getPhone(), jsonData, ex);
        }
        if (StringUtils.isBlank(result)) {
            log.error("日志编号:{}, 手机号为:{},【好汇推】进件返回数据为空,传参:{} ", logNumber, customer.getPhone(), jsonData);
        }
        try {
            HhtIncomeResponse res = JSON.parseObject(result, HhtIncomeResponse.class);
            if ("000000".equals(res.getHead().getReturnCode())) {
                if (res.getHead().getResult()) {
                    log.info("日志编号:{}, 手机号为:{},【好汇推】进件成功", logNumber, customer.getPhone());
                    // 更新数据库
                    platformCapital.setIncomeStatus(1);
                    platformCapitalService.updateById(platformCapital);
                    LvdiPushResultVo rs = new LvdiPushResultVo();
                    rs.setCheckResult(true);
                    rs.setUrlType("1");// APP下载链接
                    return true;
                }
            } else {
                log.error("日志编号:{}, 手机号为:{},【好汇推】进件失败:{},jsonData:{}", logNumber, customer.getPhone(), res.getHead().getReturnMessage(),jsonData);
            }
        } catch (Exception ex) {
            log.error("日志编号:{}, 手机号为:{},【好汇推】进件原始返回参数转换失败,jsonData:{} ex:{}", logNumber, customer.getPhone(), jsonData , ex.getMessage());
        }
        return false;
    }
    /**
     * 加密
     *
     * @param input  输入
     * @return {@code String}
     */
    private String encrypt(String input) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(aesKey.getBytes(CHARSET_NAME), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes(CHARSET_NAME));
        } catch (Exception e) {
            log.error("aes加密错误,原因是:", e);
        }
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(crypted);
    }
 
    public String decrypt(String input) {
        byte[] output = null;
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            SecretKeySpec skey = new SecretKeySpec(aesKey.getBytes(CHARSET_NAME), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(decoder.decode(input.getBytes(CHARSET_NAME)));
        } catch (Exception e) {
            log.error("aes解密错误,原因是:", e);
        }
        return new String(output);
    }
 
    public String getSignStr(JSONObject json) {
        String signContent = getSignContent(json);
        return SecureUtil.md5(signContent).toUpperCase();
    }
 
    /**
     * 1.第json的key 字典排序
     * 2.按排完序的key  获取对应的 value 拼接成字符串
     *
     * @param json
     * @return
     */
    public String getSignContent(JSONObject json) {
        Map<String, Object> map = new HashMap<>(json.size());
        json.forEach((s, v) -> {
            if (!"sign".equals(s)) {
                map.put(s, v);
            }
        });
        // 按值排序 升序
        Map<String, Object> sortMap = map
                .entrySet()
                .stream()
                .sorted(comparingByKey())
                .collect(
                        toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new));
        sortMap.put("secretKey", secretKey);
 
        StringBuilder sb = new StringBuilder();
        sortMap.forEach((key, value) -> {
            sb.append(key).append("=").append(value).append("&");
        });
        String result = sb.toString();
        if (result.length() > 2) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }
 
    // 我的测试
    public String test() {
        Long id = 1826907441992253441L;
        String idStr = id + "";
        String url = StringUtils.replace(personalAuthorizationUrl, "id_str", idStr);
        return url;
    }
}