Sunshine
2024-11-05 8f7985d7764a0aad24bd593ac5ea47b7fc290961
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
package com.nova.sankuai.service.impl;
 
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nova.sankuai.domain.dto.*;
import com.nova.sankuai.domain.entity.ChannelInfo;
import com.nova.sankuai.domain.entity.ChannelLog;
import com.nova.sankuai.domain.entity.Customer;
import com.nova.sankuai.domain.entity.CustomerUser;
import com.nova.sankuai.domain.enums.SourceTypeEnum;
import com.nova.sankuai.domain.vo.*;
import com.nova.sankuai.domain.vo.channel.ChannelExportReportVo;
import com.nova.sankuai.domain.vo.channel.ChannelImportReportVo;
import com.nova.sankuai.domain.vo.channel.ChannelReportTotalVo;
import com.nova.sankuai.infra.config.CommonException;
import com.nova.sankuai.infra.mapper.*;
import com.nova.sankuai.infra.utils.PageRequest;
import com.nova.sankuai.infra.utils.PageUtil;
import com.nova.sankuai.security.UserDetail;
import com.nova.sankuai.service.CostConfigService;
import com.nova.sankuai.service.IChannelInfoService;
import com.nova.sankuai.service.IChannelLogService;
import com.nova.sankuai.service.ICustomerUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author weikangdi
 */
@Service
@AllArgsConstructor
@Slf4j
public class ChannelLogServiceImpl extends ServiceImpl<ChannelLogMapper, ChannelLog> implements IChannelLogService {
 
    private final ChannelLogMapper channelLogMapper;
 
    private final PageUtil pageUtil;
 
    private final IChannelInfoService channelInfoService;
 
    private final CustomerMapper customerMapper;
 
    private final SysUserMapper sysUserMapper;
 
    private final ICustomerUserService customerUserService;
 
    private final LoanSupermarketMapper loanSupermarketMapper;
 
    private final ChannelInfoMapper channelInfoMapper;
 
    private final CostConfigService costConfigService;
 
    @Override
    public void createImportLog(Integer source, Integer status, Long customerId, String importObjects) {
        ChannelInfo channelInfo = channelInfoService.lambdaQuery().eq(ChannelInfo::getCode, source).one();
        ChannelLog channelLog = new ChannelLog();
        channelLog.setSource(source);
        channelLog.setName(channelInfo.getName());
        channelLog.setType(ChannelLog.IMPORT);
        channelLog.setStatus(status);
        channelLog.setCustomerRecordId(customerId);
        channelLog.setImportObjects(importObjects);
        channelLog.setCreationDate(new Date());
        if (!checkDuplicateLog(channelLog)) {
            save(channelLog);
        }
    }
 
    @Override
    public void createExportLog(Integer source, Integer exportSource, Integer status, Long customerId, String result) {
        ChannelInfo channelInfo = channelInfoService.lambdaQuery().eq(ChannelInfo::getCode, source).one();
        ChannelLog channelLog = new ChannelLog();
        channelLog.setSource(source);
        channelLog.setName(channelInfo.getName());
        channelLog.setType(ChannelLog.EXPORT);
        channelLog.setExportSource(exportSource);
        channelLog.setStatus(status);
        channelLog.setCustomerRecordId(customerId);
        channelLog.setResult(result);
        channelLog.setCreationDate(new Date());
        if (!checkDuplicateLog(channelLog)) {
            save(channelLog);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createSupermarketLog(Long supermarketId, Integer source, Long customerId) {
        ChannelLog channelLog = new ChannelLog();
        Customer customer = customerMapper.selectById(customerId);
        if (customer != null) {
            channelLog.setSource(customer.getSourceChannel());
            channelLog.setStatus(ChannelLog.SUCCESS);
        } else {
            channelLog.setSource(source);
            channelLog.setStatus(ChannelLog.FAIL);
        }
        ChannelInfo channelInfo = channelInfoService.lambdaQuery().eq(ChannelInfo::getCode, customer.getSourceChannel()).one();
        channelLog.setName(channelInfo.getName());
        channelLog.setExportSource(SourceTypeEnum.LOAN_SUPERMARKET.getCode());
        channelLog.setType(ChannelLog.EXPORT);
        channelLog.setCustomerRecordId(customerId);
        channelLog.setRecordId(supermarketId);
        channelLog.setCreationDate(new Date());
        if (!checkDuplicateLog(channelLog)) {
            save(channelLog);
        } else {
            log.info("创建重复客户推送记录,原始数据:" + channelLog.toString());
        }
    }
 
    @Override
    public List<ChannelReportTotalVo> importTotal(ChannelReportDto reportDto) {
        List<ChannelReportTotalVo> result = channelLogMapper.importTotal(reportDto.initDate());
        result = result.stream().filter(i -> i.getSuccessCountSum() != 0).collect(Collectors.toList());
        return result;
    }
 
    @Override
    public IPage<ChannelImportReportVo> importDetail(ChannelReportDetailDto reportDto, PageRequest pageRequest) {
        IPage<ChannelImportReportVo> page = channelLogMapper.importDetail(pageUtil.getPage(pageRequest), reportDto.initDate());
        return page;
    }
 
    @Override
    public List<ChannelReportTotalVo> exportTotal(ChannelReportDto reportDto) {
        List<ChannelReportTotalVo> result = new ArrayList<>();
//        List<ChannelReportTotalVo> common = channelLogMapper.exportTotal(reportDto.initDate());
//        result.addAll(common);
//        if (reportDto.getChannelCode() != null && !SourceTypeEnum.LOAN_SUPERMARKET.getCode().equals(reportDto.getChannelCode())) {
//            return result;
//        }
        List<ChannelReportTotalVo> supermarket = channelLogMapper.exportSupermarketTotal(reportDto.initDate());
        result.addAll(supermarket);
        result = result.stream().filter(i -> i.getSuccessCountSum() != 0).collect(Collectors.toList());
        return result;
    }
 
    @Override
    public IPage<ChannelExportReportVo> exportDetail(ChannelReportDetailDto reportDto, PageRequest pageRequest) {
        if (SourceTypeEnum.LOAN_SUPERMARKET.getCode().equals(reportDto.getChannelCode())) {
            IPage<ChannelExportReportVo> page = channelLogMapper.exportLoanMarketDetail(pageUtil.getPage(pageRequest), reportDto.initDate());
            return page;
        }
        IPage<ChannelExportReportVo> page = channelLogMapper.exportDetail(pageUtil.getPage(pageRequest), reportDto.initDate());
        return page;
    }
 
    @Override
    public List<ChannelInfo> channelList(Integer type) {
        List<ChannelInfo> list = channelInfoService.lambdaQuery().eq(ChannelInfo::getStatus, 1)
                .eq(ChannelInfo::getType, type).list();
        return list;
    }
 
    private boolean checkDuplicateLog(ChannelLog channelLog) {
        DateTime endOfDay = DateUtil.endOfDay(new Date());
        DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        List<ChannelLog> list = channelLogMapper.selectDuplicateLogs(beginOfDay, endOfDay, channelLog);
        if (list == null || list.isEmpty()) {
            return false;
        }
        return true;
    }
 
    @Override
    public void addJYDLoanMarketRecord(Long loanMarkId, UserDetail userDetail) {
        CustomerUser customerUser = customerUserService.lambdaQuery().eq(CustomerUser::getPhone, userDetail.getPhone()).one();
        ChannelLog channelLog = new ChannelLog();
        channelLog.setSource(customerUser.getSourceChannel());
        channelLog.setStatus(ChannelLog.SUCCESS);
        ChannelInfo channelInfo = channelInfoService.lambdaQuery().eq(ChannelInfo::getCode, customerUser.getSourceChannel()).one();
        Customer customer = customerMapper.getLatestCustomerRecord(userDetail.getPhone());
        if (customer == null) {
            throw new CommonException("客户历史记录为空");
        }
        channelLog.setExportSource(SourceTypeEnum.LOAN_SUPERMARKET.getCode());
        channelLog.setName(channelInfo.getName());
        channelLog.setType(ChannelLog.EXPORT);
        channelLog.setCustomerRecordId(customer.getId());
        channelLog.setRecordId(loanMarkId);
        channelLog.setCreationDate(new Date());
        if (!checkDuplicateLog(channelLog)) {
            save(channelLog);
        } else {
            log.info("创建重复客户推送记录,原始数据:" + channelLog.toString());
        }
    }
 
    @Override
    public List<ChannelProportionListVo> getChannelProportion(ChannelProportionDto channelProportionDto) {
        ChannelInfo channelInfos = channelInfoService.getOne(new LambdaQueryWrapper<ChannelInfo>()
                .eq(ChannelInfo::getCode, channelProportionDto.getChCode()).eq(ChannelInfo::getStatus, 1));
        if (ObjectUtils.isEmpty(channelInfos)) {
            throw new CommonException("未查询到该渠道");
        }
        if (channelProportionDto.getEndDate() == null) {
            throw new CommonException("查询时间不能为空");
        }
 
        DateTime startDate = DateUtil.beginOfDay(DateUtil.offsetDay(channelProportionDto.getEndDate(), -1));
        DateTime endDate = DateUtil.endOfDay(channelProportionDto.getEndDate());
 
        String startDayStr = DateUtil.format(startDate, "MM-dd");
        String endDayStr = DateUtil.format(endDate, "MM-dd");
 
        String startDayTemp = DateUtil.format(startDate, "yyyy-MM-dd");
        String endDayTemp = DateUtil.format(endDate, "yyyy-MM-dd");
 
        Integer chCode = channelProportionDto.getChCode();
        String[] hourStr = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
        List<ChannelProportionVo> channelProportion = channelLogMapper.getChannelProportion(startDate, endDate, chCode, startDayTemp, endDayTemp, hourStr);
        ArrayList<ChannelProportionListVo> channelProportionListVos = new ArrayList<>();
        if (ObjectUtils.isEmpty(channelProportion) || channelProportion.size() < 1) {
            return new ArrayList<>();
        }
        for (String hour : hourStr) {
            ChannelProportionListVo channelProportionListVo = new ChannelProportionListVo();
            channelProportionListVo.setHHour(hour);
            channelProportionListVo.setChName(channelInfos.getName());
            channelProportionListVo.setTime(endDayStr);
            channelProportionListVo.setLastTime(startDayStr);
            ChannelProportionVo channelProportionVo1 = channelProportion.stream()
                    .filter(i -> startDayStr.equals(i.getHDay()) && hour.equals(i.getHHour())).findFirst().orElse(null);
            if (channelProportionVo1 != null) {
                channelProportionListVo.setLastVipSum(channelProportionVo1.getVipSum());
                channelProportionListVo.setLastVipPropertion(channelProportionVo1.getVipPropertion());
                channelProportionListVo.setLastUvSum(channelProportionVo1.getUvSum());
                channelProportionListVo.setLastPkSum(channelProportionVo1.getPkSum());
                channelProportionListVo.setLastPkPropertion(channelProportionVo1.getPkPropertion());
            }
            ChannelProportionVo channelProportionVo = channelProportion.stream()
                    .filter(i -> endDayStr.equals(i.getHDay()) && hour.equals(i.getHHour())).findFirst().orElse(null);
            if (channelProportionVo != null) {
                channelProportionListVo.setVipSum(channelProportionVo.getVipSum());
                channelProportionListVo.setVipPropertion(channelProportionVo.getVipPropertion());
                channelProportionListVo.setUvSum(channelProportionVo.getUvSum());
                channelProportionListVo.setPkSum(channelProportionVo.getPkSum());
                channelProportionListVo.setPkPropertion(channelProportionVo.getPkPropertion());
            }
            channelProportionListVos.add(channelProportionListVo);
        }
        return channelProportionListVos;
    }
 
    @Override
    public List<LoanSupermarketStatisticsVo> getLoanSupermarketStatistics(LoanSupermarketStatisticsDto supermarketStatisticsDto) {
        Long suId = supermarketStatisticsDto.getSuId();
        if (supermarketStatisticsDto.getDate() == null) {
            throw new CommonException("查询时间不能为空");
        }
        DateTime startDate = DateUtil.beginOfDay(supermarketStatisticsDto.getDate());
        DateTime endDate = DateUtil.endOfDay(supermarketStatisticsDto.getDate());
        Integer chCode = supermarketStatisticsDto.getChCode();
        List<LoanSupermarketStatisticsVo> loanSupermarketStatistics = channelLogMapper.getLoanSupermarketStatistics(startDate, endDate, suId, chCode);
        if (ObjectUtils.isEmpty(loanSupermarketStatistics) || loanSupermarketStatistics.size() < 1) {
            return new ArrayList<>();
        }
        String[] hourStr = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
        Map<String, List<LoanSupermarketStatisticsVo>> collect = loanSupermarketStatistics.stream().collect(Collectors.groupingBy(LoanSupermarketStatisticsVo::getHHour));
        ArrayList<LoanSupermarketStatisticsVo> loanSupermarketStatisticsVos = new ArrayList<>();
        for (String s : hourStr) {
            if (ObjectUtils.isEmpty(collect.get(s)) || collect.get(s).size() < 1) {
                LoanSupermarketStatisticsVo loanSupermarketStatisticsVo = new LoanSupermarketStatisticsVo();
                loanSupermarketStatisticsVo.setHHour(s);
                loanSupermarketStatisticsVos.add(loanSupermarketStatisticsVo);
            } else {
                loanSupermarketStatisticsVos.addAll(collect.get(s));
            }
        }
        return loanSupermarketStatisticsVos;
    }
 
    @Override
    public List<AutoStatisticsVo> getAutoStatistics(AutoStatisticsDto autoStatisticsDto) {
        DateTime startDate = DateUtil.beginOfDay(autoStatisticsDto.getEndDate());
        DateTime endDate = DateUtil.endOfDay(autoStatisticsDto.getEndDate());
        List<AutoStatisticsVo> autoStatistics = channelLogMapper.getAutoStatistics(startDate, endDate);
        if (ObjectUtils.isEmpty(autoStatistics) || autoStatistics.isEmpty()) {
            return new ArrayList<>();
        }
        List<AutoStatisticsVo> newList = new ArrayList<>();
        autoStatistics.forEach(it -> {
            if (it.getVipAmount() != null) {
                it.setVipAmount(it.getVipAmount() / 100);
            }
            if (it.getPkAmount() != null) {
                it.setPkAmount(it.getPkAmount() / 100);
            }
            if (StringUtils.isNotEmpty(it.getChName())) {
                it.setUv(0);
                it.setVipAmountSum(null);
            }
            //数据修复
            if (Objects.isNull(it.getSuCode())) {
                log.error("联登报表{}渠道数据丢失", it.getChName());
                channelLogMapper.dataRepair(it.getId());
                ChannelInfo byId = channelInfoService.getById(it.getId());
                it.setSuCode(byId.getAutoParentCode());
            }
            if (!checkIsNull(it)) {
                newList.add(it);
            }
        });
        Map<Integer, List<AutoStatisticsVo>> collect = newList.stream().sorted(Comparator.comparing(AutoStatisticsVo::getSuName).reversed()).collect(Collectors.groupingBy(AutoStatisticsVo::getSuCode));
        List<AutoStatisticsVo> autoStatisticsVos = new ArrayList<>();
        collect.keySet().stream().map(it -> {
            List<AutoStatisticsVo> autoStatisticsVos1 = collect.get(it);
            if (!ObjectUtils.isEmpty(autoStatisticsVos1) && !autoStatisticsVos1.isEmpty()) {
                AutoStatisticsVo autoStatisticsVo = autoStatisticsVos1.get(0);
                double sum = autoStatisticsVos1.stream().filter(i -> i.getVipAmount() != null).mapToDouble(AutoStatisticsVo::getVipAmount).sum();
                autoStatisticsVos1.remove(autoStatisticsVo);
                autoStatisticsVo.setVipAmountSum(sum);
                autoStatisticsVos.add(autoStatisticsVo);
                autoStatisticsVos.addAll(autoStatisticsVos1);
            }
            return it;
        }).collect(Collectors.toList());
        return autoStatisticsVos;
    }
 
    @Override
    public void getChannelProportionExport(HttpServletResponse response, ChannelProportionDto channelProportionDto) {
        List<ChannelProportionListVo> channelProportion = this.getChannelProportion(channelProportionDto);
        ArrayList<ChannelProportionListExportVo> channelProportionListExportVos = new ArrayList<>();
        for (ChannelProportionListVo channelProportionListVo : channelProportion) {
            ChannelProportionListExportVo channelProportionListVo1 = new ChannelProportionListExportVo();
            BeanUtils.copyProperties(channelProportionListVo, channelProportionListVo1);
            channelProportionListExportVos.add(channelProportionListVo1);
        }
        for (int i = 0; i < channelProportion.size(); i++) {
            channelProportionListExportVos.get(i).setId(i + 1);
        }
        // 通过工具类创建writer,默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.passRows(3);
 
        String lastTime = channelProportion.get(0).getLastTime();
        lastTime = lastTime.replace("-", "");
        String time = channelProportion.get(0).getTime();
        time = time.replace("-", "");
        // 自定义标题别名
        writer.addHeaderAlias("id", "序号");
        writer.addHeaderAlias("chName", "渠道");
        writer.addHeaderAlias("hHour", "时间(每小时)");
 
        writer.addHeaderAlias("lastUvSum", lastTime);
        writer.addHeaderAlias("uvSum", time);
 
        writer.addHeaderAlias("lastPkSum", "1");
        writer.addHeaderAlias("pkSum", "2");
 
        writer.addHeaderAlias("lastPkPropertion", "3");
        writer.addHeaderAlias("pkPropertion", "4");
 
        writer.addHeaderAlias("lastVipSum", "5");
        writer.addHeaderAlias("vipSum", "6");
 
        writer.addHeaderAlias("lastVipPropertion", "7");
        writer.addHeaderAlias("vipPropertion", "8");
        writer.setOnlyAlias(true);
        // 合并单元格后的标题行,使用默认标题样式
        CellStyle cellStyle = writer.getStyleSet().getCellStyle();
        CellStyle cellStyle1 = writer.getStyleSet().getCellStyle();
        cellStyle1.setWrapText(true);
        //设置默认高度
        writer.setDefaultRowHeight(40);
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(channelProportionListExportVos, true);
        //设置自适应列宽
        setSizeColumn(writer.getSheet(), 12);
 
        writer.merge(0, 1, 3, 4, "UV", cellStyle);
        writer.merge(0, 1, 5, 6, "加速包购买数量", cellStyle);
        writer.merge(0, 1, 7, 8, "加速包购买率(加速包购买数量/UV)", cellStyle1);
        writer.merge(0, 1, 9, 10, "会员购买数量", cellStyle);
        writer.merge(0, 1, 11, 12, "会员购买比例(会员购买数量/UV)", cellStyle1);
        writer.merge(2, 3, 9, 9, lastTime, cellStyle);
        writer.merge(2, 3, 10, 10, time, cellStyle);
        writer.merge(2, 3, 3, 3, lastTime, cellStyle);
        writer.merge(2, 3, 4, 4, time, cellStyle);
        writer.merge(2, 3, 5, 5, lastTime, cellStyle);
        writer.merge(2, 3, 6, 6, time, cellStyle);
        writer.merge(2, 3, 7, 7, lastTime, cellStyle);
        writer.merge(2, 3, 8, 8, time, cellStyle);
        writer.merge(2, 3, 11, 11, lastTime, cellStyle);
        writer.merge(2, 3, 12, 12, time, cellStyle);
        writer.merge(2, 3, 1, 1, "渠道", cellStyle);
        writer.merge(2, 3, 2, 2, "时间(每小时)", cellStyle);
        writer.merge(2, 3, 0, 0, "序号", cellStyle);
 
        //浏览器导出
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        ServletOutputStream out = null;
        try {
            // 设置请求头属性
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("入口流量会员购买率" + ".xlsx").getBytes(), StandardCharsets.UTF_8));
            out = response.getOutputStream();
            // 写出到文件
            writer.flush(out, true);
            // 关闭writer,释放内存
            writer.close();
            // 此处记得关闭输出Servlet流
            IoUtil.close(out);
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
 
    }
 
    @Override
    public void getLoanSupermarketStatisticsExport(HttpServletResponse response, LoanSupermarketStatisticsDto supermarketStatisticsDto) {
        List<LoanSupermarketStatisticsVo> loanSupermarketStatistics = getLoanSupermarketStatistics(supermarketStatisticsDto);
        ArrayList<LoanSupermarketStatisticsExportVo> loanSupermarketStatisticsExportVos = new ArrayList<>();
        for (LoanSupermarketStatisticsVo loanSupermarketStatisticsVo : loanSupermarketStatistics) {
            LoanSupermarketStatisticsExportVo loanSupermarketStatisticsExportVo = new LoanSupermarketStatisticsExportVo();
            BeanUtils.copyProperties(loanSupermarketStatisticsVo, loanSupermarketStatisticsExportVo);
            loanSupermarketStatisticsExportVos.add(loanSupermarketStatisticsExportVo);
        }
        String suName = "";
        for (int i = 0; i < loanSupermarketStatisticsExportVos.size(); i++) {
            loanSupermarketStatisticsExportVos.get(i).setId(i + 1);
            if (!StringUtils.isEmpty(loanSupermarketStatisticsExportVos.get(i).getSuName()) && !"".equals(loanSupermarketStatisticsExportVos.get(i).getSuName())) {
                suName = loanSupermarketStatisticsExportVos.get(i).getSuName();
            }
        }
 
        String format = DateUtil.format(supermarketStatisticsDto.getDate(), "yyyy-MM-dd");
        // 通过工具类创建writer,默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.passRows(2);
 
        // 自定义标题别名
        writer.addHeaderAlias("id", "序号");
        writer.addHeaderAlias("hHour", "时间(每小时)");
        writer.addHeaderAlias("suName", "贷超产品");
        writer.addHeaderAlias("uvSum", "UV");
        writer.addHeaderAlias("chName", "渠道名称");
        writer.setOnlyAlias(true);
 
        // 合并单元格后的标题行,使用默认标题样式
        CellStyle cellStyle = writer.getStyleSet().getCellStyle();
        CellStyle cellStyle1 = writer.getStyleSet().getCellStyle();
        cellStyle1.setWrapText(true);
        //设置默认高度
        writer.setDefaultRowHeight(40);
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(loanSupermarketStatisticsExportVos, true);
        //设置自适应列宽
        setSizeColumn(writer.getSheet(), 4);
 
        writer.merge(0, 1, 0, 1, "日期:" + format, cellStyle);
        writer.merge(0, 1, 2, 3, "贷超产品:" + suName, cellStyle1);
 
        //浏览器导出
        webExport(response, writer);
    }
 
    @Override
    public void autoStatisticsExport(HttpServletResponse response, AutoStatisticsDto autoStatisticsDto) {
        List<AutoStatisticsVo> autoStatistics = getAutoStatistics(autoStatisticsDto);
        String format = DateUtil.format(autoStatisticsDto.getEndDate(), "yyyy-MM-dd");
        // 通过工具类创建writer,默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.passRows(1);
 
        // 自定义标题别名
        writer.addHeaderAlias("hDay", "日期");
        writer.addHeaderAlias("suName", "产品");
        writer.addHeaderAlias("chName", "接入渠道");
        writer.addHeaderAlias("uv", "UV");
        writer.addHeaderAlias("inletFlowSum", "入口流量数");
        writer.addHeaderAlias("pkAmount", "加速包金额");
        writer.addHeaderAlias("vipAmount", "会员金额");
        writer.addHeaderAlias("vipAmountSum", "会员金额合计");
        writer.addHeaderAlias("vipPropertion", "会员入口流量比");
        writer.setOnlyAlias(true);
 
        // 合并单元格后的标题行,使用默认标题样式
        CellStyle cellStyle = writer.getStyleSet().getCellStyle();
        cellStyle.setWrapText(true);
        //设置默认高度
        writer.setDefaultRowHeight(40);
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(autoStatistics, true);
        //设置自适应列宽
        setSizeColumn(writer.getSheet(), 8);
 
        writer.merge(0, 0, 0, 1, "日期:" + format, cellStyle);
 
        //浏览器导出
        webExport(response, writer);
 
    }
 
 
    /**
     * 判断数据内容是否为空
     *
     * @param autoStatisticsVo
     * @return
     */
    private boolean checkIsNull(AutoStatisticsVo autoStatisticsVo) {
        //判断对象数据是否为空
        if (Objects.isNull(autoStatisticsVo.getVipAmount()) && Objects.isNull(autoStatisticsVo.getPkAmount()) && Objects.isNull(autoStatisticsVo.getInletFlowSum()) && Objects.isNull(autoStatisticsVo.getVipAmountSum())) {
            if (Objects.isNull(autoStatisticsVo.getUv()) || autoStatisticsVo.getUv() == 0) {
                return true;
            }
        }
        return false;
    }
 
 
    @Override
    public List<WholeProcessStatisticsListVo> getWholeProcessStatistics(WholeProcessStatisticsDto wholeProcessStatisticsDto) {
        if (wholeProcessStatisticsDto.getDate() == null) {
            throw new CommonException("查询时间不能为空");
        }
        DateTime startDate = DateUtil.beginOfDay(wholeProcessStatisticsDto.getDate());
        DateTime endDate = DateUtil.endOfDay(wholeProcessStatisticsDto.getDate());
        Integer chCode = wholeProcessStatisticsDto.getChCode();
        WholeProcessStatisticsVo resultDb = channelLogMapper.getWholeProcessStatistics(startDate, endDate, chCode);
        List<WholeProcessStatisticsListVo> result = new ArrayList<>();
        WholeProcessStatisticsListVo statisticsH5Vo = new WholeProcessStatisticsListVo();
        WholeProcessStatisticsListVo statisticsAppVo = new WholeProcessStatisticsListVo();
        statisticsH5Vo.setType("H5");
        statisticsH5Vo.setDate(resultDb.getDate());
        statisticsH5Vo.setLoginCount(resultDb.getH5LoginCount());
        statisticsH5Vo.setDownloadCount(resultDb.getDownloadCount());
        statisticsH5Vo.setBaseInfoCount(resultDb.getBaseInfoCount());
        result.add(statisticsH5Vo);
        BeanUtils.copyProperties(resultDb,statisticsAppVo);
        statisticsAppVo.setType("APP");
        statisticsAppVo.setDownloadCount(null);
        statisticsAppVo.setLoginCount(resultDb.getAppLoginCount());
        result.add(statisticsAppVo);
        return result;
    }
 
    @Override
    public List<InletFlowProportionListVo> getInletFlowProportion(InletFlowProportionDto inletFlowProportionDto) {
        ChannelInfo channelInfos = channelInfoMapper.selectOne(new LambdaQueryWrapper<ChannelInfo>()
                .eq(ChannelInfo::getCode, inletFlowProportionDto.getChCode()).eq(ChannelInfo::getStatus, 1));
        if (ObjectUtils.isEmpty(channelInfos)) {
            throw new CommonException("未查询到该渠道");
        }
        if (inletFlowProportionDto.getEndDate() == null) {
            throw new CommonException("查询时间不能为空");
        }
 
        DateTime startDate = DateUtil.beginOfDay(DateUtil.offsetDay(inletFlowProportionDto.getEndDate(), -1));
        DateTime endDate = DateUtil.endOfDay(inletFlowProportionDto.getEndDate());
 
        String startDayStr = DateUtil.format(startDate, "MM-dd");
        String endDayStr = DateUtil.format(endDate, "MM-dd");
 
        String startDayTemp = DateUtil.format(startDate, "yyyy-MM-dd");
        String endDayTemp = DateUtil.format(endDate, "yyyy-MM-dd");
 
        Integer chCode = inletFlowProportionDto.getChCode();
        String[] hourStr = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
                "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
        List<InletFlowProportionVo> inletFlowProportionVos = customerMapper.getInletFlowProportion(startDate, endDate, chCode, startDayTemp, endDayTemp, hourStr);
        ArrayList<InletFlowProportionListVo> inletFlowProportionListVos = new ArrayList<>();
 
        if (ObjectUtils.isEmpty(inletFlowProportionVos) || inletFlowProportionVos.size() < 1) {
            return new ArrayList<>();
        }
        for (String hour : hourStr) {
            InletFlowProportionListVo channelProportionListVo = new InletFlowProportionListVo();
            channelProportionListVo.setHHour(hour);
            channelProportionListVo.setChName(channelInfos.getName());
            channelProportionListVo.setTime(endDayStr);
            channelProportionListVo.setLastTime(startDayStr);
            InletFlowProportionVo inletFlowProportionVo = inletFlowProportionVos.stream()
                    .filter(i -> startDayStr.equals(i.getHDay()) && hour.equals(i.getHHour())).findFirst().orElse(null);
            if (inletFlowProportionVo != null) {
                channelProportionListVo.setLastVipSum(inletFlowProportionVo.getVipSum());
                channelProportionListVo.setLastVipPropertion(inletFlowProportionVo.getVipPropertion());
                channelProportionListVo.setLastUvSum(inletFlowProportionVo.getUvSum());
                channelProportionListVo.setLastPkSum(inletFlowProportionVo.getPkSum());
                channelProportionListVo.setLastPkPropertion(inletFlowProportionVo.getPkPropertion());
            }
            InletFlowProportionVo inletFlowProportionVo1 = inletFlowProportionVos.stream()
                    .filter(i -> endDayStr.equals(i.getHDay()) && hour.equals(i.getHHour())).findFirst().orElse(null);
            if (inletFlowProportionVo1 != null) {
                channelProportionListVo.setVipSum(inletFlowProportionVo1.getVipSum());
                channelProportionListVo.setVipPropertion(inletFlowProportionVo1.getVipPropertion());
                channelProportionListVo.setUvSum(inletFlowProportionVo1.getUvSum());
                channelProportionListVo.setPkSum(inletFlowProportionVo1.getPkSum());
                channelProportionListVo.setPkPropertion(inletFlowProportionVo1.getPkPropertion());
            }
            inletFlowProportionListVos.add(channelProportionListVo);
        }
        return inletFlowProportionListVos;
    }
 
 
    @Override
    public void inletFlowProportionExport(HttpServletResponse response, InletFlowProportionDto inletFlowProportionDto) {
 
        List<InletFlowProportionListVo> inletFlowProportion = getInletFlowProportion(inletFlowProportionDto);
        List<InletFlowProportionListExportVo> inletFlowProportionListExportVos = new ArrayList<>();
        for (InletFlowProportionListVo inletFlowProportionListVo : inletFlowProportion) {
            InletFlowProportionListExportVo inletFlowProportionListExportVo = new InletFlowProportionListExportVo();
            BeanUtils.copyProperties(inletFlowProportionListVo, inletFlowProportionListExportVo);
            inletFlowProportionListExportVos.add(inletFlowProportionListExportVo);
        }
        for (int i = 0; i < inletFlowProportion.size(); i++) {
            inletFlowProportionListExportVos.get(i).setId(i + 1);
        }
        // 通过工具类创建writer,默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.passRows(3);
 
        String lastTime = inletFlowProportion.get(0).getLastTime();
        lastTime = lastTime.replace("-", "");
        String time = inletFlowProportion.get(0).getTime();
        time = time.replace("-", "");
        // 自定义标题别名
        writer.addHeaderAlias("id", "序号");
        writer.addHeaderAlias("chName", "渠道");
        writer.addHeaderAlias("hHour", "时间(每小时)");
 
        writer.addHeaderAlias("lastUvSum", lastTime);
        writer.addHeaderAlias("uvSum", time);
 
        writer.addHeaderAlias("lastPkSum", "1");
        writer.addHeaderAlias("pkSum", "2");
 
        writer.addHeaderAlias("lastPkPropertion", "3");
        writer.addHeaderAlias("pkPropertion", "4");
 
        writer.addHeaderAlias("lastVipSum", "5");
        writer.addHeaderAlias("vipSum", "6");
 
        writer.addHeaderAlias("lastVipPropertion", "7");
        writer.addHeaderAlias("vipPropertion", "8");
        writer.setOnlyAlias(true);
        // 合并单元格后的标题行,使用默认标题样式
        CellStyle cellStyle = writer.getStyleSet().getCellStyle();
        CellStyle cellStyle1 = writer.getStyleSet().getCellStyle();
        cellStyle1.setWrapText(true);
        //设置默认高度
        writer.setDefaultRowHeight(40);
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(inletFlowProportionListExportVos, true);
        //设置自适应列宽
        setSizeColumn(writer.getSheet(), 12);
 
        writer.merge(0, 1, 3, 4, "入口流量数", cellStyle);
        writer.merge(0, 1, 5, 6, "加速包购买数量", cellStyle);
        writer.merge(0, 1, 7, 8, "加速包购买率(加速包购买数量/UV)", cellStyle1);
        writer.merge(0, 1, 9, 10, "会员购买数量", cellStyle);
        writer.merge(0, 1, 11, 12, "会员购买购买率(会员购买数量/UV)", cellStyle1);
        writer.merge(2, 3, 9, 9, lastTime, cellStyle);
        writer.merge(2, 3, 10, 10, time, cellStyle);
        writer.merge(2, 3, 3, 3, lastTime, cellStyle);
        writer.merge(2, 3, 4, 4, time, cellStyle);
        writer.merge(2, 3, 5, 5, lastTime, cellStyle);
        writer.merge(2, 3, 6, 6, time, cellStyle);
        writer.merge(2, 3, 7, 7, lastTime, cellStyle);
        writer.merge(2, 3, 8, 8, time, cellStyle);
        writer.merge(2, 3, 11, 11, lastTime, cellStyle);
        writer.merge(2, 3, 12, 12, time, cellStyle);
        writer.merge(2, 3, 1, 1, "渠道", cellStyle);
        writer.merge(2, 3, 2, 2, "时间(每小时)", cellStyle);
        writer.merge(2, 3, 0, 0, "序号", cellStyle);
 
 
        //浏览器导出
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        ServletOutputStream out = null;
        try {
            // 设置请求头属性
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("入口流量会员购买率" + ".xlsx").getBytes(), StandardCharsets.UTF_8));
            out = response.getOutputStream();
            // 写出到文件
            writer.flush(out, true);
            // 关闭writer,释放内存
            writer.close();
            // 此处记得关闭输出Servlet流
            IoUtil.close(out);
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }
 
 
    @Override
    public List<ChannelStatisticsVo> channelStatistics(ChannelStatisticsDto channelStatisticsDto) {
        List<Integer> chCodes = channelStatisticsDto.getChCodes();
        if (chCodes != null && chCodes.size() > 0) {
            List<ChannelInfo> channelInfos = channelInfoMapper.selectList(new LambdaQueryWrapper<ChannelInfo>().in(ChannelInfo::getCode, chCodes));
            if (CollectionUtils.isEmpty(channelInfos) || channelInfos.size() < channelStatisticsDto.getChCodes().size()) {
                throw new CommonException("有未存在的渠道");
            }
        } else {
            chCodes = null;
        }
        if (channelStatisticsDto.getDate() == null) {
            throw new CommonException("查询时间不能为空");
        }
        DateTime startDate = DateUtil.beginOfDay(DateUtil.offsetDay(channelStatisticsDto.getDate(), -1));
        DateTime endDate = DateUtil.endOfDay(channelStatisticsDto.getDate());
        String startDayStr = DateUtil.format(startDate, "MM-dd");
        String endDayStr = DateUtil.format(endDate, "MM-dd");
 
        List<ChannelStatisticsListVo> channelStatisticsListVos = channelLogMapper.channelStatistics(startDate, endDate, chCodes);
        if (CollectionUtils.isEmpty(channelStatisticsListVos)) {
            return new ArrayList<>();
        }
        ArrayList<ChannelStatisticsVo> channelStatisticsVos = new ArrayList<>();
        Map<String, List<ChannelStatisticsListVo>> startDayByChName = channelStatisticsListVos.stream().filter(i -> startDayStr.equals(i.getHDay())).collect(Collectors.groupingBy(ChannelStatisticsListVo::getChName));
        Map<String, List<ChannelStatisticsListVo>> endDayByChName = channelStatisticsListVos.stream().filter(i -> endDayStr.equals(i.getHDay())).collect(Collectors.groupingBy(ChannelStatisticsListVo::getChName));
        Map<String, List<ChannelStatisticsListVo>> collect = channelStatisticsListVos.stream().collect(Collectors.groupingBy(ChannelStatisticsListVo::getChName));
        collect.keySet().stream().map(item -> {
            ChannelStatisticsVo channelStatisticsVo = new ChannelStatisticsVo();
            channelStatisticsVo.setChName(item);
            channelStatisticsVo.setLastTime(startDayStr);
            channelStatisticsVo.setTime(endDayStr);
            List<ChannelStatisticsListVo> channelStatisticsListVos1 = startDayByChName.get(item);
            if (!CollectionUtils.isEmpty(channelStatisticsListVos1) && !channelStatisticsListVos1.isEmpty()) {
                channelStatisticsVo.setLastPkPropertion(channelStatisticsListVos1.get(0).getPkPropertion());
                channelStatisticsVo.setLastPkSum(channelStatisticsListVos1.get(0).getPkSum());
                channelStatisticsVo.setLastUvSum(channelStatisticsListVos1.get(0).getUvSum());
                channelStatisticsVo.setLastVipSum(channelStatisticsListVos1.get(0).getVipSum());
                channelStatisticsVo.setLastVipPropertion(channelStatisticsListVos1.get(0).getVipPropertion());
            }
            List<ChannelStatisticsListVo> channelStatisticsListVos2 = endDayByChName.get(item);
            if (!CollectionUtils.isEmpty(channelStatisticsListVos2) && !channelStatisticsListVos2.isEmpty()) {
                channelStatisticsVo.setPkPropertion(channelStatisticsListVos2.get(0).getPkPropertion());
                channelStatisticsVo.setPkSum(channelStatisticsListVos2.get(0).getPkSum());
                channelStatisticsVo.setUvSum(channelStatisticsListVos2.get(0).getUvSum());
                channelStatisticsVo.setVipSum(channelStatisticsListVos2.get(0).getVipSum());
                channelStatisticsVo.setVipPropertion(channelStatisticsListVos2.get(0).getVipPropertion());
            }
            channelStatisticsVos.add(channelStatisticsVo);
            return item;
        }).collect(Collectors.toList());
        return channelStatisticsVos;
    }
 
    @Override
    public List<ProfitAnalysisReportVo> profitAnalysisReport(ProfitAnalysisReportDto profitAnalysisReportDto) {
        if (profitAnalysisReportDto.getDate() == null) {
            profitAnalysisReportDto.setDate(new Date());
        }
        Integer chCode = profitAnalysisReportDto.getChCode();
        if (chCode == null) {
            return new ArrayList<>();
        }
        ChannelInfo channelInfo = channelInfoMapper.selectOne(new LambdaQueryWrapper<ChannelInfo>().in(ChannelInfo::getCode, chCode));
        if (channelInfo == null) {
            throw new CommonException("渠道不存在");
        }
        DateTime startDate = DateUtil.beginOfDay(profitAnalysisReportDto.getDate());
        DateTime endDate = DateUtil.endOfDay(profitAnalysisReportDto.getDate());
        ProfitAnalysisReportVo reportVo = new ProfitAnalysisReportVo();
        BaseProfitAnalysisReportVo baseReportVo = channelLogMapper.getBaseProfitAnalysisReportVo(startDate, endDate, chCode);
        reportVo.setChName(baseReportVo.getChName());
        reportVo.setUvSum(baseReportVo.getUvSum());
        reportVo.setLoanIncome(baseReportVo.getLoanIncome());
        reportVo.setVipIncome(baseReportVo.getVipIncome());
        reportVo.setPkIncome(baseReportVo.getPkIncome());
        CityProfitAnalysisReportVo cityReportVo = channelLogMapper.getCityProfitAnalysisReportVo(startDate, endDate, chCode);
        reportVo.setCollisionIncome(cityReportVo.getCollisionIncome());
        reportVo.setCompanyIncome(cityReportVo.getCapitalIncome() + cityReportVo.getAuditIncome());
        reportVo.setRegisterSum(cityReportVo.getRegisterSum());
        Integer totalCost = baseReportVo.getUvCost() + cityReportVo.getRegisterCost();
        reportVo.setTotalCost(totalCost);
        Integer totalIncome = reportVo.getLoanIncome() + reportVo.getPkIncome() + reportVo.getVipIncome()
                + reportVo.getCollisionIncome() + reportVo.getCompanyIncome();
        reportVo.setTotalIncome(totalIncome);
        reportVo.setProfit(totalIncome - totalCost);
        return Collections.singletonList(reportVo);
    }
 
    //设置自适应列宽
    public static void setSizeColumn(Sheet sheet, int size) {
        for (int columnNum = 0; columnNum <= size; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
 
                if (currentRow.getCell(columnNum) != null) {
                    Cell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == CellType.STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }
 
    //浏览器导出
    public void webExport(HttpServletResponse response, ExcelWriter writer) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        ServletOutputStream out = null;
        try {
            // 设置请求头属性
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("入口流量会员购买率" + ".xlsx").getBytes(), StandardCharsets.UTF_8));
            out = response.getOutputStream();
            // 写出到文件
            writer.flush(out, true);
            // 关闭writer,释放内存
            writer.close();
            // 此处记得关闭输出Servlet流
            IoUtil.close(out);
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }
}