Sunshine
2024-11-04 919ed870ea1def0cfdd1dff23bec204975e7f34c
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
package com.nova.sankuai.infra.utils.syh;
 
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.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nova.sankuai.domain.api.hjqb.HjqbResponse;
import com.nova.sankuai.domain.api.syh.SyhCallback;
import com.nova.sankuai.domain.api.syh.SyhData;
import com.nova.sankuai.domain.api.syh.SyhIncomeResponse;
import com.nova.sankuai.domain.api.syh.SyhResponse;
import com.nova.sankuai.domain.dto.callback.syh.SyhCallbackRequestDTO;
import com.nova.sankuai.domain.entity.*;
import com.nova.sankuai.domain.enums.capitalInfo.CapitalInfoStatusEnum;
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.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.NotNull;
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.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Objects;
import java.util.Random;
 
/**
 * 随易花对接
 */
@Component
@RequiredArgsConstructor
public class SyhUtil {
 
    private static final Logger log = LoggerFactory.getLogger("capitalLogger");
 
    private static final String encryptKey = "MCXBIjANke";
    // 随易花在capital_info数据库中的ID
    private static final Long capitalId = 36L;
 
    @Value("${syh.callBackUrl}")
    private String callBackUrl;
 
    @Value("${syh.domain}")
    private String syhUrl;
 
    @Value("${syh.source}")
    private String source;
 
    /**
     * 获取工作年限 1: 6个月以下; 2 :6-12个月; 3 : 12 个月
     */
    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();
        }
 
//        LocalDate now = LocalDate.now();
//        LocalDate dateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
 
        long month = ChronoUnit.MONTHS.between(startDate, endDate);
 
        // 1: 6个月以下; 2 :6-12个月; 3 : 12 个月
        if (month < 6) {
            return "1";
        } else if (month >= 6 && month < 12) {
            return "2";
        }
 
        return "3";
    }
 
 
    private final CustomerMapper customerMapper;
    private final CustomerCapitalResultMapper capitalResultMapper;
    private final ICustomerUserService customerUserService;
    private final CustomerCapitalResultMapper customerCapitalResultMapper;
    private final IChannelInfoService channelInfoService;
 
    public SyhResponse callback(SyhCallbackRequestDTO body) {
        String logNumber = IdUtil.randomUUID();
        try {
            if (body == null) {
                SyhResponse resp = new SyhResponse();
                resp.setResult(400);
                resp.setMessage("请求体为空");
                log.error("日志编号:{} 随易花资方回调请求体为空", logNumber);
                return resp;
            }
            String timestamp = body.getTimestamp();
            String signs = body.getSigns();
            if (StringUtils.isBlank(timestamp) || StringUtils.isBlank(signs)) {
                SyhResponse resp = new SyhResponse();
                resp.setResult(400);
                resp.setMessage("请求体为空");
                log.error("日志编号:{} 随易花资方回调请求体为空", logNumber);
                return resp;
            }
 
            String signsRes = decrypt(timestamp, signs);// 解密
            if (StringUtils.isBlank(signsRes)) {
                SyhResponse resp = new SyhResponse();
                resp.setResult(400);
                resp.setMessage("请求体signs解析失败!");
                log.error("日志编号:{} 随易花回调请求体signs解析失败,timestamp:{},signs:{}", logNumber, timestamp, signs);
                return resp;
            }
 
            SyhCallback callback = JSON.parseObject(signsRes, SyhCallback.class);
            String mobile = callback.getPhone();
            if (StringUtils.isBlank(mobile)) {// 手机号为空
                SyhResponse resp = new SyhResponse();
                resp.setResult(400);
                resp.setMessage("手机号不能为空");
                log.error("日志编号:{} 随易花资方回调返回手机号为空,timestamp:{},signs:{}", logNumber, timestamp, signs);
                return resp;
            }
            Customer customer = customerMapper.getLatestCustomerRecord(mobile);
            CustomerUser customerUser = customerUserService.getOne(new LambdaQueryWrapper<CustomerUser>().eq(CustomerUser::getPhone, mobile));
            if (customer == null || customerUser == null) {
                SyhResponse resp = new SyhResponse();
                resp.setResult(500);
                resp.setMessage("该用户已注销");
                log.error("日志编号:{} 随易花资方返回的用户已注销,timestamp:{},signs:{}", logNumber, timestamp, signs);
                return resp;
            }
            LambdaQueryWrapper<CustomerCapitalResult> wr = new LambdaQueryWrapper<>();
            wr.eq(CustomerCapitalResult::getCustomerUserId, customerUser.getId())
                    .eq(CustomerCapitalResult::getCustomerRecordId, customer.getId())
                    .eq(CustomerCapitalResult::getCapitalInfoCode, CapitalInfoTypeCodeEnum.SYH.getCode())
                    .last(" limit 1 ");
 
            CustomerCapitalResult capitalResult = customerCapitalResultMapper.selectOne(wr);
            if (capitalResult == null) {
                SyhResponse resp = new SyhResponse();
                resp.setResult(500);
                resp.setMessage("该数据不存在");
                log.error("日志编号:{} 随易花资方回调返回的用户不存在,timestamp:{},signs:{}", logNumber, timestamp, signs);
                return resp;
            }
            Integer status = CapitalInfoStatusEnum.APPLY_PASS.getCode();
 
            LambdaUpdateWrapper<CustomerCapitalResult> updateWrapper = Wrappers.lambdaUpdate(CustomerCapitalResult.class);
            updateWrapper.eq(CustomerCapitalResult::getId, capitalResult.getId()).
                    set(CustomerCapitalResult::getStatus, status);
            customerCapitalResultMapper.update(null, updateWrapper);
 
            SyhResponse resp = new SyhResponse();
            resp.setResult(200);
            resp.setMessage("成功接收数据");
            log.info("日志编号:{} 随易花资方回调返回数据入库成功:{}", logNumber, body);
            return resp;
        } catch (Exception e) {
            SyhResponse resp = new SyhResponse();
            resp.setResult(500);
            resp.setMessage(e.getMessage());
            log.error("日志编号:{} 随易花资方回调返回数据入库失败:{} 错误原因:{}", logNumber, body, e);
            return resp;
        }
    }
 
    private JSONObject getParam(Customer customer) {
 
        JSONObject param = new JSONObject();
        Random random = new Random();
        // 获取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();
        }
 
        /**
         * 参数名称    参数类型    是否必须    参数示例    参数说明
         * timestamp    string    是    1717724899024    时间戳字符串
         * signs    string    是    01f32b38b7b208a574c512a40d30cff0    业务数据AES加密内容
         *     signs字段加密前的内容,转成jsonstr进行加密,主体使用的
         * String key = String.format("%s%s", "MCXBIjANke", timestamp).substring(0, 16);
         * String signs= SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).encryptHex(value);
         */
        /* mobile    String    是    17711223344    手机号*/
        String phone = customer.getPhone();
        param.put("mobile", phone);
        /* name    string    是    测试    姓名 */
        param.put("name", customer.getName());
        /* city    string    是    上海    城市  不带"市" */
        String city = customer.getCityName();
        param.put("city", StringUtils.isNotBlank(city) ? city.replace("市", "") : "");
 
        /* nativePlace    string    否    1    是否本地户籍,0:非本地户籍、1:本地户籍 */
        param.put("nativePlace", "1");
        /* limitScope    int    是    50000    额度范围(1:''0-3万'' ;2:''3万-5万'' ;3: ''5万-10万''  ;4: ''10万-20万'' ; 5: ''20万-50万'' ;6:''50万以上''   )(额度大于 3w)*/
        /*Double la = customer.getLoanAmount();
        double loanAmount = 0;
        loanAmount = la == null ? 0 : la.doubleValue();
        int limitScope = 2;
        if (loanAmount >= 0 && loanAmount < 50000) {
            limitScope = 3;
        } else if (loanAmount >= 50000 && loanAmount < 100000) {
            limitScope = 4;
        } else if (loanAmount >= 200000 && loanAmount < 500000) {
            limitScope = 5;
        } else {
            limitScope = 6;
        }*/
 
        int[] values = {2, 3, 3, 4, 5, 6};
        param.put("limitScope", values[random.nextInt(values.length)]);
 
        int car = 1;
        int house = 1;
        int soci = 1;
        int accu = 1;
        String hasPolicy = "1";
        int creditCard = 1;
 
        if (version2Type == 1) { //线上放款
            /* car    无论选什么,均在"2.全款 3.按揭"中随机匹配 */
            values = new int[]{2, 3};
            car = values[random.nextInt(values.length)];
 
            /* house 无论选什么,均在"5:有本地房产 6:有外地房产 50:都有"中随机匹配*/
            values = new int[]{5, 6, 50};
            house = values[random.nextInt(values.length)];
 
            /* 公积金 无论选什么 均在"2.6个月以下 3.6个月以上"中随机匹配*/
            values = new int[]{2, 3};
            accu = values[random.nextInt(values.length)];
 
            /* 社保 无论选什么 均在"2.6个月以下 3.6个月以上"中随机匹配*/
            soci = values[random.nextInt(values.length)];
 
            /* 保单 无论选什么 均在"2.缴纳未满一年 3.缴纳一年以上"中随机匹配*/
            hasPolicy = String.valueOf(values[random.nextInt(values.length)]);
 
            /* 信用卡额度 随机生成2:1万以下 3:1万-3万 4:3万以上*/
            values = new int[]{2, 3, 4};
            creditCard = values[random.nextInt(values.length)];
        } else { //银行直贷
            /* car    int    否    1    车产类型 (1无 2全款 3按揭) */
            Integer carStatus = customer.getCarStatus();
            int cs = Objects.isNull(carStatus) ? 0 : carStatus.intValue();
            if (cs == 4) {// 有按揭车
                car = 3;
            } else if (cs == 5) {// 全款车
                car = 2;
            }
 
            /* house    int    否    1    1:无房产 5:有本地房产 6:有外地房产 50:都有 备注:我们只有是否有房产*/
            /**
             * {
             *     text: '有按揭商品房',
             *     value: 4,
             *   },
             *   {
             *     text: '有全款商品房',
             *     value: 5,
             *   },
             *   {
             *     text: '仅外地有房',
             *     value: 6,
             *   },
             *   {
             *     text: '无',
             *     value: 0,
             *   },
             */
            Integer houseStatus = customer.getHouseStatus();
            int hs = Objects.isNull(houseStatus) ? 0 : houseStatus.intValue();
            if (hs == 3) {
                house = 5;
            } else if (hs == 6) {
                house = 6;
            } else if (hs == 4 || hs == 5) {
                house = 5;
            }
 
 
            /* accumulation    int    否    1    公积金(1:无公积金 2:6个月以下 3:6个月以上)*/
            /**
             * {
             *     text: '无',
             *     value: 0,
             *   },
             *   {
             *     text: '6个月以内',
             *     value: 1,
             *   },
             *   {
             *     text: '6个月以上',
             *     value: 2,
             *   },
             */
            Integer accumulation = customer.getProvidentFund();
            int at = Objects.isNull(accumulation) ? 0 : accumulation.intValue();
            if (at == 1) accu = 2;
            else if (at == 2) accu = 3;
 
            /* social    int    否    1    社保(1:无社保 2:6个月以下 3:6个月以上)*/
            /**
             * {
             *     text: '无',
             *     value: 0,
             *   },
             *   {
             *     text: '6个月以内',
             *     value: 1,
             *   },
             *   {
             *     text: '6个月以上',
             *     value: 2,
             *   },
             */
            Integer social = customer.getSocialSecurity();
            int soc = Objects.isNull(social) ? 0 : social.intValue();
            if (soc == 1) {
                soci = 2;
            } else if (soc == 2) {
                soci = 3;
            }
            /* hasPolicy    string    否    1    保单 1:无 2:缴纳未满一年 3:缴纳一年以上*/
            /**
             * {
             *     text: '投保人寿险且保两年以下',
             *     value: 6,
             *   },
             *   {
             *     text: '投保人寿险且保两年以上',
             *     value: 7,
             *   },
             *   {
             *     text: '无保险',
             *     value: 0,
             *   },
             */
            Integer insurancePolicy = customer.getInsurancePolicy();
            int ipy = Objects.isNull(insurancePolicy) ? 0 : insurancePolicy.intValue();
            if (ipy == 6) {
                hasPolicy = "2";
            } else if (ipy == 7) {
                hasPolicy = "3";
            }
 
            /* creditCard    int    否    1    信用卡额度 1:无 2:1万以下 3:1万-3万 4:3万以上*/
            /**
             * {
             *     text: '1万',
             *     value: 3,
             *   },
             *   {
             *     text: '1万-3万',
             *     value: 4,
             *   },
             *   {
             *     text: '3万以上',
             *     value: 5,
             *   },
             *   {
             *     text: '无',
             *     value: 0,
             *   },
             */
            Integer cc = customer.getCreditCard();
            int ccV = Objects.isNull(cc) ? 0 : cc.intValue();
 
            if (ccV == 3) {
                creditCard = 2;
            } else if (ccV == 4) {
                creditCard = 3;
            } else if (ccV == 5) {
                creditCard = 4;
            }
        }
        param.put("car", car);
        param.put("house", house);
        param.put("accumulation", accu);
        param.put("social", soci);
        param.put("hasPolicy", hasPolicy);
        param.put("creditCard", creditCard);
 
 
        /* sex    int    是    1    性别 1-男 2-女 */
        String sex = RbUtil.getGenderByIDCard(customer.getIdCard());
        String sexStr = "男".equals(sex) ? "1" : "2";
        param.put("sex", sexStr);
 
        /* age    String    是    25    年龄(25-55之间)*/
        param.put("age", RbUtil.calculateAgeFromIdNumber(customer.getIdCard()));
 
        /* osType    String    是    1    设备标识(0 安卓 1苹果) */
        String os = customer.getOs();
        String osType = "ios".equals(os) ? "1" : "0";
        param.put("osType", osType);
 
        /* deviceId    String    是    1dfghh    设备id,可传空字符串 */
//        param.put("deviceId", StringUtils.defaultString(customer.getDeviceId()));
        param.put("deviceId", "");
        /* ip    string    是    127.0.0.1    用户ip */
        param.put("ip", !StringUtils.isEmpty(customer.getClientIp()) ? customer.getClientIp() : "127.0.0.1");
        /* ipCity    string    否    上海    记录ip城市
         * chooseCity    string    否    上海    记录手选城市
         * gpsCity    string    否    上海    录gps城市
         * phoneCity    string    否    上海    记录手机归属地城市
         * 以上四个不搞
         */
        /* sesame    string    是    4    芝麻分 1:无芝麻分 4:700分以上 5:650分以下 6:650-700分*/
        Integer customerSesame = customer.getSesame();
        int cus = Objects.isNull(customerSesame) ? 1 : customerSesame.intValue();
        String sesame = "1";// 默认 1 无
        if (cus == 2) {
            sesame = "5";
        } else if (cus == 3) {
            sesame = "6";
        } else if (cus == 4) {
            sesame = "4";
        }
        param.put("sesame", sesame);
 
        /* carPay    int    否    1    车产价值  1:0-6万;2:6-15万; 3:15-20万 这个不搞 */
        /* job    String    否    1    职位: 1 上班族 2自由职业 3 企业主 */
        /*
        {
    text: '上班族',
    value: 0,
  },
  {
    text: '自由职业',
    value: 1,
  },
  {
    text: '企业主',
    value: 2,
  },
  {
    text: '个体户',
    value: 3,
  },
  {
    text: '公务员',
    value: 4,
  },
  job    String    是    1 上班族 2自由职业 3 企业主 4.公务员/事业/国企 这个是以前的
         */
        Integer pi = customer.getProfessionInfo();
        int professionInfo = 1;// 默认自由职业
        int job = 0;
        if (!Objects.isNull(pi)) {
            professionInfo = pi.intValue();
        }
        if (professionInfo == 0) {
            job = 1;
        } else if (professionInfo == 1) {
            job = 2;
        } else if (professionInfo == 2 || professionInfo == 3) {
            job = 3;
        } else if (professionInfo == 4) {
            values = new int[]{1, 2, 3};
            job = values[random.nextInt(values.length)];
        }
        param.put("job", String.valueOf(job));
 
        /* jobAge    String    否    1    工作年限    1: 6个月以下; 2 :6-12个月; 3 : 12 个月 */
       /* String workStartTime = customer.getWorkStartTime();
        String workEndTime = customer.getWorkEndTime();
        String jobAage = getJobAage(workStartTime, workEndTime);*/
        values = new int[]{1, 2, 3};
        param.put("jobAage", String.valueOf(values[random.nextInt(values.length)]));
 
        param.put("moneyType", String.valueOf(values[random.nextInt(values.length)]));
 
        /* moneyType    String    否    1    工资发放形式  1: 银行转账 ;2:银行代发 ; 3:现金发放 这个不搞 */
 
        /* monthlyIncomeLevel    int    否    1    月收入区间(1: 5000以下;2: 5001-10000;3: 10001-15000;4: 15001-20000;5: 25001-30000;6: 30000元以上)*/
 
        /**
         * INCOME_3Q_UNDER(0, "3000以下"), 1
         * *     Income_5Q_UNDER(6, "5000元以下"), 1
         * Income_6(5, "未知"), 1
         *
         *     Income_3Q_6Q(1, "3000-6000"), 2
         *     Income_6Q_1W(2, "6000-10000"), 2
         *     Income_5Q_1W(7, "5000 - 10000元"), 2
         *     Income_1W_UNDER(13, "10000以下"); 2
         *
         *     Income_1W_1W5(8, "10001 - 15000元"), 3
         *
         *
         *     Income_1W_3W(3, "10000-30000"), 4
         *     Income_1W5_2W(9, "15001 - 20000元"), 4
         *
         *
         *     Income_2W_2W5(10, "20001 - 25000元"), 5
         *     Income_2W5_3W(11, "25001 - 30000元"), 5
         *
         *
         *     Income_3W_UPPER_1(12, "30000元以上"), 6
         *     Income_3W_UPPER(4, "30000以上"), 6
         *
         */
        Integer monthlyIncome = customer.getMonthlyIncome();
        int mi = monthlyIncome == null ? 1 : monthlyIncome.intValue();
        int monthlyIncomeLevel = 1;
        /* if (mi == 0 || mi == 6 || mi == 5) {
            monthlyIncomeLevel = 1;
        } else if (mi == 1 || mi == 2 || mi == 7 || mi == 13) {
            monthlyIncomeLevel = 2;
        } else if (mi == 8) {
            monthlyIncomeLevel = 3;
        } else if (mi == 3 || mi == 9) {
            monthlyIncomeLevel = 4;
        } else if (mi == 10 || mi == 11) {
            monthlyIncomeLevel = 5;
        } else if (mi == 12 || mi == 4) {
            monthlyIncomeLevel = 6;
        }*/
        if (mi == 13) {
            values = new int[]{1, 2};
            monthlyIncomeLevel = values[random.nextInt(values.length)];
        } else if (mi == 3) {
            values = new int[]{3, 4, 6};
            monthlyIncomeLevel = values[random.nextInt(values.length)];
        } else if (mi == 4) {
            monthlyIncomeLevel = 6;
        }
        param.put("monthlyIncomeLevel", monthlyIncomeLevel);
 
        /* companyAge    String    否    1    企业年限 1: 1年以下 ;2:1-3年 ; 3:3年以上 这个不搞*/
        values = new int[]{1, 2, 3};
        param.put("companyAge", values[random.nextInt(values.length)]);
 
        /* jdIous    string    否    1    京东白条(短信流)  1:无  2:有
         * jdIousRp    string    否    1     京东白条(落地页) 1:无 2:0-5000 3:5000以上
         * 以上两个不搞
         */
        param.put("jdIous", 2);
        values = new int[]{2, 3};
        param.put("jdIousRp", values[random.nextInt(values.length)]);
        /* spendBai    string    否    1    花呗 1:无 2:3000以下 3:3000---1万 4:一万以上 这个不搞 */
        values = new int[]{2, 3, 4};
        param.put("spendBai", values[random.nextInt(values.length)]);
 
        /* credit    int    否    1    信用情况 1:信用良好 无逾期 2:1年内逾期少于3次 3:1年内逾期大于3次 这个不搞 */
        values = new int[]{1, 2, 3};
        param.put("spendBai", values[random.nextInt(values.length)]);
 
        /* education    string    否    1    学历 1:高中及以下 2:专科 3:本科 4:硕士 5:博士及以上*/
         /* education    String    是    学历 1:高中及以下 2:专科 3:本科 4:硕士 5:博士及以上
        PRIMARY_SCHOOL("01", "小学"),
    JUNIOR_HIGH_SCHOOL("02", "初中"),
    HIGH_SCHOOL("03", "高中"),
    COLLEGE_DEGREE("04", "大专"),
    BACHELOR_DEGREE("05", "本科"),
    MASTER_CANDIDATE("06", "研究生"),
    DOCTORAL_CANDIDATE("07", "博士"),
         */
        String et = customer.getEducation();
        String education = "1";
        if ("01".equals(et) || "02".equals(et) || "03".equals(et)) {
            education = "1";
        } else if ("04".equals(et)) {
            education = "2";
        } else if ("05".equals(et)) {
            education = "3";
        } else if ("06".equals(et)) {
            education = "4";
        } else if ("07".equals(et)) {
            education = "5";
        }
        param.put("education", education);
 
        /* source    string    是    TL    品牌来源*/
        param.put("source", source);
 
        /* system    String    是    H5-ORDER    系统来源val3*/
        param.put("system", source);
 
        /* channelMark    String    是    H5-ORDER    渠道标识val2*/
        param.put("channelMark", source);
 
        /* appName    String    是    H5-ORDER    app名称 sourceName  val4 */
        param.put("appName", source);
        return param;
    }
 
    /**
     * 中诚易数据推送到随容花操作
     */
    public boolean zcyPushToSyh(Customer customer, String logNumber) {
        boolean isSucc = false;
        log.info("日志编号:" + logNumber + ",手机号:{},中诚易数据推送到随易花流程开始", customer.getPhone());
        try {
            JSONObject param = getParam(customer);
 
            isSucc = push(customer, param, logNumber);
            Integer syh = 0;
            if (!isSucc) {
                log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据推送到随易花失败", customer.getPhone());
            } else {
                syh = 1;
            }
            saveStatus(customer, syh);
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据推送到随易花失败:", customer.getPhone(), ex);
        }
        return isSucc;
    }
 
    /**
     * 我来贷数据推送到随容花操作
     */
    public boolean wldPushToSyh(Customer customer, String logNumber) {
        boolean isSucc = false;
        log.info("日志编号:{},手机号:{},【我来贷】数据推送到随易花流程开始", logNumber, customer.getPhone());
        try {
            JSONObject param = getParam(customer);
 
            isSucc = push(customer, param, logNumber);
            Integer syh = 0;
            if (!isSucc) {
                log.error("日志编号:{},手机号:{},【我来贷】数据推送到随易花失败", logNumber, customer.getPhone());
            } else {
                syh = 1;
            }
            saveStatus(customer, syh);
            if (isSucc) {
                isSucc = wldIncomeToSyh(customer, param, logNumber);
            }
        } catch (Exception ex) {
            log.error("日志编号:{},手机号:{},【我来贷】数据推送到随易花失败:{}", logNumber, customer.getPhone(), ex.getMessage());
            isSucc = false;
        }
        return isSucc;
    }
 
    /**
     * 推送操作
     */
    public LvdiPushResultVo syhPush(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.SYH.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();
//        SyhIncomeResponse response = income(customer, platformCapital, logNumber);
        result.setCheckResult(true);
        result.setUrlType("1");// APP下载链接
//        result.setUrl(Objects.isNull(data) ? null : data.getApplyUrl());
        return result;
    }
 
    private final IPlatformCapitalService platformCapitalService;
    private final ICustomerScyIncomeService customerZcyIncomeService;
 
    private boolean push(Customer customer, JSONObject body, String logNumber) {
        // 转参
        String timestamp = String.valueOf(System.currentTimeMillis());
        String key = getKey(timestamp);
        String signs = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).encryptHex(body.toJSONString().getBytes(StandardCharsets.UTF_8));
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("signs", signs);
        log.info("日志编号:" + logNumber + " 开始推送手机号:" + customer.getPhone() + "的资料给资方【随易花】");
        String result = null;
        String url = syhUrl + "/goodsKey/bs/queryGoodsKey";
        try {
            result = HttpClientUtil.getInstance().postJsonData(url, jsonData.toJSONString());
            log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【随易花】推送原始返回参数:{}", result);
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【随易花】推送失败,传参:{} ex:{}", customer.getPhone(), jsonData, ex.getMessage());
        }
        if (StringUtils.isBlank(result)) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【随易花】推送原始返回数据为空,传参:{} ", customer.getPhone(), jsonData);
        }
        try {
            SyhResponse res = JSON.parseObject(result, SyhResponse.class);
            if (res.getResult().intValue() == 200) {
                log.info("日志编号:" + logNumber + " 手机号为:" + customer.getPhone() + ",【随易花】推送成功");
                // 解析 返回的signs
                SyhData data = res.getData();
                String timestampRes = data.getTimestamp();
                String signsRes = data.getSigns();
                if (StringUtils.isBlank(signsRes)) {
                    log.error("日志编号:" + logNumber + " 手机号为:{},【随易花】推送原始返回参数signs为空,jsonData:{}", customer.getPhone(), jsonData);
                    return false;
                }
                String signsResult = decrypt(timestampRes, signsRes);// 解密
                if (StringUtils.isBlank(signsResult)) {
                    log.error("日志编号:" + logNumber + " 手机号为:{},【随易花】推送原始返回参数signs解密失败,jsonData:{}", customer.getPhone(), jsonData);
                    return false;
                }
                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);
                platformCapitalService.save(platformCapital);
 
                return true;
            } else {
                log.error("日志编号:" + logNumber + " 手机号为:{},【随易花】推送失败:{},jsonData:{}", customer.getPhone(), res.getMessage(), jsonData);
            }
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【随易花】推送原始返回参数转换失败,jsonData:{} ex:{}", customer.getPhone(), jsonData, ex.getMessage());
        }
        return false;
    }
 
    /**
     * 中诚易进件数据给随易花操作
     */
    public void zcyIncomeToSyh(Customer customer, String logNumber) {
        log.info("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到随易花流程开始", customer.getPhone());
        try {
            Integer syh = 3;
            ResultJson<LvdiPushResultVo> rs = getPushResult(logNumber, customer);
            if (rs == null) {
                log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到随易花失败", customer.getPhone());
            } else {
                syh = 4;
                log.info("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到随易花成功", customer.getPhone());
            }
            saveStatus(customer, syh);
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + ",手机号:{},中诚易数据进件到随易花失败", customer.getPhone());
        }
    }
    /**
     * 我来贷进件数据给随易花操作
     */
    public boolean wldIncomeToSyh(Customer customer, JSONObject param, String logNumber) {
        boolean isSucc = false;
        log.info("日志编号:{},手机号:{},【我来贷】数据进件到随易花流程开始", logNumber, customer.getPhone());
        try {
            Integer syh = 3;
            isSucc = getWldPushResult(logNumber, param, customer);
            if (!isSucc) {
                log.error("日志编号:{},手机号:{},【我来贷】数据进件到随易花失败", logNumber, customer.getPhone());
            } else {
                syh = 4;
                log.info("日志编号:{},手机号:{},【我来贷】数据进件到随易花成功", logNumber, customer.getPhone());
            }
            saveStatus(customer, syh);
        } catch (Exception ex) {
            log.error("日志编号:{},手机号:{},【我来贷】数据进件到随易花失败: {}", logNumber, customer.getPhone(), ex.getMessage());
        }
        return isSucc;
    }
 
    private void saveStatus(Customer customer, Integer syh) {
        // 录入或更新到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.setSyh(syh);
        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.SYH.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;
        }
        /**
         * uuid    string    是    1587992123923271680    数据记录uuid
         * type    string    是    api    数据业务类型
         * productKey    string    是    YiUl10zCu    产品key
         */
        JSONObject param = new JSONObject();
        param.put("uuid", platformCapital.getUuid());
        param.put("type", platformCapital.getType());
        param.put("productKey", platformCapital.getProductKey());
        param.put("url", callBackUrl);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String key = getKey(timestamp);
        String signs = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).encryptHex(param.toJSONString().getBytes(StandardCharsets.UTF_8));
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("signs", signs);
//        jsonData.put("url", callBackUrl);
        log.info("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "开始进件给资方【随易花】,参数:{}", jsonData);
        String result = null;
        String url = syhUrl + "/goodsKey/bs/incoming";
        try {
            result = HttpClientUtil.getInstance().postJsonData(url, 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 {
            SyhIncomeResponse res = JSON.parseObject(result, SyhIncomeResponse.class);
            if (res.getResult().intValue() == 200) {
                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.getMessage(), 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("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "进件失败,原因:随易花推送结果不存在, customer id:" + customer.getId());
            return false;
        }
        if (platformCapital.getIncomeStatus() == 1) {// 已进件成功
            log.info("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "进件失败,原因:随易花已经进件成功过,不再进件, customer id:" + customer.getId());
            return false;
        }
        /**
         * uuid    string    是    1587992123923271680    数据记录uuid
         * type    string    是    api    数据业务类型
         * productKey    string    是    YiUl10zCu    产品key
         */
        param.put("uuid", platformCapital.getUuid());
        param.put("type", platformCapital.getType());
        param.put("productKey", platformCapital.getProductKey());
        param.put("url", callBackUrl);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String key = getKey(timestamp);
        String signs = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).encryptHex(param.toJSONString().getBytes(StandardCharsets.UTF_8));
        JSONObject jsonData = new JSONObject();
        jsonData.put("timestamp", timestamp);
        jsonData.put("signs", signs);
        log.info("日志编号:" + logNumber + " 手机号:" + customer.getPhone() + "开始进件给资方【随易花】,参数:{}", jsonData);
        String result = null;
        String url = syhUrl + "/goodsKey/bs/incoming";
        try {
            result = HttpClientUtil.getInstance().postJsonData(url, 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 {
            SyhIncomeResponse res = JSON.parseObject(result, SyhIncomeResponse.class);
            if (res.getResult().intValue() == 200) {
                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("日志编号:" + logNumber + " 手机号为:{},【随易花】进件失败:{},jsonData:{}", customer.getPhone(), res.getMessage(), jsonData);
            }
        } catch (Exception ex) {
            log.error("日志编号:" + logNumber + " 手机号为:{},【随易花】进件原始返回参数转换失败,jsonData:{} ex:{}", customer.getPhone(), jsonData, ex);
        }
        return false;
    }
 
    @NotNull
    private String getKey(String timestamp) {
        return String.format("%s%s", encryptKey, timestamp).substring(0, 16);
    }
 
    /**
     * 解密
     *
     * @param
     * @param encrypted
     * @return
     */
    public String decrypt(String timestamp, String encrypted) {
        String key = String.format("%s%s", encryptKey, timestamp).substring(0, 16);
        String str = null;
        try {
            str = SecureUtil.aes(key.getBytes("UTF-8")).decryptStr(encrypted);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }
 
}