CustomerStatisticsService.java 51 KB
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 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
package cn.com.glsx.entmicro.service;

import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.entity.CustomerStatistics;
import cn.com.glsx.entmicro.mapper.CustomerBaseStatisticsMapper;
import cn.com.glsx.entmicro.mapper.CustomerStatisticsMapper;
import cn.com.glsx.entmicro.model.CustomerStaticRequest;
import cn.com.glsx.entmicro.model.CustomerStatisticModel;
import cn.com.glsx.entmicro.model.MerchantRopResponse;
import cn.com.glsx.entmicro.model.request.drainage.DracScrmStatisticCodeDefaultRequest;
import cn.com.glsx.entmicro.model.response.*;
import cn.com.glsx.entmicro.util.CalculateUtils;
import cn.com.glsx.entmicro.util.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.glsx.plat.common.utils.DateUtils;
import com.glsx.plat.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fengzhi
 * @Description: 客户概览统计 Service
 * @date 2021/9/23 14:40
 * matches 121
 */

@Service
@Slf4j
public class CustomerStatisticsService {
    @Autowired
    private CustomerStatisticsMapper customerStatisticsMapper;

    @Autowired
    private CustomerBaseStatisticsMapper customerBaseStatisticsMapper;

    @Autowired
    private RopCommonServie ropCommonServie;

    @Autowired
    private MerchantService merchantService;

    /**
     * // 获取昨日天统计的潜在,购买客户数
     * // 1.客户分层
     * // 查询昨日的客户统计(获取昨日客户总数)   昨日占比: 昨日统计潜在/昨日客户总数,昨日统计购买客户数/昨日客户总数
     * // 今日购买客户占比
     *
     * @param datalist 商户
     * @return
     */
    public CustomerDataViewResponse customerDataViewActual(List<Integer> datalist) {
        CustomerDataViewResponse response = new CustomerDataViewResponse();
        if (CollectionUtils.isEmpty(datalist)) {
            log.info("customerDataViewActual===datalist为空");
            return response;
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        //获取今日客户分层,客户分群的标签统计数据
        String joinMerchantIds = StringUtils.join(datalist, ",");
        CustomerDataViewRopResponse customerDataView = ropCommonServie.getCustomerDataView(joinMerchantIds);
        //潜在(意向)客户
        int purposeCustomerCountRop = customerDataView.getPurposeCustomerCount()  == null ? 0 : customerDataView.getPurposeCustomerCount();
        //已加企微,待匹配客户数
        int waitMatchCustomerAddCountRop = customerDataView.getWaitMatchCustomerAddCount() == null ? 0 :customerDataView.getWaitMatchCustomerAddCount();
        //基盘客户数
        int purchaseCustomerCountRop =  customerDataView.getPurchaseCustomerCount() == null ? 0 : customerDataView.getPurchaseCustomerCount();
        //已加企微潜在(意向)客户
        int purposeCustomerAddCount = customerDataView.getPurposeCustomerAddCount() == null ? 0 : customerDataView.getPurposeCustomerAddCount();
        //已加企微购买(存档)客户
        int purchaseCustomerAddCount = customerDataView.getPurchaseCustomerAddCount() == null ? 0 :customerDataView.getPurchaseCustomerAddCount();
        //未加企微未匹配客户数
        int notMatchCustomerNAddCount = customerDataView.getNotMatchCustomerNAddCount() == null ? 0 : customerDataView.getNotMatchCustomerNAddCount();

        //客户总数=基盘客户数+潜在意向客户数+已加企微,待匹配客户+未加企微未匹配客户
        int customerCount = purposeCustomerCountRop + waitMatchCustomerAddCountRop + purchaseCustomerCountRop + notMatchCustomerNAddCount;
        response.setCustomerCount(customerCount);
        //已加企微=基盘已加企微数+潜在已加企微数+已加企微,待匹配客户
        int entmicroAddCustomerCount = purchaseCustomerAddCount + purposeCustomerAddCount + waitMatchCustomerAddCountRop;
        response.setEntmicroAddCustomerCount(entmicroAddCustomerCount);
        // 未加企微客户
        response.setEntmicroNotAddCustomerCount(customerCount - entmicroAddCustomerCount);
        boolean isValid = customerCount != 0;
        response.setPercentValid(isValid);

        log.info("dataview===joinMerchantIds:{},customerDataView:{}", joinMerchantIds, customerDataView);
        BeanUtils.copyProperties(customerDataView, response);
        stopWatch.stop();
        log.debug("获取客户数据概览耗时:" + stopWatch.getTime() + " ms");

        //昨日购买客户数 昨日潜在客户数
        int yesterdayCustomerPurchaseCount = customerDataView.getPurchaseCustomerYdayCount();
        int yesterdayCustomerPurposeCount = customerDataView.getPurposeCustomerYdayCount();
        //昨日已加企微,待匹配客户数
        Integer yesterdayCustomerWaitMatchCount = customerDataView.getWaitMatchCustomerAddYdayCount();
        //昨日未加企微未匹配数
        Integer notMatchCustomerNAddYdayCount = customerDataView.getNotMatchCustomerNAddYdayCount();
        int yesterdayNotMatchCustomerCount = notMatchCustomerNAddYdayCount == null ? 0 : notMatchCustomerNAddYdayCount;

        //查询昨日总客户数据
        Date date = DateUtils.addDays(new Date(), -1);
        String yesterDay = DateUtils.format(date, "yyyy/MM/dd");
        //昨日客户总数
        int customerCountYesTerday = customerStatisticsMapper.getCustomerCountActual(datalist, yesterDay);
        //昨日购买客户占比
        double yesterdayPurchasePercent = 0;
        //昨日潜在客户占比
        double yesterdayPurposePercent = 0;
        //昨日已加企微,待匹配客户占比
        double yesterdayWaitMatchPercent = 0;
        //昨日未加企微未匹配客户占比
        double yesterdayNotMatchPercent = 0;
        //校验昨日总数分母
        if (customerCountYesTerday != 0) {
            yesterdayPurchasePercent = yesterdayCustomerPurchaseCount * 1.0 / customerCountYesTerday;
            yesterdayPurposePercent = yesterdayCustomerPurposeCount * 1.0 / customerCountYesTerday;
            yesterdayWaitMatchPercent = yesterdayCustomerWaitMatchCount * 1.0 / customerCountYesTerday;
            yesterdayNotMatchPercent = yesterdayNotMatchCustomerCount * 1.0 / customerCountYesTerday;
        }

        //今日潜在意向客户
        Integer purposeCustomerCount = response.getPurposeCustomerCount();
        //今日已加企微,待匹配客户
        Integer waitMatchCustomerAddCount = response.getWaitMatchCustomerAddCount();
        //今日潜在意向客户占比
        double todayPurposePercent = 0;
        //今日已加企微,待匹配客户占比
        double todayWaitMatchPercent = 0;
        //今日未加企微未匹配客户占比
        double todayNotMatchPercent = 0;
        //校验分母合法性
        if (isValid) {
            todayPurposePercent = purposeCustomerCount * 1.0 / customerCount;
            response.setPurposePercent(todayPurposePercent);
            todayWaitMatchPercent = (waitMatchCustomerAddCount * 1.0 / customerCount) * 100;
            response.setWaitMatchPercent(todayWaitMatchPercent);
            todayNotMatchPercent = (notMatchCustomerNAddCount * 1.0 / customerCount);
            response.setNotMatchCustomerNAddPercent(todayNotMatchPercent);
        } else {
            response.setPercentValid(false);
            response.setPurposePercent(0);
            response.setWaitMatchPercent(0.0);
            response.setNotMatchCustomerNAddPercent(0.0);
        }

        //今日购买存档客户
        Integer purchaseCustomerCount = response.getPurchaseCustomerCount();
        //今日购买占比
        double todayPurchasePercent = 0;
        //校验分母合法性
        if (isValid) {
            //占比
            todayPurchasePercent = purchaseCustomerCount * 1.0 / customerCount;
            //今日占比-昨日占比/昨日占比
            response.setPurchasePercent(todayPurchasePercent);
        } else {
            response.setPercentValid(false);
            response.setPurchasePercent(0);
        }
        log.info("今日客户总数:{}, 今日购买客户数: {}, 今日潜在客户数: {}", customerCount, purchaseCustomerCount, purposeCustomerCount);
        log.info("今日购买占比:{}, 今日潜在占比:{}", todayPurchasePercent, todayPurposePercent);
        //环比
        int purchaseUp = Constants.IS_STAY;
        double purchaseBefore = yesterdayPurchasePercent;
        if (todayPurchasePercent > purchaseBefore) {
            purchaseUp = Constants.IS_UP;
        } else if (todayPurchasePercent < purchaseBefore) {
            purchaseUp = Constants.IS_DOWN;
        } else if (todayPurchasePercent == purchaseBefore) {
            purchaseUp = Constants.IS_STAY;
        }
        response.setPurchaseUp(purchaseUp);
        //环比
        int purposeUp = Constants.IS_STAY;
        double purposePercent = yesterdayPurposePercent;
        if (todayPurposePercent > purposePercent) {
            purposeUp = Constants.IS_UP;
        } else if (todayPurposePercent < purposePercent) {
            purposeUp = Constants.IS_DOWN;
        } else if (todayPurposePercent == purposePercent) {
            purposeUp = Constants.IS_STAY;
        }
        response.setPurposeUp(purposeUp);
        //已加企微,待匹配客户占比
        int waitMatchUp = Constants.IS_STAY;
        if (todayWaitMatchPercent > yesterdayWaitMatchPercent){
            waitMatchUp = Constants.IS_UP;
        } else if (todayWaitMatchPercent < yesterdayWaitMatchPercent) {
            waitMatchUp = Constants.IS_DOWN;
        }
        response.setWaitMatchUp(waitMatchUp);

        //未加企微未匹配客户占比
        Integer notMatchUp = Constants.IS_STAY;
        if (todayNotMatchPercent > yesterdayNotMatchPercent){
            notMatchUp = Constants.IS_UP;
        } else if (todayNotMatchPercent < yesterdayNotMatchPercent) {
            notMatchUp = Constants.IS_DOWN;
        }
        response.setNotMatchUp(notMatchUp);

        if (purposeCustomerCount != null && purposeCustomerCount != 0){
            //潜在意向已加企微客户占比
            response.setPurposeCustomerAddPercent(response.getPurposeCustomerAddCount() * 1.0 / purposeCustomerCount);
            //潜在意向未加企微客户占比
            response.setPurposeCustomerNAddPercent(response.getPurposeCustomerNAddCount() * 1.0 / purposeCustomerCount);
        }

        if (purchaseCustomerCount != null && purchaseCustomerCount != 0){
            //基盘已加企微客户占比
            response.setPurchaseCustomerAddPercent(response.getPurchaseCustomerAddCount() * 1.0 / purchaseCustomerCount);
            //基盘未加企微客户占比
            response.setPurchaseCustomerNAddPercent(response.getPurchaseCustomerNAddCount() * 1.0 / purchaseCustomerCount);
        }

        log.info("客户数据概览查询,res:{}", response);
        return response;
    }

    /**
     * 客户管理-客户统计柱状图查询(1-2)
     */
    public CustomerChartResponse customerChart(Integer dayNum, List<Integer> merchantIds) {
        log.info("客户统计柱状图查询");
        //3.客户增长趋势
        CustomerChartResponse response = new CustomerChartResponse();
        //日均新增客户
        int dayAvergGrow = 0;
        //日均新增企微客户
        int entmicroDayAvergGrow = 0;
        //客户
        int customerCount = 0;
        //企微客户
        int entmicroCustomerCount = 0;
        //区间数据 (7/30 +1天数据),取多一天计算环比
        List<String> dates = DateUtil.getDates(dayNum + 1, true);
        CustomerStaticRequest customerStaticRequest = new CustomerStaticRequest(merchantIds);
        customerStaticRequest.setEndTime(dates.get(0));
        customerStaticRequest.setStartTime(dates.get(dates.size() - 1));
        List<CustomerStatisticModel> customerStatistic = customerStatisticsMapper.findCustomerStatistic(customerStaticRequest);
        if (!CollectionUtils.isEmpty(customerStatistic)) {
            //去掉开始时间多算的一天
            List<CustomerStatisticModel> collect = customerStatistic.stream().filter(index -> !index.getCreateTime().equals(customerStaticRequest.getStartTime())).collect(Collectors.toList());
            customerCount = collect.size();
            //已加企微客户数
            long count = collect.stream().filter(index -> index.getUserId() != null && index.getFlag() == 0).count();
            entmicroCustomerCount = (int) count;
        }
        Map<String, ChartDayResponse> daysDataMap = getDaysDataByMerchantIds(dates, merchantIds);

        List<ChartDayResponse> dayDatas = new ArrayList<>(daysDataMap.values());
        Collections.sort(dayDatas);
        for (int i = 1; i < dayDatas.size(); i++) {
            //昨天
            ChartDayResponse yesterdayData = dayDatas.get(i - 1);
            int newCustomerCountYesterday = yesterdayData.getNewCustomerCount();
            int newEntmicroCountYesterday = yesterdayData.getNewEntmicroCount();
            //今天
            ChartDayResponse todayData = dayDatas.get(i);
            int newCustomerCount = todayData.getNewCustomerCount();
            int newEntmicroCount = todayData.getNewEntmicroCount();
            //客户环比
            double custRatio;
            boolean custRatioValid = true;
            if (newCustomerCountYesterday == 0) {
                custRatioValid = false;
                custRatio = 0;
            } else {
                BigDecimal b = new BigDecimal((newCustomerCount - newCustomerCountYesterday) * 1.0 / newCustomerCountYesterday);
                custRatio = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            todayData.setCustomerRatio(custRatio);
            //企微客户环比
            double entmicroCustRatio;
            boolean entmicroCustRatioValid = true;
            if (newEntmicroCountYesterday == 0) {
                entmicroCustRatioValid = false;
                entmicroCustRatio = 0;
            } else {
                BigDecimal b = new BigDecimal((newEntmicroCount - newEntmicroCountYesterday) * 1.0 / newEntmicroCountYesterday);
                entmicroCustRatio = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            todayData.setEntmicroRatio(entmicroCustRatio);
        }
        dayAvergGrow = (int) Math.ceil((customerCount * 1.0) / dayNum);
        entmicroDayAvergGrow = (int) Math.ceil((entmicroCustomerCount * 1.0) / dayNum);
        //排序
        List<ChartDayResponse> customerGrowthTrends = dayDatas.subList(1, dayNum + 1);

        //客户数
        response.setCustomerCount(customerCount);

        //日均新增
        response.setDayAvergGrow(dayAvergGrow);

        //企微客户数
        response.setEntmicroCustomerCount(entmicroCustomerCount);

        //企微日均新增
        response.setEntmicroDayAvergGrow(entmicroDayAvergGrow);

        //区间数据 (7/30天数据)
        response.setCustomerGrowthTrends(customerGrowthTrends);

        return response;
    }

    /**
     * 客户数据概览趋势图
     * @param dates
     * @param merchantIds
     * @return
     */
    private Map<String, ChartDayResponse> getDaysDataByMerchantIds(List<String> dates, List<Integer> merchantIds) {
        Map<String, ChartDayResponse> stringChartDayResponseMap = new HashMap<>();
        Map<String, Map> daysAddCountDataByMerchantIds = customerStatisticsMapper.getDaysAddCountDataByMerchantIds(dates, merchantIds);
        Map<String, Map> daysAddEntCountDataByMerchantIds = customerStatisticsMapper.getDaysAddEntCountDataByMerchantIds(dates, merchantIds);
        dates.forEach(index -> {
            ChartDayResponse chartDayResponse = new ChartDayResponse();
            chartDayResponse.setDateTime(index);
            Map map = daysAddCountDataByMerchantIds.get(index);
            if (map != null) {
                chartDayResponse.setNewCustomerCount(Math.toIntExact((Long) map.get("customerCount")));
            }
            Map map1 = daysAddEntCountDataByMerchantIds.get(index);
            if (map1 != null) {
                chartDayResponse.setNewEntmicroCount(Math.toIntExact((Long) map1.get("customerCount")));
            }
            stringChartDayResponseMap.put(index, chartDayResponse);
        });
        return stringChartDayResponseMap;
    }


    /**************************************  嘀加SCRM运营平台-首页-概览(客户)  **************************************/
    /**
     * 汇总数据查询(商户登录)
     */
    public ShopCollectViewResponse getShopCollectView(Date date, List<Integer> merchantIds) {
        if (CollectionUtils.isEmpty(merchantIds)) {
            return new ShopCollectViewResponse();
        }
        return customerStatisticsMapper.getShopCollectViewByMerchantIds(date, merchantIds);
    }

    /**
     * 实时汇总数据查询(商户登录)
     */
    public ShopCollectViewResponse getShopCollectViewActual(Date date, List<Integer> merchantIds) {
        ShopCollectViewResponse response = new ShopCollectViewResponse();
        if (CollectionUtils.isEmpty(merchantIds)) {
            return new ShopCollectViewResponse();
        }
        String dateTime = DateUtils.format(date, "yyyy/MM/dd");
        String yesToday = DateUtils.format(DateUtils.addDateDays(date, -1), "yyyy/MM/dd");
        //累计客户总数(魔方客户+已加员工客户)
        int customerCount = customerStatisticsMapper.getCustomerCountActual(merchantIds, dateTime);
        response.setCustomerCount(customerCount);
        //当天新增客户总数
        int newCustomerCount = customerStatisticsMapper.getCustomerDateTimeCountActual(merchantIds, dateTime);
        int yesterdayCount = customerStatisticsMapper.getCustomerDateTimeCountActual(merchantIds, yesToday);
        //当天新增客户日环比
        response.setTotalCountDayToDayRadio(CalculateUtils.dayToday(yesterdayCount, newCustomerCount));
        response.setNewCustomerCount(newCustomerCount);

        //累计已加企微(已加企微员工客户)
        int addEntmicroCount = customerStatisticsMapper.getEntmicroCustomerCountActual(merchantIds, dateTime);
        //今日已加企微
        int todayAddEntmicroCount = customerStatisticsMapper.getEntmicroCustomerDayTimeCountActual(merchantIds, dateTime);
        //昨日已加企微
        int yesAddEntmicroCount = customerStatisticsMapper.getEntmicroCustomerDayTimeCountActual(merchantIds, yesToday);
        //当天已加企微日环比
        response.setEntmicroCountDayToDayRadio(CalculateUtils.dayToday(yesAddEntmicroCount, todayAddEntmicroCount));
        //企微客户占客户总数比
        response.setEntmicroCountRadio(CalculateUtils.radio(addEntmicroCount, customerCount));
        //企微客户总数
        response.setAddEntmicroCount(addEntmicroCount);

        //未加企微 (客户总数-已加客户数)
        int notAddEntmicroCount = customerCount - addEntmicroCount;
        response.setNotAddEntmicroCount(notAddEntmicroCount);
        //企微客户数-当日新增
        response.setNewEntmicroCount(todayAddEntmicroCount);

        //企微流失总数
        int entmicroLoseCount = customerStatisticsMapper.getLostCustomerCountActual(merchantIds, dateTime);
        response.setEntmicroLoseCount(entmicroLoseCount);
        //当日企微流失总数
        int todayEntmicroLoseCount = customerStatisticsMapper.getLostCustomerDateTimeCountActual(merchantIds, dateTime);
        //昨日流失数
        int yesEntmicroLoseCount = customerStatisticsMapper.getLostCustomerDateTimeCountActual(merchantIds, yesToday);
        //流失日占比 今日流失数/昨日流失数
        response.setLostCountDayToDayRadio(CalculateUtils.dayToday(yesEntmicroLoseCount, todayEntmicroLoseCount));
        response.setTodayEntmicroLoseCount(todayEntmicroLoseCount);
        return response;
    }

    /**
     * 汇总数据查询(门店登录)
     */
    public StoreCollectViewResponse getStoreCollectView(Date dateEnd, List<Integer> merchantIds) {
        StoreCollectViewResponse response = new StoreCollectViewResponse();
        if (CollectionUtils.isEmpty(merchantIds)) {
            return response;
        }


        ShopCollectViewResponse resData = getShopCollectViewActual(dateEnd, merchantIds);
        log.info("getStoreCollectView====merchantIds:{},resData:{}", merchantIds, resData);

        if (null != resData) {
            response.setCustomerCount(resData.getCustomerCount());
            response.setNewCustomerCount(resData.getNewCustomerCount());
            response.setNewEntmicroCount(resData.getNewEntmicroCount());
            response.setTodayEntmicroLoseCount(resData.getTodayEntmicroLoseCount());
            response.setAddEntmicroCount(resData.getAddEntmicroCount());
            response.setNotAddEntmicroCount(resData.getNotAddEntmicroCount());
            response.setEntmicroLoseCount(resData.getEntmicroLoseCount());
        }

        //当日群成员总数
        StoreCollectViewResponse packmenberData = customerBaseStatisticsMapper.getBaseCusAllList(dateEnd, merchantIds);
        //查询当日新增群成员
        StoreCollectViewResponse addBaseCusList = customerBaseStatisticsMapper.getAddBaseCusList(dateEnd, merchantIds);
        //查询昨日新增群成员
        StoreCollectViewResponse yesterdayCusList = customerBaseStatisticsMapper.getAddBaseCusList(DateUtils.addDateDays(dateEnd, -1), merchantIds);
        if (null != packmenberData && null != addBaseCusList) {
            response.setPackmenberCount(packmenberData.getPackmenberCount());
            response.setTodayAddPackmenberCount(addBaseCusList.getTodayAddPackmenberCount());
        }
        //群当日新增客户-日环比
        response.setGroupCustCountDayToDayRadio(CalculateUtils.dayToday(yesterdayCusList.getTodayAddPackmenberCount(), addBaseCusList.getTodayAddPackmenberCount()));
        return response;
    }

    /**
     * 汇总数据查询(门店登录)
     */
    public StoreCollectViewResponse getStoreCollectViewActual(Date dateEnd, List<Integer> merchantIds) {
        StoreCollectViewResponse response = new StoreCollectViewResponse();
        if (CollectionUtils.isEmpty(merchantIds)) {
            return response;
        }

        ShopCollectViewResponse resData = getShopCollectViewActual(dateEnd, merchantIds);
        log.info("getStoreCollectView====merchantIds:{},resData:{}", merchantIds, resData);

        if (null != resData) {
            response.setCustomerCount(resData.getCustomerCount());
            response.setNewCustomerCount(resData.getNewCustomerCount());
            response.setNewEntmicroCount(resData.getNewEntmicroCount());
            response.setTodayEntmicroLoseCount(resData.getTodayEntmicroLoseCount());
            response.setAddEntmicroCount(resData.getAddEntmicroCount());
            response.setNotAddEntmicroCount(resData.getNotAddEntmicroCount());
            response.setEntmicroLoseCount(resData.getEntmicroLoseCount());
            response.setEntmicroCountDayToDayRadio(resData.getEntmicroCountDayToDayRadio());
            response.setLostCountDayToDayRadio(resData.getLostCountDayToDayRadio());
            response.setTotalCountDayToDayRadio(resData.getTotalCountDayToDayRadio());
            response.setEntmicroCountRadio(resData.getEntmicroCountRadio());
        }


        //当日群成员总数
        StoreCollectViewResponse packmenberData = customerBaseStatisticsMapper.getBaseCusAllList(dateEnd, merchantIds);
        //查询当日新增群成员
        StoreCollectViewResponse addBaseCusList = customerBaseStatisticsMapper.getAddBaseCusList(dateEnd, merchantIds);
        //查询昨日新增群成员
        StoreCollectViewResponse yesterdayCusList = customerBaseStatisticsMapper.getAddBaseCusList(DateUtils.addDateDays(dateEnd, -1), merchantIds);
        if (null != packmenberData && null != addBaseCusList) {
            response.setPackmenberCount(packmenberData.getPackmenberCount());
            response.setTodayAddPackmenberCount(addBaseCusList.getTodayAddPackmenberCount());
        }
        //群当日新增客户-日环比
        response.setGroupCustCountDayToDayRadio(CalculateUtils.dayToday(yesterdayCusList.getTodayAddPackmenberCount(), addBaseCusList.getTodayAddPackmenberCount()));
        return response;
    }

    /**
     * 商户登录——折线图(1-2)
     */
    public ShopLineChartResponse getShopLineChart(Date dateEnd, Integer day, List<Integer> merchantIds) {
        ShopLineChartResponse response = new ShopLineChartResponse();

        if (CollectionUtils.isEmpty(merchantIds)) {
            return null;
        }

        //区间数据 ,取多一天计算环比
        List<String> dates = DateUtil.getDates(dateEnd, day + 1);

        //区间数据月份
        Set<String> months = DateUtil.getMonths(day);

        Map<String, LineChartMonthResponse> monthsMap = getCustMonthsCount(merchantIds, months);


        // 求月均值
        if (null != monthsMap) {
            Set<Map.Entry<String, LineChartMonthResponse>> entries = monthsMap.entrySet();

            if (!CollectionUtils.isEmpty(entries)) {
                entries.stream().forEach(entry -> {
                    String date = entry.getKey();
                    LineChartMonthResponse value = entry.getValue();
                    int customerCount = value.getCustomerCount();
                    int customerEntmicroCount = value.getCustomerEntmicroCount();
                    int customerLoseCount = value.getCustomerLoseCount();

                    Integer monthDays = DateUtil.getMonthDays(date);
                    value.setMonthCustAddAverg((int) Math.round(customerCount * 1.0 / monthDays));
                    value.setMonthEntmicroAddAverg((int) Math.round(customerEntmicroCount * 1.0 / monthDays));
                    value.setMonthCustLoseAverg((int) Math.round(customerLoseCount * 1.0 / monthDays));
                });
            }
        }

        //日区间数据
        Map<String, ShopLineChart> lineChartMap = getShopLineChartByMerchantIds(dates, merchantIds);

        monthsMap.entrySet().stream().forEach(System.out::println);
        //每日新增客户 区间数据
        List<ShopLineCust> custAddList = new ArrayList<>();

        //每日流失客户 区间数据
        List<ShopLineCust> custLoseList = new ArrayList<>();

        //每日新增企微客户 区间数据
        List<ShopLineCust> custEntmicroAdds = new ArrayList<>();

        //映射<date,ChartDayResponse>,初始化数据,每日为0
        Map<String, ShopLineChart> dataMap = new HashMap<>();
        for (String dateStr : dates) {
            if (null != lineChartMap && lineChartMap.containsKey(dateStr)) {
                ShopLineChart shopLineChart = lineChartMap.get(dateStr);
                shopLineChart.setDateTime(dateStr);
                dataMap.put(dateStr, shopLineChart);
                continue;
            }
            ShopLineChart res = new ShopLineChart();
            res.setDateTime(dateStr);
            dataMap.put(dateStr, res);
        }

        List<ShopLineChart> dayDatas = new ArrayList(dataMap.values());

        Collections.sort(dayDatas);

        for (int i = 1; i < dayDatas.size(); i++) {
            ShopLineCust custAdd = new ShopLineCust();
            ShopLineCust custEntmicroAdd = new ShopLineCust();
            ShopLineCust custLose = new ShopLineCust();

            //前天
            ShopLineChart beforyesterdayData = dayDatas.get(i - 1);
            //客户
            int customerCountBefore = beforyesterdayData.getNewCustomerCount();
            //企微客户
            int customerEntmicroCountBefore = beforyesterdayData.getNewEntmicroCustomerCount();
            //流失客户
            int customerLoseCountBefore = beforyesterdayData.getTodayEntmicroLoseCount();

            //昨天
            ShopLineChart yesterdayData = dayDatas.get(i);
            String dateTime = yesterdayData.getDateTime();

            //客户
            int customerCountYesterday = yesterdayData.getNewCustomerCount();
            //企微客户
            int customerEntmicroCountYesterday = yesterdayData.getNewEntmicroCustomerCount();
            //流失客户
            int customerLoseCountYesterday = yesterdayData.getTodayEntmicroLoseCount();

            //增长数
            int subCustCount = customerCountYesterday - customerCountBefore;
            int subEntmicroCount = customerEntmicroCountYesterday - customerEntmicroCountBefore;
            int subLoseCount = customerLoseCountYesterday - customerLoseCountBefore;

            int index = dateTime.lastIndexOf("/");
            String subDate = dateTime.substring(0, index);


            //月平均值
            if (monthsMap.containsKey(subDate)) {
                LineChartMonthResponse lineChartMonthResponse = monthsMap.get(subDate);
                custAdd.setMonthAverg(lineChartMonthResponse.getMonthCustAddAverg());
                custEntmicroAdd.setMonthAverg(lineChartMonthResponse.getMonthEntmicroAddAverg());
                custLose.setMonthAverg(lineChartMonthResponse.getMonthCustLoseAverg());
            }
            //客户数
            custAdd.setCustomerCount(customerCountYesterday);
            //日期
            custAdd.setDateTime(dateTime);
            //环比趋势
            custAdd.setRatio(subCustCount > 0 ? 1 : 0);
            custAddList.add(custAdd);

            custEntmicroAdd.setCustomerCount(customerEntmicroCountYesterday);
            custEntmicroAdd.setDateTime(dateTime);
            custEntmicroAdd.setRatio(subEntmicroCount > 0 ? 1 : 0);
            custEntmicroAdds.add(custEntmicroAdd);

            custLose.setCustomerCount(customerLoseCountYesterday);
            custLose.setDateTime(dateTime);
            custLose.setRatio(subLoseCount > 0 ? 1 : 0);
            custLoseList.add(custLose);
        }

        response.setCustAddList(custAddList);

        response.setCustEntmicroAdds(custEntmicroAdds);

        response.setCustLoseList(custLoseList);
        return response;
    }

    private Map<String, LineChartMonthResponse> getCustMonthsCount(List<Integer> merchantIds, Set<String> months) {
        Map<String, Map> daysAddCountDataByMerchantIds = customerStatisticsMapper.getMonAddCountDataByMerchantIds(months, merchantIds);
        Map<String, Map> daysAddEntCountDataByMerchantIds = customerStatisticsMapper.getMonAddEntCountDataByMerchantIds(months, merchantIds);
        Map<String, Map> daysLostEntCountDataByMerchantIds = customerStatisticsMapper.getMonLostEntCountDataByMerchantIds(months, merchantIds);
        Map<String, LineChartMonthResponse> stringShopLineChartMap = new HashMap<>();
        months.forEach(index -> {
            LineChartMonthResponse shopLineChart = new LineChartMonthResponse();
            Map map = daysAddCountDataByMerchantIds.get(index);
            if (map != null) {
                shopLineChart.setCustomerCount(Math.toIntExact((Long) map.get("customerCount")));
            }
            Map map1 = daysAddEntCountDataByMerchantIds.get(index);
            if (map1 != null) {
                shopLineChart.setCustomerEntmicroCount(Math.toIntExact((Long) map1.get("customerCount")));
            }
            Map map2 = daysLostEntCountDataByMerchantIds.get(index);
            if (map2 != null) {
                shopLineChart.setCustomerLoseCount(Math.toIntExact((Long) map2.get("customerCount")));
            }
            shopLineChart.setDateTime(index);
            stringShopLineChartMap.put(index, shopLineChart);
        });
        return stringShopLineChartMap;
    }

    public Map<String, ShopLineChart> getShopLineChartByMerchantIds(List<String> dates, List<Integer> merchantIds) {
        Map<String, Map> daysAddCountDataByMerchantIds = customerStatisticsMapper.getDaysAddCountDataByMerchantIds(dates, merchantIds);
        Map<String, Map> daysAddEntCountDataByMerchantIds = customerStatisticsMapper.getDaysAddEntCountDataByMerchantIds(dates, merchantIds);
        Map<String, Map> daysLostEntCountDataByMerchantIds = customerStatisticsMapper.getDaysLostEntCountDataByMerchantIds(dates, merchantIds);
        Map<String, ShopLineChart> stringShopLineChartMap = new HashMap<>();
        dates.forEach(index -> {
            ShopLineChart shopLineChart = new ShopLineChart();
            Map map = daysAddCountDataByMerchantIds.get(index);
            if (map != null) {
                shopLineChart.setNewCustomerCount(Math.toIntExact((Long) map.get("customerCount")));
            }
            Map map1 = daysAddEntCountDataByMerchantIds.get(index);
            if (map1 != null) {
                shopLineChart.setNewEntmicroCustomerCount(Math.toIntExact((Long) map1.get("customerCount")));
            }
            Map map2 = daysLostEntCountDataByMerchantIds.get(index);
            if (map2 != null) {
                shopLineChart.setTodayEntmicroLoseCount(Math.toIntExact((Long) map2.get("customerCount")));
            }
            shopLineChart.setDateTime(index);
            stringShopLineChartMap.put(index, shopLineChart);
        });
        return stringShopLineChartMap;
    }

    /**
     * 商户登录——门店企微客户排行(1-3)
     */
    public ShopCustSortResponse getShopCustSort(Integer merchantId, Integer sortType, List<Integer> datalist) {
        ShopCustSortResponse res = new ShopCustSortResponse();

        List<MerchantRopResponse> merchantNotEntmicro = merchantService.findShopMerchant(merchantId);

        if (CollectionUtils.isEmpty(merchantNotEntmicro)) {
            return res;
        }
        List<MerchantRopResponse> collect = merchantNotEntmicro.stream().filter(index -> datalist.contains(index.getMerchantNo())).collect(Collectors.toList());
        Map<Integer, ShopCustSort> merchantMap = new HashMap<>();
        for (MerchantRopResponse merchantRopResponse : collect) {
            Integer merchantNo = merchantRopResponse.getMerchantNo();
            String merchantName = merchantRopResponse.getMerchantName();
            ShopCustSort custSort = new ShopCustSort();
            custSort.setMerchantId(merchantNo);
            custSort.setShopName(merchantName);
            merchantMap.put(merchantNo, custSort);
        }

        List<Integer> merchantIds = new ArrayList<>(merchantMap.keySet());

        List<ShopCustSort> shopSorts = getShopCustSortByTypeActual(merchantIds, sortType);


        int total = 0;
        if (!CollectionUtils.isEmpty(shopSorts)) {
            //门店名称
            for (int i = 1; i <= shopSorts.size(); i++) {
                ShopCustSort shopSort = shopSorts.get(i - 1);
                Integer storeMerchantid = shopSort.getMerchantId();
                if (!merchantMap.containsKey(storeMerchantid)) {
                    continue;
                }
                ShopCustSort custSort = merchantMap.get(storeMerchantid);
                int custCount = shopSort.getCustCount();
                custSort.setCustCount(custCount);
                merchantMap.put(storeMerchantid, custSort);
                total += custCount;
            }
            int averg = (int) (total * 1.0 / merchantMap.size());
            res.setCustAvergCount(averg);
        }

        shopSorts = new ArrayList<>(merchantMap.values());
        if (!CollectionUtils.isEmpty(shopSorts)) {
            Collections.sort(shopSorts);
        }
        res.setCustSortList(shopSorts);

        return res;
    }

    private List<ShopCustSort> getShopCustSortByType(List<Integer> merchantIds, Integer sortType) {
        //门店企微客户数排行类型   1:累计新增  2:昨日新增  3:累计流失
        List<ShopCustSort> shopSorts = new ArrayList<>();
        if (sortType == 1) {
            shopSorts = customerStatisticsMapper.getShopCustSortAdd(merchantIds);
        } else if (sortType == 2) {
            shopSorts = customerStatisticsMapper.getShopCustSortYesterAdd(merchantIds);
        } else if (sortType == 3) {
            shopSorts = customerStatisticsMapper.getShopCustSortLose(merchantIds);
        }
        return shopSorts;
    }

    private List<ShopCustSort> getShopCustSortByTypeActual(List<Integer> merchantIds, Integer sortType) {
        //门店企微客户数排行类型   1:累计新增  2:昨日新增  3:累计流失
        List<ShopCustSort> shopSorts = new ArrayList<>();
        String dateTime = DateUtils.format(new Date(), "yyyy/MM/dd");
        if (sortType == 1) {
            shopSorts = customerStatisticsMapper.getShopCustSortAddActual(merchantIds, dateTime);
        } else if (sortType == 2) {
            shopSorts = customerStatisticsMapper.getShopCustSortDayAddActual(merchantIds, dateTime);
        } else if (sortType == 3) {
            shopSorts = customerStatisticsMapper.getShopCustSortLoseActual(merchantIds, dateTime);
        }
        return shopSorts;
    }


    /************************************** 客户数据统计 **************************************/
    // 统计客户的数据
    @Async("taskExecutor")
    public void customerStatisticsSync(List<Integer> datalist) {
        customerStatistics(datalist);
    }

    // 统计客户的数据
    public void customerStatistics(List<Integer> datalist) {
        if (CollectionUtils.isEmpty(datalist)) {
            log.info("customerStatistics===datalist为空");
            return;
        }
        // 取客戶的最小日期
        String minDay = customerStatisticsMapper.getCreateCustomerMinDay(datalist);
        List<Integer> first = customerStatisticsMapper.findFirst(minDay, datalist);
        List<String> dates = new ArrayList<>();
        if (CollectionUtils.isEmpty(first) && StringUtils.isNotEmpty(minDay)) {
            log.info("最小日期为{}", minDay);
            dates = DateUtil.getAllDates(minDay);
        } else {
            dates = DateUtil.getAllDates(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
        }

/*        //如果日期不存在才统计
        List<String> dateExists = customerStatisticsMapper.getExistDates(datalist);
        if(!CollectionUtils.isEmpty(dateExists)){
            dates = dates.stream().filter(date-> !dateExists.contains(date)).collect(Collectors.toList());
        }*/

        log.info("customerStatistics===dates:{},datalist:{}", dates, datalist);

        if (CollectionUtils.isEmpty(dates)) {
            return;
        }

        dates.forEach(index -> {
            //今日
            String dateStr = index;
            Date date = DateUtils.stringToDate(dateStr, "yyyy/MM/dd");
            //昨日
            String yesterDay = new SimpleDateFormat("yyyy/MM/dd").format(DateUtils.addDays(date, -1));

            Map<Integer, CustomerStatistics> resMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(datalist)) {
                datalist.stream().forEach(merchantId -> {
                    if (!resMap.containsKey(merchantId)) {
                        CustomerStatistics statistics = new CustomerStatistics();
                        statistics.setMerchantId(merchantId);
                        statistics.setStatisticsDate(dateStr);
                        resMap.put(merchantId, statistics);
                    }
                });
            }

            log.info("customerStatistics===initData:{},datalist:{}", JSONObject.toJSONString(resMap), datalist);

            //客户
            Map<Integer, CustomerStatistics> customerBeforeYesterDayCount = customerStatisticsMapper.getCustomerBeforeYesterDayCount(datalist, yesterDay);
            if (null != customerBeforeYesterDayCount && customerBeforeYesterDayCount.size() > 0) {
                customerBeforeYesterDayCount.forEach((key, value) -> {
                    value.setStatisticsDate(dateStr);
                    resMap.put(key, value);
                });
            }

            Map<Integer, CustomerStatistics> customeYesterDayCount = customerStatisticsMapper.getCustomeYesterDayCount(datalist, dateStr);
            if (null != customeYesterDayCount && customeYesterDayCount.size() > 0) {
                customeYesterDayCount.forEach((key, value) -> {

                    if (resMap.containsKey(key)) {
                        //已存在商户,昨日有新增
                        CustomerStatistics beforeCustomer = resMap.get(key);
                        int beforeCustomerCount = beforeCustomer.getCustomerCount();
                        int addCustomerCount = value.getCustomerCount();
                        //新增数
                        beforeCustomer.setNewCustomerCount(addCustomerCount);
                        //总数
                        int totalCustCount = beforeCustomerCount + addCustomerCount;
                        beforeCustomer.setCustomerCount(totalCustCount);
                        //环比
                        double ratio;
                        if (beforeCustomerCount == 0) {
                            ratio = 100;
                        } else {
                            ratio = (addCustomerCount * 1.0 / beforeCustomerCount) * 100;
                        }
                        beforeCustomer.setCustomerRatio(ratio);
                        resMap.put(key, beforeCustomer);
                    } else {
                        //未存在商户,昨日有新增

                        //总数
                        int beforeCustomerCount = value.getCustomerCount();
                        //新增数
                        value.setNewCustomerCount(beforeCustomerCount);
                        //环比
                        double ratio = 100;
                        value.setCustomerRatio(ratio);
                        value.setStatisticsDate(dateStr);
                        resMap.put(key, value);
                    }
                });
            }
            //企微客户
            Map<Integer, CustomerStatistics> entmicroCustomerBeforeYesterDayCount = customerStatisticsMapper.getEntmicroCustomerBeforeYesterDayCount(datalist, yesterDay);
            if (null != entmicroCustomerBeforeYesterDayCount && entmicroCustomerBeforeYesterDayCount.size() > 0) {
                entmicroCustomerBeforeYesterDayCount.forEach((key, value) -> {

                    if (resMap.containsKey(key)) {
                        CustomerStatistics beforeCustomer = resMap.get(key);
                        //昨日之前企微数
                        int addEntmicroCount = value.getAddEntmicroCount();
                        beforeCustomer.setAddEntmicroCount(addEntmicroCount);

                        //未加企微总数
                        int customerCount = beforeCustomer.getCustomerCount();
                        int notAddCount = customerCount - addEntmicroCount;
                        beforeCustomer.setNotAddEntmicroCount(notAddCount);
                        resMap.put(key, beforeCustomer);
                    }
                });
            }
            Map<Integer, CustomerStatistics> entmicroCustomerYesterDayCount = customerStatisticsMapper.getEntmicroCustomerYesterDayCount(datalist, dateStr);
            if (null != entmicroCustomerYesterDayCount && entmicroCustomerYesterDayCount.size() > 0) {
                entmicroCustomerYesterDayCount.forEach((key, value) -> {
                    if (resMap.containsKey(key)) {
                        //已存在商户,昨日有新增
                        CustomerStatistics beforeCustomer = resMap.get(key);

                        //昨日之前企微客户数
                        int addEntmicroCountBefore = beforeCustomer.getAddEntmicroCount();
                        //昨日新增企微客户数
                        int addEntmicroCount = value.getAddEntmicroCount();

                        //企微新增数
                        beforeCustomer.setNewEntmicroCount(addEntmicroCount);
                        //企微总数
                        int totalCustCount = addEntmicroCountBefore + addEntmicroCount;
                        beforeCustomer.setAddEntmicroCount(totalCustCount);

                        //未加企微总数
                        int customerCount = beforeCustomer.getCustomerCount();
                        int notAddCount = customerCount - totalCustCount;
                        beforeCustomer.setNotAddEntmicroCount(notAddCount);
                        //企微环比
                        double ratio;
                        if (addEntmicroCountBefore == 0) {
                            ratio = 100;
                        } else {
                            ratio = (addEntmicroCount * 1.0 / addEntmicroCountBefore) * 100;
                        }
                        beforeCustomer.setEntmicroRatio(ratio);
                        resMap.put(key, beforeCustomer);
                    }

                });
            }
            //企微流失客户
            Map<Integer, CustomerStatistics> lostCustomerBeforeYesterDayCount = customerStatisticsMapper.getLostCustomerBeforeYesterDayCount(datalist, yesterDay);
            log.info("统计企微流失客户=====" + JSONObject.toJSONString(lostCustomerBeforeYesterDayCount));
            if (null != lostCustomerBeforeYesterDayCount && lostCustomerBeforeYesterDayCount.size() > 0) {
                lostCustomerBeforeYesterDayCount.forEach((key, value) -> {

                    if (resMap.containsKey(key)) {
                        CustomerStatistics beforeCustomer = resMap.get(key);
                        //昨日之前企微流失数
                        int loseCount = value.getEntmicroLoseCount();
                        beforeCustomer.setEntmicroLoseCount(loseCount);
                        resMap.put(key, beforeCustomer);
                    }
                });
            }
            Map<Integer, CustomerStatistics> lostCustomerYesterDayCount = customerStatisticsMapper.getLostCustomerYesterDayCount(datalist, dateStr);
            if (null != lostCustomerYesterDayCount && lostCustomerYesterDayCount.size() > 0) {
                lostCustomerYesterDayCount.forEach((key, value) -> {
                    if (resMap.containsKey(key)) {
                        //已存在商户,昨日企微流失有新增
                        CustomerStatistics beforeCustomer = resMap.get(key);

                        //昨日之前企微流失客户数
                        int entmicroLoseCount = beforeCustomer.getEntmicroLoseCount();
                        //昨日新增企微流失客户数
                        int todayEntmicroLoseCount = value.getEntmicroLoseCount();

                        //企微流失新增数
                        beforeCustomer.setTodayEntmicroLoseCount(todayEntmicroLoseCount);
                        //企微总数
                        int totalCustCount = entmicroLoseCount + todayEntmicroLoseCount;
                        beforeCustomer.setEntmicroLoseCount(totalCustCount);
                        resMap.put(key, beforeCustomer);
                    }
                });
            }

            Collection<CustomerStatistics> values = resMap.values();
            if (CollectionUtils.isEmpty(values)) {
                return;
            }

            List<String> merchantIds = datalist.stream().map(String::valueOf).collect(Collectors.toList());
            try {
                String dateToday = DateUtils.format(new Date(), "yyyy/MM/dd");
                if (dateStr.equals(dateToday)) {
                    //潜在意向客户
                    Map<String, Integer> purposeMap = ropCommonServie.getMutOneIdsCountByLables(Collections.singletonList(Constants.PURPOSE), merchantIds);
                    //购买存档客户
                    Map<String, Integer> purchaseMap = ropCommonServie.getMutOneIdsCountByLables(Collections.singletonList(Constants.PURCHASE), merchantIds);
                    for (CustomerStatistics value : values) {
                        String merchantId = String.valueOf(value.getMerchantId());
                        if (null != purposeMap && purposeMap.containsKey(merchantId)) {
                            Integer count = purposeMap.get(merchantId);
                            value.setUnBuyCustCount(count);
                        }

                        if (null != purchaseMap && purchaseMap.containsKey(merchantId)) {
                            Integer count = purchaseMap.get(merchantId);
                            value.setBuyCustCount(count);
                        }
                    }
                }
            } catch (Exception e) {
                log.info("labelRemote=====getMutOneIdsCountByLables异常:{}", e.getMessage());
            }

            List<CustomerStatistics> statistics = new ArrayList(values);
            log.info("customerStatistics===statistics:{},merchantIds:{}", statistics, merchantIds);

            //1.merchantIds查询统计数据  2.如果merchantID对应日期未统计则插入统计数据,否则更新统计数据
            Map<Integer, CustomerStatistics> statisticsExistMap = customerStatisticsMapper.findStaticsDataByDate(merchantIds, dateStr);

            List<CustomerStatistics> addList = new ArrayList<>();
            List<CustomerStatistics> updateList = new ArrayList<>();

            if (null == statisticsExistMap || statisticsExistMap.isEmpty()) {
                addList.addAll(statistics);
            } else {
                for (CustomerStatistics statistic : statistics) {
                    Integer merchantId = statistic.getMerchantId();
                    if (statisticsExistMap.containsKey(merchantId)) {
                        CustomerStatistics statisticsExist = statisticsExistMap.get(merchantId);
                        statistic.setId(statisticsExist.getId());
                        updateList.add(statistic);
                    } else {
                        addList.add(statistic);
                    }
                }
            }

            if (!CollectionUtils.isEmpty(addList)) {
                log.info("customerStatistics===客户统计add");
                customerStatisticsMapper.insertList(addList);
            }

            if (!CollectionUtils.isEmpty(updateList)) {
                log.info("customerStatistics===客户统计update");
                customerStatisticsMapper.batchUpdate(updateList);
            }

            log.info("customerStatistics===客户统计成功");
        });
    }


    public void getDracStatisticCodeDefault(DracScrmStatisticCodeDefaultRequest dracScrmStatisticCodeDefaultRequest) {

    }

    /**
     * 根据条件查询客户新增情况
     *
     * @param customerStaticRequest
     * @return
     */
    public List<CustomerStatisticModel> findTimeCustomerStatistic(CustomerStaticRequest customerStaticRequest) {
        return customerStatisticsMapper.findCustomerStatistic(customerStaticRequest);
    }

    /**
     * 根据流失的客户数客户
     *
     * @param customerStaticRequest
     * @return
     */
    public List<CustomerStatisticModel> findLostCustomerStatistic(CustomerStaticRequest customerStaticRequest) {
        return customerStatisticsMapper.findLostCustomerStatistic(customerStaticRequest);
    }

    /**
     * 根据条件查询渠道活码新增情况
     *
     * @param customerStaticRequest
     * @return
     */
    public List<CustomerStatisticModel> findCodeStatistic(CustomerStaticRequest customerStaticRequest) {
        return customerStatisticsMapper.findCodeStatistic(customerStaticRequest);
    }

}