package com.iformall.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.domain.dto.KwMerchantMeterDataDto;
import com.iformall.domain.dto.KwMeterDataDto;
import com.iformall.domain.dto.MarkingCouponDataReportDto;
import com.iformall.domain.dto.WxCUserBasicInfoDto;
import com.iformall.domain.po.*;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.vo.*;
import com.iformall.enums.*;
import com.iformall.mapper.*;
import com.iformall.service.MarkingDataReportService;
import com.iformall.service.WxBusinessService;
import com.iformall.service.WxChartDataService;
import com.iformall.service.WxCouponService;
import com.iformall.service.kw.KwMerchantMeterService;
import com.iformall.service.kw.KwMeterDataService;
import com.iformall.service.kw.KwMeterService;
import com.iformall.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WxChartServiceImpl implements WxChartDataService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxShopMapper wxShopMapper;
    @Autowired
    WxBillRentMapper wxBillRentMapper;
    @Autowired
    WxMerchantMapper wxMerchantMapper;
    @Autowired
    WxMerchantTradeDailyMapper wxMerchantTradeDailyMapper;
    @Autowired
    WxCarCmdLogMapper wxCarCmdLogMapper;
    @Autowired
    WxCouponOrderMapper wxCouponOrderMapper;
    @Autowired
    WxUserVisitMapper wxUserVisitMapper;
    @Autowired
    WxCUserCarMapper wxCUserCarMapper;
    @Autowired
    WxCouponActionLogMapper wxCouponActionLogMapper;
    @Autowired
    WxCUserMapper wxCUserMapper;
    @Autowired
    WxCUserBasicInfoMapper wxCUserBasicInfoMapper;
    @Autowired
    WxUserChannelMapper wxUserChannelMapper;
    @Autowired
    WxLevelConfigMapper wxLevelConfigMapper;
    @Autowired
    WxCUserTagsMapper wxCUserTagsMapper;
    @Autowired
    WxCouponService wxCouponService;
    @Autowired
    WxOrderGroupMapper wxOrderGroupMapper;
    @Autowired
    WxBillPropertyMapper wxBillPropertyMapper;
    @Autowired
    WxBillDepositMapper wxBillDepositMapper;
    @Autowired
    WxBillOtherMapper wxBillOtherMapper;
    @Autowired
    WxBillAllMapper wxBillAllMapper;
    @Autowired
    MarkingDataReportService markingDataReportService;
    @Autowired
    WxBusinessService wxBusinessService;

    @Autowired
    KwMeterDataService kwMeterDataService;
    @Autowired
    KwMerchantMeterService kwMerchantMeterService;
    @Autowired
    KwMeterService kwMeterService;



    @Override
    public ResultData queryData(Map<String, String> paramsMap) {
        String tenantId = paramsMap.get("tenantId");
        Integer chart = Integer.valueOf(paramsMap.get("chart"));
        String startdate = paramsMap.get("startdate");
        String enddate = paramsMap.get("enddate");

        if(chart == null){
            return new ResultData(ErrorCode.REPORT_TYPE_UNKNOWN);
        }

        if (StringUtils.isEmpty(startdate)) {
            startdate = DateUtils.getSystemTime("yyyy-MM-dd") + " 00:00:00" ;
        } else {
            startdate = startdate + " 00:00:00";
        }
        if (StringUtils.isEmpty(enddate)) {
            enddate = DateUtils.getSystemTime("yyyy-MM-dd") + " 23:59:59";
        } else {
            enddate = enddate + " 23:59:59";
        }

        //出租率
        if (chart.equals(EnumChart.CZL.getCode())) {
            return getRentRate(tenantId);
        }
        //租金收缴率
        if (chart.equals(EnumChart.ZJSJL.getCode())) {
            return getRentMoneyRate(tenantId, startdate, enddate);
        }
        //昨日报单率
        if (chart.equals(EnumChart.ZRBDL.getCode())) {
            return getYesterdayTradeRate(tenantId);
        }
        //车流数据
        if (chart.equals(EnumChart.CLSJ.getCode())) {
            return getCarHistoryAndTodayAndHB(tenantId, false);
        }
        //券交易数据
        if (chart.equals(EnumChart.QJYSJ.getCode())) {
            return getCouponSaleAnalysis(tenantId);
        }
        //活跃用户数据
        if (chart.equals(EnumChart.HYYHSJ.getCode())) {
            // TODO getActiveMemberAnalysis
            return getActiveMemberTrade(tenantId);
        }
        //销售数据
        if (chart.equals(EnumChart.XSSJ.getCode())) {
            return getSaleAnalysis(tenantId);
        }
        //解单数据
        if (chart.equals(EnumChart.JDSJ.getCode())) {
            return getMerchantTradeMonthly(tenantId);
        }

        ///// --- 车流 -- START
        //今日已绑车牌量
        if (chart.equals(EnumChart.JRYBCPL.getCode())) {
            return getBindCarAnalysis(tenantId);
        }
        //实时车流量
        if (chart.equals(EnumChart.SSCLL.getCode())) {
            return getCarDataCurrent(tenantId);
        }
        // 历史车流量+今日车流量 + 上周同期
        if (chart.equals(EnumChart.LSCLL.getCode())) {
            return getCarHistoryAndTodayAndHB(tenantId, true);
        }
        //近一周新增停车会员
        if (chart.equals(EnumChart.JYZXXZTCHY.getCode())) {
            return getCarNewMemberCount(tenantId);
        }
        //近一周线上缴费车辆
        if (chart.equals(EnumChart.JYZXSJFCL.getCode())) {
            return getCarPayCarCountInWeek(tenantId);
        }
        //近一周线上缴费金额
        if (chart.equals(EnumChart.JYZXSJFJE.getCode())) {
            return getCarPayCountInWeek(tenantId);
        }
        //近一周新增会员数
        if (chart.equals(EnumChart.JYZXZHYS.getCode())) {
            return getCarNewMemberCountInWeek(tenantId);
        }
        //// --- 车流 -- END
        //昨日触达用户
        if (chart.equals(EnumChart.ZRCDYH.getCode())) {
            return getTodayTouchUser(tenantId);
        }
        //今日券交易数据
        if (chart.equals(EnumChart.JRQJYSJ.getCode())) {
            return getTodayCouponCount(tenantId);
        }
        //今日场景营销
        if (chart.equals(EnumChart.JRCJYX.getCode())) {
            return getSaleSceneCount(tenantId);
        }
        //触达用户数
        if (chart.equals(EnumChart.CDYHS.getCode())) {
            return getTouchUserCount(tenantId);
        }
        //场景营销数据
        if (chart.equals(EnumChart.CJYXSJ.getCode())) {
            return getSceneData(tenantId);
        }
        //新增用户
        if (chart.equals(EnumChart.XZYH.getCode())) {
            return getNewUserCount(tenantId);
        }
        //活跃用户
        if (chart.equals(EnumChart.HYYH.getCode())) {
            return getActiveMemberCount(tenantId);
        }
        //线上交易
        if (chart.equals(EnumChart.XSJY.getCode())) {
            return getOnlineOrderCount(tenantId);
        }
        //近一周新增用户数
        if (chart.equals(EnumChart.JYZXZYHS.getCode())) {
            return getNewMemberInWeek(tenantId);
        }
        //近一周活跃用户数
        if (chart.equals(EnumChart.JYZHYYHS.getCode())) {
            return getActiveMemberCountInWeek(tenantId);
        }
        //近一周线上交易金额(元)
        if (chart.equals(EnumChart.JYZXSJYJE.getCode())) {
            return getWeekMoneyData(tenantId);
        }
        //新增用户趋势
        if (chart.equals(EnumChart.XZYHQS.getCode())) {
            return getNewMemberTradeMonthly(tenantId);
        }
        //活跃用户趋势
        if (chart.equals(EnumChart.HYYHQS.getCode())) {
            return getActiveMemberTrade(tenantId);
        }
        //线上交易趋势
        if (chart.equals(EnumChart.XSJYQS.getCode())) {
            return getOnlineTrade(tenantId);
        }
        //微信用户总数
        if (chart.equals(EnumChart.WXYHZS.getCode())) {
            return getMemeberWechatTotal(tenantId);
        }
        //会员总数
        if (chart.equals(EnumChart.HYZS.getCode())) {
            return getMemberTotalCount(tenantId);
        }
        //微信用户累计趋势
        if (chart.equals(EnumChart.WXYHLJQS.getCode())) {
            return getMemberWechatJoinTrade(tenantId);
        }
        //会员累计趋势
        if (chart.equals(EnumChart.HYLJQS.getCode())) {
            return getMemberJoinTrade(tenantId);
        }
        //微信用户新增趋势
        if (chart.equals(EnumChart.WXYHXZQS.getCode())) {
            return getWechatMemberTrade(tenantId);
        }
        //会员新增趋势
        if (chart.equals(EnumChart.HYXZQS.getCode())) {
            return getNewMemberTrade(tenantId);
        }
        //拓客渠道
        if (chart.equals(EnumChart.TKQD.getCode())) {
            return getFromChannelAnalysis(tenantId);
        }
        //场景排名
        if (chart.equals(EnumChart.CJPM.getCode())) {
            return getSceneAnalysis(tenantId);
        }
        //会员性别比例
        if (chart.equals(EnumChart.HYXBBL.getCode())) {
            return getMemberSexRate(tenantId, startdate, enddate);
        }
        //会员绑定车牌率
        if (chart.equals(EnumChart.HYBDCPL.getCode())) {
            return getMemberBindCar(tenantId, startdate, enddate);
        }
        //会员年龄层次
        if (chart.equals(EnumChart.HYNLCC.getCode())) {
            return getMemberAgeAnalysis(tenantId, startdate, enddate);
        }
        //会员成长值
        if (chart.equals(EnumChart.HYCZZ.getCode())) {
            return getMemberGrowthAnalysis(tenantId, startdate, enddate);
        }
        //会员手机品牌
        if (chart.equals(EnumChart.HYSJPP.getCode())) {
            return getMobileBrandAnalysis(tenantId, startdate, enddate);
        }
        //会员活跃度
        if (chart.equals(EnumChart.HYHYD.getCode())) {
            return getMemActivity(tenantId, startdate, enddate);
        }
        //卡营销数据
        if (chart.equals(EnumChart.SALE_CARD.getCode())) {
            return getSaleCardAnalysis(paramsMap, startdate, enddate);
        }

        //券营销数据
        if (chart.equals(EnumChart.SALE_COUPON.getCode())) {
            return getSaleCouponAnalysis(paramsMap, startdate, enddate);
        }

        //砍价营销数据
        if (chart.equals(EnumChart.SALE_PRESS.getCode())) {
            return getSalePressAnalysis(paramsMap, tenantId, startdate, enddate);
        }

        //拼团营销数据
        if (chart.equals(EnumChart.SALE_GROUP.getCode())) {
            return getSaleGroupAnalysis(paramsMap, tenantId, startdate);
        }

        //首页商铺出租数据
        if (chart.equals(EnumChart.INDEX_SHOP_RENT.getCode())) {
            return getIndexShopRentData(paramsMap);
        }

        //首页商铺出租数据
        if (chart.equals(EnumChart.INDEX_BILL_RECE_RATE.getCode())) {
            return getBillReceRate(tenantId, startdate);
        }

        //首页场景发券
        if (chart.equals(EnumChart.INDEX_COUPON_SCENE.getCode())) {
            return new ResultData(markingDataReportService.getSceneDataHistory(tenantId, startdate, enddate));
        }

        //首页营销数据
        if (chart.equals(EnumChart.INDEX_SALE_DATA.getCode())) {
            return getSaleDataHistory(tenantId, startdate, enddate);
        }

        //商铺出租率走势
        if (chart.equals(EnumChart.RENT_RATE_HISTORY.getCode())) {
            return getRentRateHistory(tenantId,paramsMap);
        }

        //业务分析
        if (chart.equals(EnumChart.BUSINESS.getCode())) {
            return getBusiness(tenantId,paramsMap);
        }

        //电能分析
        if (chart.equals(EnumChart.POWER_SUMMERY.getCode())) {
            return getPowerSummery(tenantId,paramsMap);
        }

        return new ResultData(ErrorCode.REPORT_TYPE_UNKNOWN);
    }

    private Date addHour(int addHourAmount) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, addHourAmount);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        Date date = c.getTime();
        return date;
    }

    private Date addDay(int addDayAmount) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, addDayAmount);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        Date date = c.getTime();
        return date;
    }

    private Date addMonth(int addMountAmount) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, addMountAmount);
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        Date date = c.getTime();
        return date;
    }

    private Date addDay(Date date , int addDayAmount) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, addDayAmount);
        Date result = c.getTime();
        return result;
    }

    private Date addMonth(Date date, int addMountAmount) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, addMountAmount);
        Date result = c.getTime();
        return result;
    }

    private Date convertDateAndAdd(Date date, int addDayAmount) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, addDayAmount);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        Date result = c.getTime();
        return result;
    }


    /**
     * 用电分析
     * @param tenantId
     * @return
     */
    private ResultData getPowerSummery(String tenantId,Map<String, String> paramsMap){

        Map<String,Object> resultMap = new HashMap<>();

        KwMeterDataDto kwMeterDataDto = new KwMeterDataDto();
        kwMeterDataDto.setStartTime(addDay(-29));
        kwMeterDataDto.setEndTime(addDay(1));
        kwMeterDataDto.setTenantId(tenantId);
        kwMeterDataDto.setReportType(EnumMeterDataReportType.DAY.getCode());
        List<KwMeterDataVo> kwMeterDataVosDaily = kwMeterDataService.findVoList(kwMeterDataDto);

        List<KwMeterDataVo> monthDailyPower = new ArrayList<>();

        if (kwMeterDataVosDaily.size() >= 30) {
            resultMap.put("monthDailyPower", monthDailyPower);
        } else {
            for (int i = 29; i >= 0; i--) {
                String date = new SimpleDateFormat("yyyy-MM-dd").format(addDay(-i));
                Optional<KwMeterDataVo> optionalKwMeterDataVo = kwMeterDataVosDaily.stream().filter(md -> md.getReportTime().equals(date)).findFirst();
                if (optionalKwMeterDataVo.isPresent())
                    monthDailyPower.add(optionalKwMeterDataVo.get());
                else {
                    KwMeterDataVo kwMeterDataVo = new KwMeterDataVo();
                    kwMeterDataVo.setReportTime(date);
                    monthDailyPower.add(kwMeterDataVo);
                }
            }
        }


        kwMeterDataDto.setReportType(EnumMeterDataReportType.BY_HOUR.getCode());
        List<KwMeterDataVo> monthHoursPower = kwMeterDataService.findVoList(kwMeterDataDto);

        resultMap.put("monthHoursPower",monthHoursPower);

        resultMap.put("monthDailyPower",monthDailyPower);

        kwMeterDataDto = new KwMeterDataDto();
        kwMeterDataDto.setStartTime(addMonth(-11));
        kwMeterDataDto.setEndTime(addMonth(1));
        kwMeterDataDto.setTenantId(tenantId);
        kwMeterDataDto.setReportType(EnumMeterDataReportType.MONTH.getCode());
        List<KwMeterDataVo> kwMeterDataVosMonthly = kwMeterDataService.findVoList(kwMeterDataDto);

        List<KwMeterDataVo> yearMonthlyPower = new ArrayList<>();

        for (int i = 11; i >= 0; i--) {
            String date = new SimpleDateFormat("yyyy-MM").format(addMonth(-i));
            Optional<KwMeterDataVo> optionalKwMeterDataVo = kwMeterDataVosMonthly.stream().filter(md->md.getReportTime().equals(date)).findFirst();
            if (optionalKwMeterDataVo.isPresent())
                yearMonthlyPower.add(optionalKwMeterDataVo.get());
            else {
                KwMeterDataVo kwMeterDataVo = new KwMeterDataVo();
                kwMeterDataVo.setReportTime(date);
                yearMonthlyPower.add(kwMeterDataVo);
            }
        }

        resultMap.put("yearMonthlyPower",yearMonthlyPower);


        kwMeterDataDto = new KwMeterDataDto();
        kwMeterDataDto.setStartTime(addDay(0));
        kwMeterDataDto.setEndTime(addDay(1));
        kwMeterDataDto.setTenantId(tenantId);
        kwMeterDataDto.setReportType(EnumMeterDataReportType.HOUR.getCode());
        List<KwMeterDataVo> kwMeterDataVosHourly = kwMeterDataService.findVoList(kwMeterDataDto);

        List<KwMeterDataVo> todayHourlyPower = new ArrayList<>();

        for (int i = 0; i <= 23; i++) {
            String date = new SimpleDateFormat("HH:mm").format(addHour(i));
            Optional<KwMeterDataVo> optionalKwMeterDataVo = kwMeterDataVosHourly.stream().filter(md->md.getReportTime().contains(date)).findFirst();
            if (optionalKwMeterDataVo.isPresent()) {
                optionalKwMeterDataVo.get().setReportTime(date);
                todayHourlyPower.add(optionalKwMeterDataVo.get());
            }
            else {
                KwMeterDataVo kwMeterDataVo = new KwMeterDataVo();
                kwMeterDataVo.setReportTime(date);
                todayHourlyPower.add(kwMeterDataVo);
            }
        }
        resultMap.put("todayHourlyPower",todayHourlyPower);

        kwMeterDataDto = new KwMeterDataDto();

        kwMeterDataDto.setStartTime(addDay(-1));
        kwMeterDataDto.setEndTime(addDay(new Date(), -1));
        kwMeterDataDto.setTenantId(tenantId);
        KwMeterDataVo yesterdayUsedPower = kwMeterDataService.getPower(kwMeterDataDto);

        kwMeterDataDto.setStartTime(addDay(0));
        kwMeterDataDto.setEndTime(addDay(new Date(), 0));
        kwMeterDataDto.setTenantId(tenantId);
        KwMeterDataVo todayUsedPower = kwMeterDataService.getPower(kwMeterDataDto);

        if (todayUsedPower.getUsedPower() != null)
            resultMap.put("todayUsedPower", todayUsedPower.getUsedPower());

        if (yesterdayUsedPower.getUsedPower() != null)
            resultMap.put("yesterdayUsedPower", yesterdayUsedPower.getUsedPower());

        if (yesterdayUsedPower.getUsedPower() != null
                && todayUsedPower.getUsedPower() != null
                && !yesterdayUsedPower.getUsedPower().equals(0)) {
            double hbd = (double) (todayUsedPower.getUsedPower() - yesterdayUsedPower.getUsedPower()) / yesterdayUsedPower.getUsedPower() * 100;
            double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            resultMap.put("todayUsedPowerRate", hb + "%");
        } else {
            resultMap.put("todayUsedPowerRate", "--" + "%");
        }

        kwMeterDataDto.setStartTime(addMonth(0));
        kwMeterDataDto.setEndTime(addMonth(new Date(),0));
        kwMeterDataDto.setTenantId(tenantId);
        KwMeterDataVo thisMonthUsedPower = kwMeterDataService.getPower(kwMeterDataDto);
        if (thisMonthUsedPower.getUsedPower() != null)
            resultMap.put("thisMonthUsedPower",thisMonthUsedPower.getUsedPower());

        kwMeterDataDto.setStartTime(addMonth(-1));
        kwMeterDataDto.setEndTime(addMonth(new Date(),-1));
        kwMeterDataDto.setTenantId(tenantId);
        KwMeterDataVo lastMonthUsedPower = kwMeterDataService.getPower(kwMeterDataDto);
        if (lastMonthUsedPower.getUsedPower() != null)
            resultMap.put("lastMonthUsedPower",lastMonthUsedPower.getUsedPower());

        if (lastMonthUsedPower.getUsedPower() !=null && thisMonthUsedPower.getUsedPower() != null && lastMonthUsedPower.getUsedPower() !=0) {
            double hbd = (double) (thisMonthUsedPower.getUsedPower() - lastMonthUsedPower.getUsedPower()) / lastMonthUsedPower.getUsedPower() * 100;
            double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            resultMap.put("monthUsedPowerRate", hb + "%");
        } else {
            resultMap.put("monthUsedPowerRate", "--" + "%");
        }

        KwMeter kwMeter = new KwMeter();
        kwMeter.setTenantId(tenantId);
        kwMeter.setStatus(EnumMeterStatus.VALID.getCode());
        int meterCount = kwMeterService.selectCount(kwMeter);

        kwMeter.setBindStatus(EnumMeterBindStatus.BIND.getCode());
        int boxMeterCount = kwMeterService.selectCount(kwMeter);

        resultMap.put("meterCount",meterCount);
        resultMap.put("boxMeterCount",boxMeterCount);

        KwMerchantMeter kwMerchantMeter = new KwMerchantMeter();
        kwMerchantMeter.setTenantId(tenantId);
        kwMerchantMeter.setStatus(EnumMerchantMeterStatus.VALID.getCode());
        int merchantMeterCount = kwMerchantMeterService.selectCount(kwMerchantMeter);
        resultMap.put("merchantMeterCount",merchantMeterCount);

        KwMerchantMeterDataDto kwMerchantMeterDataDto = new KwMerchantMeterDataDto();
        kwMerchantMeterDataDto.setStartTime(addMonth(0));
        kwMerchantMeterDataDto.setEndTime(addMonth(new Date(),0));
        kwMerchantMeterDataDto.setSortColumns(BaseEntity.SortField.UsedPower_DESC);

        kwMerchantMeterDataDto.setMerchantId(0L);
        kwMerchantMeterDataDto.setLimitCount(10);
        List <KwMerchantMeterDataVo> merchantTop10 = kwMerchantMeterService.findDataVoList(kwMerchantMeterDataDto);
        resultMap.put("merchantTop10",merchantTop10);

        kwMerchantMeterDataDto.setMerchantId(null);
        kwMerchantMeterDataDto.setBusinessId(0);
        kwMerchantMeterDataDto.setLimitCount(null);
        List <KwMerchantMeterDataVo> businessPower = kwMerchantMeterService.findDataVoList(kwMerchantMeterDataDto);

        List <WxBusiness> businessList = wxBusinessService.findListAll(tenantId,null);
        businessList.stream().forEach(b->{
            Optional<KwMerchantMeterDataVo> businessData = businessPower.stream().filter(bd->bd.getBusinessId().equals(b.getId())).findAny();
            if (businessData.isPresent()) {
                businessData.get().setBusinessTitle(b.getTitle());
            } else {
                KwMerchantMeterDataVo newBusinessData = new KwMerchantMeterDataVo();
                newBusinessData.setBusinessId(b.getId());
                newBusinessData.setBusinessTitle(b.getTitle());
                businessPower.add(newBusinessData);
            }
        });

        resultMap.put("businessPower",businessPower);

        return new ResultData(resultMap);
    }


    /**
     * 业态分析
     * @param tenantId
     * @return
     */
    private ResultData getBusiness(String tenantId,Map<String, String> paramsMap){
        Map<String,Long> resultMap = new LinkedMap();
        List<WxBusiness> businessList = wxBusinessService.findList(new WxBusiness());
        for (WxBusiness b:businessList) {
            resultMap.put(b.getTitle(),0l);
        }
        Map<String,Object> query = new HashedMap();
        query.put("tenantId",tenantId);
        query.put("id",paramsMap.get("id"));
        query.put("buildingId",paramsMap.get("buildingId"));
        List<Map<String,Object>> mapList = wxMerchantMapper.findBusByFloorId(query);
        for (Map<String,Object> map:mapList) {
            resultMap.put((String)map.get("btitle"),(Long)map.get("count"));
        }
        return new ResultData(resultMap);
    }

    /**
     * 首页商铺出租率走势
     * @param tenantId
     * @return
     */
    private ResultData getRentRateHistory(String tenantId,Map<String, String> paramsMap) {
        Integer dateType = Integer.parseInt(paramsMap.get("dateType"));

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("tenantId",tenantId);
        queryMap.put("dateType",dateType);

        String building = paramsMap.get("building");
        String floor = paramsMap.get("floor");
        String business = paramsMap.get("businessId");

        if (StringUtils.isNotEmpty(building)) {
            queryMap.put("building", building);
        }
        if (StringUtils.isNotEmpty(floor)) {
            queryMap.put("floor", floor);
        }
        if (StringUtils.isNotEmpty(business)) {
            queryMap.put("businessId", business);
        }

        // get all
        WxShop query = new WxShop();
        query.setTenantId(tenantId);
        List<WxShop> allList = wxShopMapper.findList(query);

        List<Map<String,Object>> mapList = wxShopMapper.rentRateHistory(queryMap);
        if(CollectionUtils.isNotEmpty(mapList)){
            String startTime = (String)mapList.get(0).get("xTime");
            String endTime = (String)mapList.get(mapList.size()-1).get("xTime");
            List<String> days = DateUtils.getTjTimeList(startTime, endTime, 1==dateType.intValue()?"0":"1");
            Map<String,Long> map = getMap(days);
            for (Map<String,Object> m : mapList) {
                map.put((String)m.get( "xTime"),(Long)m.get("xCount"));
            }

            double all = allList.size();
            Map<String,String> resultMap = new LinkedMap();
            double rentTotal = 0;
            for (String key : map.keySet()) {
                rentTotal += map.get(key);
                resultMap.put(key,formatDouble(rentTotal/all*100)+"%");
            }
            return new ResultData(resultMap);
        }
        Map<Object, Object> result = new HashMap<>();
        if (dateType == 1) {
            //出租率-日
            String systemTime = DateUtils.getSystemTime("yyyy/MM/dd");
            result.put(systemTime, "0%");
        } else {
            //出租率-月
            String systemTime = DateUtils.getSystemTime("yyyy/MM");
            result.put(systemTime, "0%");
        }
        return new ResultData(result);
    }

    public Map<String,Long> getMap(List<String> days){
        Map<String,Long> map = new LinkedMap();
        for (String d:days) {
            map.put(d.replace("-", "/"),0l);
        }
        return map;
    }

    /**
     * 解单数据 - 月
     * @param tenantId
     * @return
     */
    private ResultData getMerchantTradeMonthly(String tenantId) {
        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();
        wxMerchantTradeDaily.setTenantId(tenantId);

        List<WxMerchantTradeDaily> recordList = wxMerchantTradeDailyMapper.findTotalListOfMonth(wxMerchantTradeDaily);
        Map<String, WxMerchantTradeDaily> recordMap = recordList.stream().collect(Collectors.toMap(WxMerchantTradeDaily::getReportDate, r -> r));

        List<WxMerchantTradeDaily> tradeList = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat fmtv = new SimpleDateFormat("MM/dd");
        cal.setTime(new Date());
        for (int i = 0; i < 30; i++) {
            cal.add(Calendar.DAY_OF_YEAR, -1);
            WxMerchantTradeDaily trade = recordMap.get(fmt.format(cal.getTime()));
            if (trade != null) {
                trade.setReportDate(fmtv.format(cal.getTime()));
                tradeList.add(trade);
            } else {
                trade = new WxMerchantTradeDaily();
                trade.setTradeAmt("0");
                trade.setReportDate(fmtv.format(cal.getTime()));
                tradeList.add(trade);
            }
        }
        Collections.reverse(tradeList);
        return new ResultData(tradeList);
    }

    /**
     * 今日已绑车牌量
     * @param tenantId
     * @return
     */
    private ResultData getBindCarAnalysis(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        String yesterday = DateUtils.getTimeBefore(1, new Date());
        String lastweek = DateUtils.getTimeBefore(7, new Date());
        //绑定车牌
        Map<String, Object> carParams = new HashMap<>();
        carParams.put("tenantId", tenantId);
        carParams.put("startdate", DateUtils.getSystemTime("yyyy-MM-dd 00:00:00"));
        carParams.put("enddate", DateUtils.getSystemTime("yyyy-MM-dd HH:mm:ss"));
        long todaybindcar = wxCUserCarMapper.queryCarCount(carParams);
        carParams.put("startdate", yesterday + " 00:00:00");
        carParams.put("enddate", yesterday + " 23:59:59");
        long yesterdaybindcar = wxCUserCarMapper.queryCarCount(carParams);
        carParams.put("startdate", lastweek + " 00:00:00");
        carParams.put("enddate", lastweek + " 23:59:59");
        long lastweekbindcar = wxCUserCarMapper.queryCarCount(carParams);
        datamap.put("todaybindcar", todaybindcar);
        if (yesterdaybindcar > 0) {
            double yesterdaybinddhb = (double) (todaybindcar - yesterdaybindcar) / yesterdaybindcar * 100;
            double yesterdaybindhb = new BigDecimal(yesterdaybinddhb).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            datamap.put("yesterdaybindhb", yesterdaybindhb + "%");
        } else {
            datamap.put("yesterdaybindhb", "--");
        }
        if (lastweekbindcar > 0) {
            double lastweekbinddhb = (double) (todaybindcar - lastweekbindcar) / lastweekbindcar * 100;
            double lastweekbindhb = new BigDecimal(lastweekbinddhb).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            datamap.put("lastweekbindhb", lastweekbindhb + "%");
        } else {
            datamap.put("lastweekbindhb", "--");
        }
        return new ResultData(datamap);
    }

    /**
     * 实时车流量
     * @param tenantId
     * @return
     */
    private ResultData getCarDataCurrent(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        String systemTime = DateUtils.getSystemTime("yyyy-MM-dd");
        String yesterday = DateUtils.getTimeBefore(1, new Date());
        String lastweek = DateUtils.getTimeBefore(7, new Date());
        HashMap<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("cmdType", EnumCarCmd.CAR_ETCP_CALLBACK_PARK_IN.getCode());
        params.put("startdate", systemTime + " 05:00:00");
        params.put("enddate", DateUtils.getSystemTime("yyyy-MM-dd HH:mm:ss"));
        List<Map<String, Object>> todayCarlist = wxCarCmdLogMapper.queryTodayCar(params);
        Map<Object, Object> todaycollect = todayCarlist.stream().collect(Collectors.toMap(m -> {
            return m.get("create_time");
        }, m -> {
            return m.get("carcount");
        }));
        List<String> hourList = new ArrayList<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR_OF_DAY, 1);
        int hour = instance.get(Calendar.HOUR_OF_DAY);
        int startHour = 6;
        int endHour = 24;
        for (int i = startHour; i < endHour; i++) {
            hourList.add(i < 10 ? "0" + i + ":00" : i + ":00");
        }
        List<Object> todayCarList = new ArrayList<>();
        for (int i = startHour; i < endHour; i++) {
            if(i<hour) {
                todayCarList.add(todaycollect.get((Object) hourList.get(i-startHour)));
            } else {
                todayCarList.add("");
            }
        }
        datamap.put("currentimeindex", hourList);
        datamap.put("todaycardata", todayCarList);
        params.put("startdate", yesterday + " 05:00:00");
        params.put("enddate", yesterday + " 22:59:59");
        List<Map<String, Object>> yesterdayCarlist = wxCarCmdLogMapper.queryTodayCar(params);
        Map<Object, Object> yesterdaycollect = yesterdayCarlist.stream().collect(Collectors.toMap(m -> {
            return m.get("create_time");
        }, m -> {
            return m.get("carcount");
        }));
        List<Object> yesterdayCarList = new ArrayList<>();
        for (int i = startHour; i < endHour; i++) {
            yesterdayCarList.add(yesterdaycollect.get((Object) hourList.get(i-startHour)));
        }
        datamap.put("yesterdaycardata", yesterdayCarList);

        params.put("startdate", lastweek + " 05:00:00");
        params.put("enddate", lastweek + " 22:59:59");
        List<Map<String, Object>> lastdayCarlist = wxCarCmdLogMapper.queryTodayCar(params);
        Map<Object, Object> lastweekdaycollect = lastdayCarlist.stream().collect(Collectors.toMap(m -> {
            return m.get("create_time");
        }, m -> {
            return m.get("carcount");
        }));
        List<Object> lastweekdayCarList = new ArrayList<>();
        for (int i = startHour; i < endHour; i++) {
            lastweekdayCarList.add(lastweekdaycollect.get((Object) hourList.get(i-startHour)));
        }
        datamap.put("lastdaycardata", lastweekdayCarList);

        return new ResultData(datamap);
    }

    /**
     * 数据塔台-数据总览-车流数据 | 数据塔台-车流数据-(历史车流量 + 今日车流量 + 上周同期)
     * @param tenantId
     * @return
     */
    private ResultData getCarHistoryAndTodayAndHB(String tenantId, boolean withOthers ) {
        String startdate;
        HashMap<String, Object> datamap = new HashMap<>();
        HashMap<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("cmdType", EnumCarCmd.CAR_ETCP_CALLBACK_PARK_IN.getCode());
        startdate = DateUtils.getTimeBefore(30, new Date());
        String systemTime = DateUtils.getSystemTime("yyyy-MM-dd");

        List<String> tjTimeList = DateUtils.getTjTimeList(startdate, systemTime, "0");

        params.put("startdate", startdate + " 00:00:00");
        params.put("enddate", systemTime + " 23:59:59");

        List<Map<String, Object>> historylist = wxCarCmdLogMapper.queryHistory(params);

        Map<Object, Object> collect = historylist.stream().collect(Collectors.toMap(m -> {
            return m.get("create_date");
        }, m -> {
            return m.get("carcount");
        }));

        List<String> timeList = new ArrayList<>();
        List<Object> valList = new ArrayList<>();
        for (String date : tjTimeList) {
            Object o = collect.get(date);
            timeList.add(date.substring(5).replace("-", "/"));
            if (o == null) {
                valList.add(0L);
            } else {
                valList.add(o);
            }
        }
        Map map = new HashMap();
        map.put("index", timeList);
        map.put("val", valList);
        datamap.put("history", map);

        if(withOthers) {
            //今日车流量
            long todaycar = ((Long) valList.get(valList.size()-1)).longValue();
            datamap.put("todaycar", todaycar);
            //环比
            long yesterdaycar = (long) ((Long) valList.get(valList.size()-2)).longValue();
            if (yesterdaycar > 0) {
                double hbd = (double) (todaycar - yesterdaycar) / yesterdaycar * 100;
                double hb = new BigDecimal(hbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                datamap.put("hb", hb + "%");
            } else {
                datamap.put("hb", "--");
            }
            //上周同期
            long lastweekcar = ((Long) valList.get(valList.size()-8)).longValue();
            if (lastweekcar > 0) {
                double lasthbd = (double) (todaycar - lastweekcar) / lastweekcar * 100;
                double lasthb = new BigDecimal(lasthbd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                datamap.put("lasthb", lasthb + "%");
            } else {
                datamap.put("lasthb", "--");
            }
            // 周入场数量
            long carWeekCount = 0L;
            for(int i=0;i<7;i++) {
                carWeekCount += ((Long)valList.get(valList.size()-1-i)).longValue();
            }
            datamap.put("carWeekCount", carWeekCount);
        }
        return new ResultData(datamap);
    }

    /**
     * 近一周线上缴费车辆
     * @param tenantId
     * @return
     */
    private ResultData getCarPayCarCountInWeek(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        HashMap<String, Object> weekParams = new HashMap<>();
        weekParams.put("tenantId", tenantId);
        String oneWeekStartdate = DateUtils.getTimeBefore(7, new Date());
        String oneWeekEndDate = DateUtils.getTimeBefore(1, new Date());
        weekParams.put("startdate", oneWeekStartdate + " 00:00:00");
        weekParams.put("enddate", oneWeekEndDate + " 23:59:59");
        weekParams.put("cmdType", EnumCarCmd.CAR_ETCP_CALLBACK_PAY_MANUAL.getCode());
        datamap.put("oneWeekCarPayCount", wxCarCmdLogMapper.queryWeekCarPayCount(weekParams));
        return new ResultData(datamap);
    }

    /**
     * 近一周线上缴费金额
     * @param tenantId
     * @return
     */
    private ResultData getCarPayCountInWeek(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        HashMap<String, Object> weekParams = new HashMap<>();
        weekParams.put("tenantId", tenantId);
        String oneWeekStartdate = DateUtils.getTimeBefore(7, new Date());
        String oneWeekEndDate = DateUtils.getTimeBefore(1, new Date());
        weekParams.put("startdate", oneWeekStartdate + " 00:00:00");
        weekParams.put("enddate", oneWeekEndDate + " 23:59:59");
        weekParams.put("cmdType", EnumCarCmd.CAR_ETCP_CALLBACK_PAY_MANUAL.getCode());
        List<Map<String, Object>> weekCarPayHistoryList = wxCarCmdLogMapper.queryWeekCarPay(weekParams);
        Map<String, Object> weekCollect = weekCarPayHistoryList.stream().collect(Collectors.toMap(m -> {
            return (String) m.get("create_time");
        }, m -> {
            return m.get("fee");
        }));
        List<String> days = DateUtils.getTjTimeList(oneWeekStartdate, oneWeekEndDate, "0");
        List<String> timeList = new ArrayList<>();
        List<Object> valList = new ArrayList<>();
        for (String date : days) {
            String dateStr = date.substring(5, date.length()).replace("-", "/");
            timeList.add(dateStr);
            Object o = weekCollect.get(dateStr);
            if (o == null) {
                valList.add(0L);
            } else {
                valList.add(o);
            }
        }

        Map map = new HashMap();
        map.put("index", timeList);
        map.put("val", valList);
        datamap.put("oneWeekCarPayFeeCount", map);
        return new ResultData(datamap);
    }

    /**
     * 车流 - 近一周新增停车会员
     * @param tenantId
     * @return
     */
    private ResultData getCarNewMemberCount(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        String oneWeekStartdate = DateUtils.getTimeBefore(7, new Date());
        String oneWeekEndDate = DateUtils.getTimeBefore(1, new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        WxCUserBasicInfoDto wxCUserBasicInfoDto = new WxCUserBasicInfoDto();
        wxCUserBasicInfoDto.setTenantId(tenantId);
        try {
            wxCUserBasicInfoDto.setStartTime(sdf.parse(oneWeekStartdate));
            wxCUserBasicInfoDto.setEndTime(sdf.parse(oneWeekEndDate));
        } catch (Exception e) {
            e.printStackTrace();
        }
        datamap.put("oneWeekNewCarUserCount", wxCUserCarMapper.countUser(wxCUserBasicInfoDto));
        //停车会员总数
        wxCUserBasicInfoDto = new WxCUserBasicInfoDto();
        wxCUserBasicInfoDto.setTenantId(tenantId);
        datamap.put("newCarUserSumCount", wxCUserCarMapper.countUser(wxCUserBasicInfoDto));

        return new ResultData(datamap);
    }

    /**
     * 车流 - 近一周新增会员数
     * @param tenantId
     * @return
     */
    private ResultData getCarNewMemberCountInWeek(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        HashMap<String, Object> weekParams = new HashMap<>();
        weekParams.put("tenantId", tenantId);
        String oneWeekStartdate = DateUtils.getTimeBefore(7, new Date());
        String oneWeekEndDate = DateUtils.getTimeBefore(1, new Date());
        weekParams.put("startdate", oneWeekStartdate + " 00:00:00");
        weekParams.put("enddate", oneWeekEndDate + " 23:59:59");
        weekParams.put("cmdType", EnumCarCmd.CAR_ETCP_CALLBACK_PAY_MANUAL.getCode());
        List<Map<String, Object>> carCountHistory = wxCUserCarMapper.queryCarCountHistory(weekParams);
        Map<String, Object> weekCarCollect = carCountHistory.stream().collect(Collectors.toMap(m -> {
            return (String) m.get("create_time");
        }, m -> {
            return m.get("count");
        }));
        List<String> days = DateUtils.getTjTimeList(oneWeekStartdate, oneWeekEndDate, "0");
        List<String> timeList = new ArrayList<>();
        List<Object> valList = new ArrayList<>();
        for (String date : days) {
            String newdate = date.substring(5, date.length()).replace("-", "/");
            Object o = weekCarCollect.get(newdate);
            timeList.add(newdate);
            if (o == null) {
                valList.add(0L);
            } else {
                valList.add(o);
            }
        }

        Map map = new HashMap();
        map.put("index", timeList);
        map.put("val", valList);
        datamap.put("oneWeekNewCarUserHistory", map);
        return new ResultData(datamap);
    }

    /**
     * 今日券交易数据
     * @param tenantId
     * @return
     */
    private ResultData getTodayTouchUser(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        //查询UV PV
        HashMap<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("startTime", addDay(-1));
        params.put("endTime", addDay(1));
        List<TouchUsersReportVo> wxUserVisitList = wxUserVisitMapper.touchUsersReportData(params);
        TouchUsersReportVo touchUsersReportVo = new TouchUsersReportVo();
        if (!wxUserVisitList.isEmpty()) {
            touchUsersReportVo = wxUserVisitList.get(0);
        } else {
            touchUsersReportVo.setPv(0);
            touchUsersReportVo.setUv(0);
            touchUsersReportVo.setCouponCount(0);
            touchUsersReportVo.setUserCount(0);
            touchUsersReportVo.setVerifyCount(0);
            touchUsersReportVo.setVerifyUserCount(0);
            touchUsersReportVo.setXTime(DateUtils.getSystemTime("MM/dd"));
        }
        datamap.put("yesterday", touchUsersReportVo);
        return new ResultData(datamap);
    }

    /**
     * 今日券交易数据
     * @param tenantId
     * @return
     */
    private ResultData getTodayCouponCount(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        //今日领取券数
        //查询coupon order表
        WxCouponOrder wxCouponOrder = new WxCouponOrder();
        wxCouponOrder.setTenantId(tenantId);
        wxCouponOrder.setStartTime(addDay(0));
        wxCouponOrder.setEndTime(addDay(1));
        int todayCouponCount = wxCouponOrderMapper.findCount(wxCouponOrder);
        wxCouponOrder.setStartTime(addDay(-1));
        wxCouponOrder.setEndTime( addDay(0));
        int yesterdayCount = wxCouponOrderMapper.findCount(wxCouponOrder);
        wxCouponOrder.setStartTime(addDay(-7));
        wxCouponOrder.setEndTime( addDay(-6));
        int lastWeekCount = wxCouponOrderMapper.findCount(wxCouponOrder);
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);//控制保留小数点后几位，2：表示保留2位小数点
        String couponUpDay = "--";
        if (yesterdayCount != 0) {
            couponUpDay = nf.format((todayCouponCount - yesterdayCount) / (float) yesterdayCount);
        }
        String couponUpWeek = "--";
        if (lastWeekCount != 0) {
            couponUpWeek = nf.format((todayCouponCount - lastWeekCount) / (float) lastWeekCount);
        }
        datamap.put("couponUpDay", couponUpDay);//比昨日提升
        datamap.put("couponUpWeek", couponUpWeek);//比上周提升
        datamap.put("todayCouponCount", todayCouponCount);//今日领取数
        return new ResultData(datamap);
    }

    /**
     * 今日场景营销
     * @param tenantId
     * @return
     */
    private ResultData getSaleSceneCount(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        int todaySceneCount = wxCouponActionLogMapper.getCountByDateLimit(tenantId, addDay(0), addDay(1));
        int yesterdayCount = wxCouponActionLogMapper.getCountByDateLimit(tenantId, addDay(-1), addDay(0));
        int lastWeekCount = wxCouponActionLogMapper.getCountByDateLimit(tenantId, addDay(-7), addDay(-6));
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);//控制保留小数点后几位，2：表示保留2位小数点
        String sceneDownDay = "--";
        if (yesterdayCount != 0) {
            sceneDownDay = nf.format((yesterdayCount - todaySceneCount) / (float) yesterdayCount);
        }
        String sceneUpWeek = "--";
        if (lastWeekCount != 0) {
            sceneUpWeek = nf.format((todaySceneCount - lastWeekCount) / (float) lastWeekCount);
        }
        datamap.put("sceneDownDay", sceneDownDay);//比昨日下降
        datamap.put("sceneUpWeek", sceneUpWeek);//比上周提升
        datamap.put("todaySceneCount", todaySceneCount);//今日领取数
        return new ResultData(datamap);
    }

    /**
     * 触达用户数
     * @param tenantId
     * @return
     */
    private ResultData getTouchUserCount(String tenantId) {
        String startdate;
        String enddate;//查询UV PV
        HashMap<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("startTime", addDay(-30));
        params.put("endTime", addDay(1));
        List<TouchUsersReportVo> wxUserVisitList = wxUserVisitMapper.touchUsersReportData(params);
        startdate = DateUtils.getTimeBefore(30, new Date());
        enddate = DateUtils.getTimeBefore(1, new Date());
        List<String> tjTimeList = DateUtils.getTjTimeList(startdate, enddate, "0");
        List<String> tjList = tjTimeList.stream().map(d -> d.substring(5).replace("-", "/")).collect(Collectors.toList());
        List<TouchUsersReportVo> tempDatalist = new LinkedList<>();
        for (String tj : tjList) {
            Optional<TouchUsersReportVo> first = wxUserVisitList.stream().filter(c -> c.getXTime().equals(tj)).findFirst();
            if (!first.isPresent()) {
                TouchUsersReportVo touchUsersReportVo = new TouchUsersReportVo();
                touchUsersReportVo.setPv(0);
                touchUsersReportVo.setUv(0);
                touchUsersReportVo.setCouponCount(0);
                touchUsersReportVo.setUserCount(0);
                touchUsersReportVo.setVerifyCount(0);
                touchUsersReportVo.setVerifyUserCount(0);
                touchUsersReportVo.setXTime(tj);
                tempDatalist.add(touchUsersReportVo);
                continue;
            }
            tempDatalist.add(first.get());
        }
        return new ResultData(tempDatalist);
    }

    /**
     * 场景营销数据
     * @param tenantId
     * @return
     */
    private ResultData getSceneData(String tenantId) {
        String startdate;
        String enddate;
        HashMap<String, Object> datamap = new HashMap<>();

        HashMap<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("startTime", addDay(-30));
        params.put("endTime", addDay(1));
        //停车发券数 停车发券被核销数  核销发券数 核销发券被核销数
        List<MarkingSceneDataReportVo> list = wxCouponActionLogMapper.sceneDataMap(params);

        //停车发券被核销数
        HashMap<String, Object> params1 = new HashMap<>();
        params1.put("tenantId", tenantId);
        params1.put("startTime", addDay(-30));
        params1.put("endTime", addDay(1));
        params1.put("channelType", EnumCouponSendSendType.CAR_STOP.getCode());//停车
        List<MarkingSceneDataReportVo> list1 = wxCouponActionLogMapper.sceneDataMapJoinCouponOrder(params1);
        Map<String, Integer> parkCountMap = list1.stream().collect(Collectors.toMap(MarkingSceneDataReportVo::getXTime, p -> p.getTempCount()));

        //核销发券被核销数
        HashMap<String, Object> params2 = new HashMap<>();
        params2.put("tenantId", tenantId);
        params2.put("startTime", addDay(-30));
        params2.put("endTime", addDay(1));
        params2.put("channelType", EnumCouponSendSendType.COUPON_VERIFY.getCode());//核销
        List<MarkingSceneDataReportVo> list2 = wxCouponActionLogMapper.sceneDataMapJoinCouponOrder(params2);
        Map<String, Integer> verifyCountMap = list2.stream().collect(Collectors.toMap(MarkingSceneDataReportVo::getXTime, p -> p.getTempCount()));

        // B端刷卡支付被核销数
        HashMap<String, Object> params3 = new HashMap<>();
        params3.put("tenantId", tenantId);
        params3.put("startTime", addDay(-30));
        params3.put("endTime", addDay(1));
        params3.put("channelType", EnumCouponSendSendType.B_MICROPAY.getCode());//B端刷卡支付
        List<MarkingSceneDataReportVo> list3 = wxCouponActionLogMapper.sceneDataMapJoinCouponOrder(params3);
        Map<String, Integer> microPayCountMap = list3.stream().collect(Collectors.toMap(MarkingSceneDataReportVo::getXTime, p -> p.getTempCount()));

        // 购买发券被核销数
        HashMap<String, Object> params4 = new HashMap<>();
        params3.put("tenantId", tenantId);
        params3.put("startTime", addDay(-30));
        params3.put("endTime", addDay(1));
        params3.put("channelType", EnumCouponSendSendType.C_ORDER.getCode());//买券
        List<MarkingSceneDataReportVo> list4 = wxCouponActionLogMapper.sceneDataMapJoinCouponOrder(params4);
        Map<String, Integer> OrderCountMap = list4.stream().collect(Collectors.toMap(MarkingSceneDataReportVo::getXTime, p -> p.getTempCount()));

        for (MarkingSceneDataReportVo vo : list) {
            vo.setParkCount(parkCountMap.get(vo.getXTime()) == null ? 0 : parkCountMap.get(vo.getXTime()));
            vo.setVerifyCount(verifyCountMap.get(vo.getXTime()) == null ? 0 : verifyCountMap.get(vo.getXTime()));
            vo.setMicroPayCount(microPayCountMap.get(vo.getXTime()) == null ? 0 : microPayCountMap.get(vo.getXTime()));
            vo.setOrderCount(OrderCountMap.get(vo.getXTime()) == null ? 0 : OrderCountMap.get(vo.getXTime()));
        }

        startdate = DateUtils.getTimeBefore(30, new Date());
        enddate = DateUtils.getTimeBefore(1, new Date());
        List<String> tjTimeList = DateUtils.getTjTimeList(startdate, enddate, "0");
        List<String> tjList = tjTimeList.stream().map(d -> d.substring(5).replace("-", "/")).collect(Collectors.toList());
        List<MarkingSceneDataReportVo> tempDatalist = new LinkedList<>();

        for (String tj : tjList) {
            Optional<MarkingSceneDataReportVo> first = list.stream().filter(c -> c.getXTime().equals(tj)).findFirst();

            MarkingSceneDataReportVo msdVo;
            if (!first.isPresent()) {
                msdVo = new MarkingSceneDataReportVo();
                msdVo.setXTime(tj);
                msdVo.setCarCount(0);
                msdVo.setParkCount(0);
                msdVo.setVerifyCount(0);
                msdVo.setMicroPayCount(0);
                msdVo.setOrderCount(0);
                msdVo.setTempCount(0);
                msdVo.setParkSendCount(0);
                msdVo.setVerifySendCount(0);
                msdVo.setMicroPaySendCount(0);
                msdVo.setOrderSendCount(0);
                msdVo.setTotal(0);
            } else {
                msdVo = first.get();
                msdVo.setTotal(msdVo.getParkSendCount() +
                        msdVo.getVerifySendCount() +
                        msdVo.getMicroPaySendCount() +
                        msdVo.getOrderSendCount());
            }
            tempDatalist.add(msdVo);
        }
        datamap.put("sceneDataMap", tempDatalist);
        return new ResultData(datamap);
    }

    /**
     * 活跃用户
     * @param tenantId
     * @return
     */
    private ResultData getNewUserCount(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        long allCount = wxCUserMapper.findCount(dto);//总数
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        c.setTime(today);
        c.add(Calendar.DAY_OF_YEAR, -1);
        dto.setStartTime(c.getTime());
        c.add(Calendar.DAY_OF_YEAR, 1);
        dto.setEndTime(c.getTime());
        long todayCount = wxCUserMapper.findCount(dto);
        datamap.put("allCount", allCount);//会员总数
        datamap.put("todayCount", todayCount);//今日新增会员数
        return new ResultData(datamap);
    }

    /**
     * 活跃用户
     * @param tenantId
     * @return
     */
    private ResultData getActiveMemberCount(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, -30);
        Date startTime = c.getTime();
        MarkingCouponDataReportDto markingCouponDataReportDto = new MarkingCouponDataReportDto();
        markingCouponDataReportDto.setTenantId(tenantId);
        markingCouponDataReportDto.setStartTime(startTime);
        markingCouponDataReportDto.setEndTime(endTime);
        List<TouchUsersReportVo> list = wxUserVisitMapper.touchUsersReportList(markingCouponDataReportDto);
        String yesterday = DateUtils.getTimeBefore(1, new Date());
        List<TouchUsersReportVo> collect = list.parallelStream().filter(x -> x.getXTime().equals(yesterday)).collect(Collectors.toList());
        int yesterdayCount = 0;
        if (!collect.isEmpty()) {
            yesterdayCount = collect.get(0).getUv();
        }
        Integer thisMonthCount = list.parallelStream().collect(Collectors.summingInt(u -> u.getUv()));
        datamap.put("yesterdayCount", yesterdayCount);//昨日活跃数
        datamap.put("thisMonthCount", thisMonthCount);//近一个月活跃数
        return new ResultData(datamap);
    }

    /**
     * 线上交易
     * @param tenantId
     * @return
     */
    private ResultData getOnlineOrderCount(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();//明天0点
        c.add(Calendar.DAY_OF_YEAR, -30);
        Date startTime = c.getTime();
        WxCouponOrder wxCouponOrder = new WxCouponOrder();
        wxCouponOrder.setStartTime(startTime);
        wxCouponOrder.setEndTime(endTime);
        wxCouponOrder.setTenantId(tenantId);
        int thisMonthCount = wxCouponOrderMapper.queryPriceTotal(wxCouponOrder);//月消费金额
        c.clear();
        c.add(Calendar.DAY_OF_YEAR, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        startTime = c.getTime();
        wxCouponOrder.setStartTime(startTime);
        wxCouponOrder.setEndTime(endTime);
        wxCouponOrder.setTenantId(tenantId);
        int todayCount = wxCouponOrderMapper.queryPriceTotal(wxCouponOrder);//月消费金额
        DecimalFormat df = new DecimalFormat("0.00");
        datamap.put("todayCount", df.format((float) todayCount / 100));//今日消费金额
        String thisMonthCountStr = df.format((float) thisMonthCount / 100);
        datamap.put("thisMonthCount", thisMonthCountStr);//近一个月消费金额数
        return new ResultData(datamap);
    }

    private ResultData getNewMemberCount(String tenantId, int days, String returnName) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        List<UserStructureVo> weekVos = new ArrayList<>();//周会员数
        for (int i = days, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            dto.setStartTime(c.getTime());
            c.add(Calendar.DAY_OF_YEAR, 1);
            dto.setEndTime(c.getTime());
            long count = wxCUserMapper.findCount(dto);
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(dto.getStartTime()));
            vo.setSortNum(sortNum++);
            vo.setCount(count);
            weekVos.add(vo);
        }
        datamap.put(returnName, weekVos);//月用户增加数列表
        return new ResultData(datamap);
    }

    /**
     * 近一周新增用户数
     * @param tenantId
     * @return
     */
    private ResultData getNewMemberInWeek(String tenantId) {
        return getNewMemberCount(tenantId, 7, "weekVos");
    }

    /**
     * 近一周活跃用户数
     * @param tenantId
     * @return
     */
    private ResultData getActiveMemberCountInWeek(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, -7);
        Date startTime = c.getTime();
        MarkingCouponDataReportDto markingCouponDataReportDto = new MarkingCouponDataReportDto();
        markingCouponDataReportDto.setTenantId(tenantId);
        markingCouponDataReportDto.setStartTime(startTime);
        markingCouponDataReportDto.setEndTime(endTime);
        List<TouchUsersReportVo> list = wxUserVisitMapper.touchUsersReportList(markingCouponDataReportDto);
        Map<String, TouchUsersReportVo> dateMap = new HashMap<>();
        for (TouchUsersReportVo vo : list) {
            dateMap.put(vo.getXTime(), vo);
        }
        List<UserStructureVo> weekVos = new ArrayList<>();//每周uv
        for (int i = 7, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(endTime);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dayStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (dateMap.get(dayStr) != null) {
                TouchUsersReportVo rv = dateMap.get(dayStr);
                Long l = new Long((long) rv.getUv());
                vo.setCount(l);
            } else {
                vo.setCount(0);
            }
            weekVos.add(vo);
        }
        datamap.put("weekVos", weekVos);//周活跃数列表
        return new ResultData(datamap);
    }

    /**
     * 近一周线上交易金额(元)
     * @param tenantId
     * @return
     */
    private ResultData getWeekMoneyData(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        Date today = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();//明天0点
        c.add(Calendar.DAY_OF_YEAR, -30);//三十天前
        c.clear();
        c.setTime(endTime);
        Date eTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, -7);
        Date sTime = c.getTime();
        List<CUserDateAmountVo> datas = wxCouponOrderMapper.queryPriceTotalGroup(tenantId, sTime, eTime);
        Map<String, Integer> dataMap = new HashMap<>();
        for (CUserDateAmountVo v : datas) {
            dataMap.put(v.getXTime(), v.getPrice());
        }
        List<UserStructureVo> weekVos = new ArrayList<>();//周消费金额
        for (int i = 7, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (dataMap.get(dateStr) != null) {
                int price = dataMap.get(dateStr);
                vo.setPrice(price);
            } else {
                vo.setPrice(0);
            }
            weekVos.add(vo);
        }
        datamap.put("weekVos", weekVos);//一周金额列表
        return new ResultData(datamap);
    }

    /**
     * 销售数据
     * @param tenantId
     * @return
     */
    private ResultData getSaleAnalysis(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        Date sTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date eTime = c.getTime();//明天0点
        c.add(Calendar.DAY_OF_YEAR, -30);//三十天前
        List<CUserDateAmountVo> datas = wxCouponOrderMapper.queryPriceTotalGroup(tenantId, sTime, eTime);
        List<UserStructureVo> monthVos = new ArrayList<>();//周消费金额
        Map<String, Integer> dataMap = new HashMap<>();
        for (CUserDateAmountVo v : datas) {
            dataMap.put(v.getXTime(), v.getPrice());
        }
        for (int i = 29, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(sTime);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (datamap.get(dateStr) != null) {
                int price = dataMap.get(dateStr);
                vo.setPrice(price);
            } else {
                vo.setPrice(0);
            }
            monthVos.add(vo);
        }
        datamap.put("monthVos", monthVos);//一月金额列表
        return new ResultData(datamap);
    }

    private ResultData getActiveMemberAnalysis(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, -30);
        Date startTime = c.getTime();
        MarkingCouponDataReportDto markingCouponDataReportDto = new MarkingCouponDataReportDto();
        markingCouponDataReportDto.setTenantId(tenantId);
        markingCouponDataReportDto.setStartTime(startTime);
        markingCouponDataReportDto.setEndTime(endTime);
        List<TouchUsersReportVo> list = wxUserVisitMapper.touchUsersReportList(markingCouponDataReportDto);
        Map<String, TouchUsersReportVo> dateMap = new HashMap<>();
        for (TouchUsersReportVo vo : list) {
            dateMap.put(vo.getXTime(), vo);
        }
        List<UserStructureVo> monthVos = new ArrayList<>();//每月uv
        for (int i = 29, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(endTime);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dayStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (dateMap.get(dayStr) != null) {
                TouchUsersReportVo rv = dateMap.get(dayStr);
                Long l = new Long((long) rv.getUv());
                vo.setCount(l);
            } else {
                vo.setCount(0);
            }
            monthVos.add(vo);
        }
        datamap.put("monthVos", monthVos);//月活跃数列表
        return new ResultData(datamap);
    }

    /**
     * 新增用户趋势-月
     * @param tenantId
     * @return
     */
    private ResultData getNewMemberTradeMonthly(String tenantId) {
        return getNewMemberCount(tenantId, 29, "monthVos");
    }

    /**
     * 活跃用户趋势
     * @param tenantId
     * @return
     */
    private ResultData getActiveMemberTrade(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date endTime = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, -30);
        Date startTime = c.getTime();
        MarkingCouponDataReportDto markingCouponDataReportDto = new MarkingCouponDataReportDto();
        markingCouponDataReportDto.setTenantId(tenantId);
        markingCouponDataReportDto.setStartTime(startTime);
        markingCouponDataReportDto.setEndTime(endTime);
        List<TouchUsersReportVo> list = wxUserVisitMapper.touchUsersReportList(markingCouponDataReportDto);
        Map<String, TouchUsersReportVo> dateMap = new HashMap<>();
        for (TouchUsersReportVo vo : list) {
            dateMap.put(vo.getXTime(), vo);
        }
        List<UserStructureVo> monthVos = new ArrayList<>();//每月uv
        for (int i = 29, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(endTime);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dayStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (dateMap.get(dayStr) != null) {
                TouchUsersReportVo rv = dateMap.get(dayStr);
                Long l = new Long((long) rv.getUv());
                vo.setCount(l);
            } else {
                vo.setCount(0);
            }
            monthVos.add(vo);
        }
        datamap.put("monthVos", monthVos);//月活跃数列表
        return new ResultData(datamap);
    }

    /**
     * 线上交易趋势
     * @param tenantId
     * @return
     */
    private ResultData getOnlineTrade(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        Calendar c = Calendar.getInstance();
        Date today = c.getTime();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date eTime = c.getTime();//明天0点
        c.add(Calendar.DAY_OF_YEAR, -30);//三十天前
        Date sTime = c.getTime();
        List<CUserDateAmountVo> datas = wxCouponOrderMapper.queryPriceTotalGroup(tenantId, sTime, eTime);
        Map<String, Integer> dataMap = new HashMap<>();
        for (CUserDateAmountVo v : datas) {
            dataMap.put(v.getXTime(), v.getPrice());
        }
        List<UserStructureVo> monthVos = new ArrayList<>();
        for (int i = 29, sortNum = 0; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
            UserStructureVo vo = new UserStructureVo();
            vo.setName(new SimpleDateFormat("MM/dd").format(c.getTime()));
            vo.setSortNum(sortNum++);
            if (dataMap.get(dateStr) != null) {
                int price = dataMap.get(dateStr);
                vo.setPrice(price);
            } else {
                vo.setPrice(0);
            }
            monthVos.add(vo);
        }
        datamap.put("monthVos", monthVos);//一月金额列表
        return new ResultData(datamap);
    }

    /**
     * 微信用户总数
     * @param tenantId
     * @return
     */
    private ResultData getMemeberWechatTotal(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        //微信用户数据
        long wxallCount = wxCUserMapper.findCount(dto);//总量
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        dto.setStartTime(today);
        dto.setEndTime(null);
        long wxtodayCount = wxCUserMapper.findCount(dto);//今天新增
        datamap.put("wxallCount", wxallCount);//累计会员总数
        datamap.put("wxtodayCount", wxtodayCount);//今日新增会员数
        return new ResultData(datamap);
    }

    /**
     * 会员总数
     * @param tenantId
     * @return
     */
    private ResultData getMemberTotalCount(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        long allCount = wxCUserBasicInfoMapper.findCount(dto);//总量
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        dto.setStartTime(today);
        dto.setEndTime(null);
        long todayCount = wxCUserBasicInfoMapper.findCount(dto);//今天新增
        datamap.put("allCount", allCount);//累计会员总数
        datamap.put("todayCount", todayCount);//今日新增会员数
        return new ResultData(datamap);
    }

    /**
     * 微信用户累计趋势
     * @param tenantId
     * @return
     */
    private ResultData getMemberWechatJoinTrade(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        final int daysBefore = 29;
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        List<UserStructureVo> wxnewCountVos = new ArrayList<>();//每日新增会员数
        int j = 1;
        for (int i = daysBefore; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            dto.setStartTime(c.getTime());
            c.add(Calendar.DAY_OF_YEAR, 1);
            dto.setEndTime(c.getTime());
            long count = wxCUserMapper.findCount(dto);
            UserStructureVo vo = new UserStructureVo();
            vo.setSortNum(j);
            j++;
            vo.setName(new SimpleDateFormat("MM/dd").format(dto.getStartTime()));
            vo.setCount(count);
            wxnewCountVos.add(vo);
        }
        List<UserStructureVo> wxallCountVos = new ArrayList<>();//累计会员数
        c.clear();
        c.setTime(today);
        c.add(Calendar.DAY_OF_YEAR, -daysBefore);
        dto.setEndTime(c.getTime());
        dto.setStartTime(null);
        long firstDay = wxCUserMapper.findCount(dto);//统计的第一天总数
        int i = 0;
        long sumCount = 0;
        for (UserStructureVo v : wxnewCountVos) {
            UserStructureVo vo = new UserStructureVo();
            sumCount += v.getCount();
            vo.setCount(firstDay + sumCount);
            vo.setName(v.getName());
            vo.setSortNum(i + 1);
            wxallCountVos.add(vo);
            i++;
        }
        datamap.put("wxallCountVos", wxallCountVos);//累计会员列表（ 日期和数量list）
        return new ResultData(datamap);
    }

    /**
     * 券交易数据
     * @param tenantId
     * @return
     */
    private ResultData getCouponSaleAnalysis(String tenantId) {
        String startdate;
        String enddate;
        HashMap<String, Object> datamap = new HashMap<>();
        //couponData
        HashMap<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("startTime", addDay(-30));
        params.put("endTime", addDay(1));
        List<MarkingCouponDataReportVo> couponDatalist = wxCouponOrderMapper.couponDataMap(params);
        //查询券领取人数
        startdate = DateUtils.getTimeBefore(30, new Date());
        enddate = DateUtils.getTimeBefore(1, new Date());
        List<String> tjTimeList = DateUtils.getTjTimeList(startdate, enddate, "0");
        List<String> tjList = tjTimeList.stream().map(d -> d.substring(5).replace("-", "/")).collect(Collectors.toList());
        List<MarkingCouponDataReportVo> couponTempDatalist = new LinkedList<>();
        for (String tj : tjList) {
            Optional<MarkingCouponDataReportVo> first = couponDatalist.stream().filter(c -> c.getCreateTime().equals(tj)).findFirst();
            if (!first.isPresent()) {
                MarkingCouponDataReportVo markingCouponDataReportVo = new MarkingCouponDataReportVo();
                markingCouponDataReportVo.setCreateTime(tj);
                markingCouponDataReportVo.setCouponCount(0);
                markingCouponDataReportVo.setCouponUserCount(0);
                markingCouponDataReportVo.setVerifyCount(0);
                markingCouponDataReportVo.setVerifyUserCount(0);
                couponTempDatalist.add(markingCouponDataReportVo);
                continue;
            }
            couponTempDatalist.add(first.get());
        }
        datamap.put("couponDataMap", couponTempDatalist);
        return new ResultData(datamap);
    }

    /**
     * 会员累计趋势
     * @param tenantId
     * @return
     */
    private ResultData getMemberJoinTrade(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        final int daysBefore = 29;
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        List<UserStructureVo> newCountVos = new ArrayList<>();//每日新增会员数
        int j = 1;
        for (int i = daysBefore; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            dto.setStartTime(c.getTime());
            c.add(Calendar.DAY_OF_YEAR, 1);
            dto.setEndTime(c.getTime());
            long count = wxCUserBasicInfoMapper.findCount(dto);
            UserStructureVo vo = new UserStructureVo();
            vo.setSortNum(j);
            j++;
            vo.setName(new SimpleDateFormat("MM/dd").format(dto.getStartTime()));
            vo.setCount(count);
            newCountVos.add(vo);
        }
        List<UserStructureVo> allCountVos = new ArrayList<>();//累计会员数
        c.clear();
        c.setTime(today);
        c.add(Calendar.DAY_OF_YEAR, -daysBefore);
        dto.setEndTime(c.getTime());
        dto.setStartTime(null);
        long firstDay = wxCUserBasicInfoMapper.findCount(dto);//统计的第一天总数
        int i = 0;
        long sumCount = 0;
        for (UserStructureVo v : newCountVos) {
            UserStructureVo vo = new UserStructureVo();
            sumCount += v.getCount();
            vo.setCount(firstDay + sumCount);
            vo.setName(v.getName());
            vo.setSortNum(i + 1);
            allCountVos.add(vo);
            i++;
        }
        datamap.put("allCountVos", allCountVos);//累计会员列表（ 日期和数量list）
        return new ResultData(datamap);
    }

    /**
     * 拓客渠道
     * @param tenantId
     * @return
     */
    private ResultData getFromChannelAnalysis(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        List<WxUserChannel> channelStructureList = new ArrayList<>();
        WxCUser wxCUser = new WxCUser();
        wxCUser.setTenantId(tenantId);
        List<WxUserChannel> channels = wxUserChannelMapper.findDistinctChannel();
        for (WxUserChannel w : channels) {
            WxUserChannel c = new WxUserChannel();
            c.setChannelName(w.getChannelName());
            PageInfo<WxUserChannel> page = PageHelper.startPage(1, 1000).doSelectPageInfo(() -> wxUserChannelMapper.findList(c));
            if (page.getSize() > 0) {
                List<String> sceneList = new ArrayList<>();
                for (WxUserChannel uc : page.getList()) {
                    List<String> scene = new ArrayList<>();
                    scene.add(uc.getSceneAddress());
                    wxCUser.setSceneList(scene);
                    sceneList.add(uc.getSceneAddress());
                }
                wxCUser.setSceneList(sceneList);
                WxUserChannel channelStructure = new WxUserChannel();
                channelStructure.setChannelName(w.getChannelName());
                channelStructure.setCount(wxCUserMapper.countByChannel(wxCUser));
                channelStructureList.add(channelStructure);
            }
        }
        datamap.put("channelList", channelStructureList);
        return new ResultData(datamap);
    }

    /**
     * 微信用户新增趋势
     * @param tenantId
     * @return
     */
    private ResultData getWechatMemberTrade(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        final int daysBefore = 29;
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        List<UserStructureVo> wxnewCountVos = new ArrayList<>();//每日新增会员数
        int j = 1;
        for (int i = daysBefore; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            dto.setStartTime(c.getTime());
            c.add(Calendar.DAY_OF_YEAR, 1);
            dto.setEndTime(c.getTime());
            long count = wxCUserMapper.findCount(dto);
            UserStructureVo vo = new UserStructureVo();
            vo.setSortNum(j);
            j++;
            vo.setName(new SimpleDateFormat("MM/dd").format(dto.getStartTime()));
            vo.setCount(count);
            wxnewCountVos.add(vo);
        }
        datamap.put("wxnewCountVos", wxnewCountVos);//新增会员列表（日期和数量list）
        return new ResultData(datamap);
    }

    /**
     * 会员新增趋势
     * @param tenantId
     * @return
     */
    private ResultData getNewMemberTrade(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        final int daysBefore = 29;
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        List<UserStructureVo> newCountVos = new ArrayList<>();//每日新增会员数
        int j = 1;
        for (int i = daysBefore; i >= 0; i--) {
            c.clear();
            c.setTime(today);
            c.add(Calendar.DAY_OF_YEAR, -i);
            dto.setStartTime(c.getTime());
            c.add(Calendar.DAY_OF_YEAR, 1);
            dto.setEndTime(c.getTime());
            long count = wxCUserBasicInfoMapper.findCount(dto);
            UserStructureVo vo = new UserStructureVo();
            vo.setSortNum(j);
            j++;
            vo.setName(new SimpleDateFormat("MM/dd").format(dto.getStartTime()));
            vo.setCount(count);
            newCountVos.add(vo);
        }
        datamap.put("newCountVos", newCountVos);//新增会员列表（日期和数量list）
        return new ResultData(datamap);
    }

    /**
     * 场景排名
     * @param tenantId
     * @return
     */
    private ResultData getSceneAnalysis(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        List<WxUserChannel> senceStructureList = new ArrayList<>();
        WxCUser wxCUser = new WxCUser();
        wxCUser.setTenantId(tenantId);
        List<WxUserChannel> channels = wxUserChannelMapper.findDistinctChannel();
        for (WxUserChannel w : channels) {
            WxUserChannel c = new WxUserChannel();
            c.setChannelName(w.getChannelName());
            PageInfo<WxUserChannel> page = PageHelper.startPage(1, 1000).doSelectPageInfo(() -> wxUserChannelMapper.findList(c));
            if (page.getSize() > 0) {
                for (WxUserChannel uc : page.getList()) {
                    List<String> scene = new ArrayList<>();
                    scene.add(uc.getSceneAddress());
                    wxCUser.setSceneList(scene);
                    WxUserChannel senceStructure = new WxUserChannel();
                    senceStructure.setDescription(uc.getDescription());
                    senceStructure.setCount(wxCUserMapper.countByChannel(wxCUser));
                    senceStructureList.add(senceStructure);
                }
            }
        }
        Collections.sort(senceStructureList, (s1, s2) -> ((int) (s2.getCount() - s1.getCount())));
        datamap.put("senceList", senceStructureList.subList(0, 10));
        return new ResultData(datamap);
    }

    /**
     * 会员性别比例   TODO
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getMemberSexRate(String tenantId, String startdate, String enddate) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        dto.setStartTime(DateUtils.stringToDate(startdate + " 00:00:00"));
        dto.setEndTime(DateUtils.stringToDate(enddate + " 23:59:59"));
        long all = wxCUserBasicInfoMapper.findCount(dto);
        List<UserStructureVo> vos = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        for (EnumAgeInfo a : EnumAgeInfo.values()) {
            c.clear();
            c.setTime(new Date());
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            long count = getCountByAge(a, c, dto);
            vos.add(getVo(count, all, a.getDesc(), a.getSortNum()));
        }
        return new ResultData(datamap);
    }

    /**
     * 会员绑定车牌率
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getMemberBindCar(String tenantId, String startdate, String enddate) {
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        dto.setStartTime(DateUtils.stringToDate(startdate + " 00:00:00"));
        dto.setEndTime(DateUtils.stringToDate(enddate + " 23:59:59"));
        long total = wxCUserBasicInfoMapper.findCount(dto);
        long userCountWithCar = wxCUserCarMapper.countUser(dto);
        Map userWithCar = new HashMap();
        userWithCar.put("title", "已绑定车牌");
        userWithCar.put("count", userCountWithCar);
        long userCountWithoutCar = total - userCountWithCar;
        Map userWithoutCar = new HashMap();
        userWithoutCar.put("title", "未绑定车牌");
        userWithoutCar.put("count", userCountWithoutCar);
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        if (userCountWithoutCar + userCountWithCar > 0) {
            userWithCar.put("percentage", nf.format(userCountWithCar / new Double(userCountWithoutCar + userCountWithCar).doubleValue()));
            userWithoutCar.put("percentage", nf.format(userCountWithoutCar / new Double(userCountWithoutCar + userCountWithCar).doubleValue()));
        } else {
            userWithCar.put("percentage", "--");
            userWithoutCar.put("percentage", "--");
        }
        List<Map> list = new ArrayList<>();
        list.add(userWithCar);
        list.add(userWithoutCar);
        return new ResultData(list);
    }

    /**
     * 会员年龄层次
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getMemberAgeAnalysis(String tenantId, String startdate, String enddate) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        dto.setStartTime(DateUtils.stringToDate(startdate + " 00:00:00"));
        dto.setEndTime(DateUtils.stringToDate(enddate + " 23:59:59"));
        long all = wxCUserBasicInfoMapper.findCount(dto);
        List<UserStructureVo> vos = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        for (EnumAgeInfo a : EnumAgeInfo.values()) {
            c.clear();
            c.setTime(new Date());
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            long count = getCountByAge(a, c, dto);
            vos.add(getVo(count, all, a.getDesc(), a.getSortNum()));
        }
        return new ResultData(datamap);
    }

    /**
     * 会员成长值
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getMemberGrowthAnalysis(String tenantId, String startdate, String enddate) {
        WxLevelConfig wxLevelConfig = new WxLevelConfig();
        wxLevelConfig.setTenantId(tenantId);
        wxLevelConfig.setSortColumns(BaseEntity.SortField.Points_ASC);
        List<WxLevelConfig> levelList = wxLevelConfigMapper.findList(wxLevelConfig);

        for (int i = 0; i < levelList.size(); i++) {

            WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
            dto.setTenantId(tenantId);
            dto.setStartTime(DateUtils.stringToDate(startdate + " 00:00:00"));
            dto.setEndTime(DateUtils.stringToDate(enddate + " 23:59:59"));
            if (i + 1 < levelList.size()) {
                dto.setLevelStartScore(levelList.get(i).getPoints());
                dto.setLevelEndScore(levelList.get(i + 1).getPoints());
            } else {
                dto.setLevelStartScore(levelList.get(i).getPoints());
            }

            long all = wxCUserBasicInfoMapper.findCountByScore(dto);

            levelList.get(i).setCount(all);
        }
        WxLevelConfig other = new WxLevelConfig();
        //没有等级的会员
        other.setLevel("无");
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        other.setCount(wxCUserBasicInfoMapper.findCount(dto)
                - levelList.stream().map(WxLevelConfig::getCount).reduce(Long::sum).orElse(0L));
        levelList.add(other);
        return new ResultData(levelList);
    }

    /**
     * 会员手机品牌
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getMobileBrandAnalysis(String tenantId, String startdate, String enddate) {
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        Date startTime = DateUtils.stringToDate(startdate + " 00:00:00");
        Date endTime = DateUtils.stringToDate(enddate + " 23:59:59");
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        long total = wxCUserBasicInfoMapper.findCount(dto);
        List<WxTags> tagList = new ArrayList<>();
        EnumTag[] tags = {EnumTag.ID_49,
                EnumTag.ID_50,
                EnumTag.ID_51,
                EnumTag.ID_52,
                EnumTag.ID_53,
                EnumTag.ID_54};
        for (int i = 0; i < tags.length; i++) {
            WxTags tag = new WxTags();
            tag.setName(tags[i].getMessage());
            tag.setCount(wxCUserTagsMapper.countUser(JSON.toJSONString(tags[i].getCode()), tenantId, startTime, endTime));
            tagList.add(tag);
            total -= tag.getCount();
        }

        WxTags tag = new WxTags();
        tag.setName("暂未获取");
        tag.setCount(total);
        tagList.add(tag);
        return new ResultData(tagList);
    }

    /**
     * 会员活跃度
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getMemActivity(String tenantId, String startdate, String enddate) {
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(tenantId);
        Date startTime = DateUtils.stringToDate(startdate + " 00:00:00");
        Date endTime = DateUtils.stringToDate(enddate + " 23:59:59");
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        long total = wxCUserBasicInfoMapper.findCount(dto);
        List<WxTags> tagList = new ArrayList<>();
        EnumTag[] tags = {
                EnumTag.ID_112,
                EnumTag.ID_111,
                EnumTag.ID_110
        };
        for (int i = 0; i < tags.length; i++) {
            WxTags tag = new WxTags();
            tag.setName(tags[i].getMessage());
            tag.setCount(wxCUserTagsMapper.countUser(JSON.toJSONString(tags[i].getCode()), tenantId, startTime, endTime));
            tagList.add(tag);
            total -= tag.getCount();
        }
        WxTags tag = new WxTags();
        tag.setName("休眠");
        tag.setCount(total);
        tagList.add(tag);
        return new ResultData(tagList);
    }

    /**
     * 卡营销数据
     * @param paramsMap
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getSaleCardAnalysis(Map<String, String> paramsMap, String startdate, String enddate) {
        WxCoupon wxCoupon = new WxCoupon();

        //默认时间本月第一天，截止到当天
        if (StringUtils.isEmpty(paramsMap.get("startdate"))) {
            wxCoupon.setStartdate(DateUtils.getFirstDayForCurrMonth());
        }else{
            Date startTime = DateUtils.stringToDate(startdate);
            wxCoupon.setStartdate(startTime);
        }
        if (StringUtils.isEmpty(paramsMap.get("enddate"))) {
            wxCoupon.setEnddate(new Date());
        }else{
            Date endTime = DateUtils.stringToDate(enddate, "yyyy-MM-dd HH:mm:ss");
            wxCoupon.setEnddate(endTime);
        }

        Map<String,Object> result = new HashedMap();
        List<WxCouponStatisVo> saleMoneyList = wxCouponService.findSaleMoneyByDate(wxCoupon);
        List<WxCouponStatisVo> paymentList = wxCouponService.findPaymentByDate(wxCoupon);
        Map<String,String> saleMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());
        Map<String,String> payMentMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());

        for (WxCouponStatisVo coupon:saleMoneyList){
            saleMap.put(coupon.getXtime(),coupon.getXcount());
        }
        for (WxCouponStatisVo coupon:paymentList){
            payMentMap.put(coupon.getXtime(),coupon.getXcount());
        }
        result.put("saleHistory",saleMap);
        result.put("paymentHistory",payMentMap);
        result.put("saleCardCount",wxCouponService.findSaleCardCount(wxCoupon));
        result.put("tranCount",wxCouponService.findTranCardCount(wxCoupon));
        result.put("subsidyCount",wxCouponService.findSubsidyMoney(wxCoupon));
        return new ResultData(result);
    }

    /**
     * 券营销数据
     * @param paramsMap
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getSaleCouponAnalysis(Map<String, String> paramsMap, String startdate, String enddate) {
        WxCoupon wxCoupon = new WxCoupon();
        Map<String,Object> result = new HashedMap();

        //默认时间本月第一天，截止到当天
        if (StringUtils.isEmpty(paramsMap.get("startdate"))) {
            wxCoupon.setStartdate(DateUtils.getFirstDayForCurrMonth());
        }else{
            Date startTime = DateUtils.stringToDate(startdate);
            wxCoupon.setStartdate(startTime);
        }
        if (StringUtils.isEmpty(paramsMap.get("enddate"))) {
            wxCoupon.setEnddate(new Date());
        }else{
            Date endTime = DateUtils.stringToDate(enddate, "yyyy-MM-dd HH:mm:ss");
            wxCoupon.setEnddate(endTime);
        }
        List<WxCouponStatisVo> orderCountList = wxCouponService.findCouponOrderCount(wxCoupon);
        List<WxCouponStatisVo> paymentCountList = wxCouponService.findCouponPaymentCount(wxCoupon);
        List<WxCouponStatisVo> priceCouponSaleCountList = wxCouponService.priceCouponSaleCount(wxCoupon);
        List<WxCouponStatisVo> priceCouponPaymentCountList = wxCouponService.priceCouponPaymentCount(wxCoupon);
        Long priceCouponCancelCount = wxCouponService.priceCouponCancelCount(wxCoupon);

        Map<String,String> orderCountMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());
        Map<String,String> paymentCountMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());
        Map<String,String> priceCouponSaleCountMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());
        Map<String,String> priceCouponPaymentCountMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());

        for (WxCouponStatisVo coupon:orderCountList){
            orderCountMap.put(coupon.getXtime(),coupon.getXcount());
        }
        for (WxCouponStatisVo coupon:paymentCountList){
            paymentCountMap.put(coupon.getXtime(),coupon.getXcount());
        }
        for (WxCouponStatisVo coupon:priceCouponSaleCountList){
            priceCouponSaleCountMap.put(coupon.getXtime(),coupon.getXcount());
        }
        for (WxCouponStatisVo coupon:priceCouponPaymentCountList){
            priceCouponPaymentCountMap.put(coupon.getXtime(),coupon.getXcount());
        }
        result.put("orderCountList",orderCountMap);
        result.put("paymentCountList",paymentCountMap);
        result.put("priceCouponSaleCountList",priceCouponSaleCountMap);
        result.put("priceCouponPaymentCountList",priceCouponPaymentCountMap);
        result.put("sumPriceSaleMoney",wxCouponService.findSumPriceSaleMoney(wxCoupon));
        result.put("sumPricePayMent",wxCouponService.findSumPricePayMent(wxCoupon));
        result.put("sumSubsidyMoney",wxCouponService.findSumSubsidyMoney(wxCoupon));
        result.put("priceCouponCancelCount",priceCouponCancelCount);//有价卷退款数量

        //有价券售出数量
        int total = 0;
        for (WxCouponStatisVo couponStatisVo:priceCouponSaleCountList) {
            total += Integer.parseInt(couponStatisVo.getXcount());
        }
        result.put("priceCouponSaleCountListTotal",total);
        return new ResultData(result);
    }

    /**
     * 砍价营销数据
     * @param paramsMap
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getSalePressAnalysis(Map<String, String> paramsMap, String tenantId, String startdate, String enddate) {
        WxCoupon wxCoupon = new WxCoupon();
        Map<String,Object> result = new HashedMap();

        //默认时间本月第一天，截止到当天
        if (StringUtils.isEmpty(paramsMap.get("startdate"))) {
            wxCoupon.setStartdate(DateUtils.getFirstDayForCurrMonth());
        }else{
            Date startTime = DateUtils.stringToDate(startdate);
            wxCoupon.setStartdate(startTime);
        }
        if (StringUtils.isEmpty(paramsMap.get("enddate"))) {
            wxCoupon.setEnddate(new Date());
        }else{
            Date endTime = DateUtils.stringToDate(enddate, "yyyy-MM-dd HH:mm:ss");
            wxCoupon.setEnddate(endTime);
        }
        List<WxCouponStatisVo> pressSendHistory = wxCouponService.pressSendHistory(wxCoupon);
        List<WxCouponStatisVo> pressSuccHistory = wxCouponService.pressSuccHistory(wxCoupon);
        List<WxCouponStatisVo> pressPaymentHistory = wxCouponService.pressPaymentHistory(wxCoupon);

        Map<String,String> pressSendHistoryMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());
        Map<String,String> pressSuccHistoryMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());
        Map<String,String> pressPaymentHistoryMap = getDateMap(wxCoupon.getStartdate(),wxCoupon.getEnddate());

        for (WxCouponStatisVo coupon:pressSendHistory){
            pressSendHistoryMap.put(coupon.getXtime(),coupon.getXcount());
        }
        for (WxCouponStatisVo coupon:pressSuccHistory){
            pressSuccHistoryMap.put(coupon.getXtime(),coupon.getXcount());
        }
        for (WxCouponStatisVo coupon:pressPaymentHistory){
            pressPaymentHistoryMap.put(coupon.getXtime(),coupon.getXcount());
        }
        result.put("pressSendHistory",pressSendHistoryMap);
        result.put("pressSuccHistory",pressSuccHistoryMap);
        result.put("pressPaymentHistory",pressPaymentHistoryMap);

        wxCoupon.setTenantId(tenantId);

        result.put("pressSendHistoryTotal",getTotal(pressSendHistoryMap));
        result.put("pressSuccHistoryCount",getTotal(pressSuccHistoryMap));
        result.put("pressPaymentHistoryCount",getTotal(pressPaymentHistoryMap));

        result.put("pressSuccRate",wxCouponService.pressSuccRate(wxCoupon));
        result.put("sumJoin",wxCouponService.sumJoin(wxCoupon));
        return new ResultData(result);
    }

    public int getTotal(Map<String,String> map){
        int tatal = 0;
        for (String key:map.keySet()) {
            tatal += Integer.parseInt(map.get(key));
        }
        return tatal;
    }

    /**
     * 拼团营销数据
     * @param paramsMap
     * @param tenantId
     * @param startdate
     * @return
     */
    private ResultData getSaleGroupAnalysis(Map<String, String> paramsMap, String tenantId, String startdate) {
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        //默认时间本月第一天，截止到当天
        Map<String, Object> result = new HashMap<>();
        Date startTime = new Date();
        Date endTime = startTime;
        if (StringUtils.isEmpty(paramsMap.get("startdate"))) {
            startTime = DateUtils.getFirstDayForCurrMonth();
            params.put("startdate", startTime);
        } else {
            startTime = DateUtils.stringToDate(startdate + " 00:00:00");
            params.put("startdate", startTime);
        }
        if (StringUtils.isEmpty(paramsMap.get("enddate"))) {
            params.put("enddate", endTime);
        } else {
            endTime = DateUtils.stringToDate(paramsMap.get("enddate") + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
            params.put("enddate", paramsMap.get("enddate") + " 23:59:59");
        }
        List<Map<String, Object>> successlist = wxOrderGroupMapper.queryOrderGroupSuccessCountAndTime(params);
        List<Map<String, Object>> verifyList = wxOrderGroupMapper.queryOrderGroupVerifyCountAndTime(params);

        Map<String, String> successMap = getDateMap(startTime, endTime);
        Map<String, String> verifyMap = getDateMap(startTime, endTime);

        long successCount = wxOrderGroupMapper.queryOrderGroupSuccessCount(params);
        long groupCount = wxOrderGroupMapper.queryOrderGroupCount(params);
        long peopleCount = wxOrderGroupMapper.queryOrderGroupPeopleCount(params);
        long verifyCount = wxOrderGroupMapper.queryOrderGroupVerifyCount(params);
        long successPeopleCount = wxOrderGroupMapper.queryOrderGroupSuccessPeopleCount(params);


        double transferRatio = 0;
        if (groupCount > 0) {
            double transfer = (double) successCount / groupCount * 100;
            transferRatio = new BigDecimal(transfer).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }

        Map<String, String> successListMap = successlist.parallelStream().collect(Collectors.toMap(x -> {
            return x.get("time").toString();
        }, x -> {
            return x.get("total").toString();
        }));

        Map<String, String> verifyListMap = verifyList.parallelStream().collect(Collectors.toMap(x -> {
            return x.get("time").toString();
        }, x -> {
            return x.get("total").toString();
        }));

        successMap.putAll(successListMap);
        verifyMap.putAll(verifyListMap);

        result.put("successList", successMap);
        result.put("verifyList", verifyMap);

        result.put("successCount", successCount);
        result.put("groupCount", groupCount);
        result.put("peopleCount", peopleCount);
        result.put("transferRatio", transferRatio);
        result.put("verifyCount", verifyCount);
        result.put("successPeopleCount", successPeopleCount);

        return new ResultData(result);
    }

    /**
     * 昨日解单率
     * @param tenantId
     * @return
     */
    private ResultData getYesterdayTradeRate(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxMerchant wxMerchant = new WxMerchant();
        wxMerchant.setTenantId(tenantId);
        wxMerchant.setStatus(1);
        List<WxMerchant> merchants = wxMerchantMapper.findList(wxMerchant);
        WxMerchantTradeDaily wxMerchantTradeDaily = new WxMerchantTradeDaily();
        wxMerchantTradeDaily.setTenantId(tenantId);
        String reportdate = DateUtils.getTimeBefore(1, new Date());
        wxMerchantTradeDaily.setReportDate(reportdate);
        List<WxMerchantTradeDaily> tradelist = wxMerchantTradeDailyMapper.findList(wxMerchantTradeDaily);
        int merchantsize = merchants.size();
        int tradesize = tradelist.size();
        if (merchantsize > 0 && tradesize > 0) {
            double shsbld = ((double) tradesize / merchantsize) * 100;
            double shsbl = new BigDecimal(shsbld).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            datamap.put("shsbl", shsbl);
        } else {
            datamap.put("shsbl", 0);
        }
        int shsbjg = tradelist.stream().mapToInt(WxMerchantTradeDaily::getTradeAmtInteger).sum();
        datamap.put("shsbjg", shsbjg);
        return new ResultData(datamap);
    }

    /**
     * 出租率
     * @param tenantId
     */
    private ResultData getRentRate(String tenantId) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxShop wxShop = new WxShop();
        wxShop.setTenantId(tenantId);
        wxShop.setStatus(EnumShopStatus.RENT.getCode());
        List<WxShop> yczlist = wxShopMapper.findList(wxShop);
        wxShop.setStatus(EnumShopStatus.NOT_RENT.getCode());
        List<WxShop> wczlist = wxShopMapper.findList(wxShop);
        //出租与未出租
        int yczsize = yczlist.size();
        int wczsize = wczlist.size();
        int size = yczsize + wczsize;
        if (size == 0) {
            datamap.put("yczsl", 0);
            datamap.put("wczsl", 0);
            datamap.put("yczl", 0);
            datamap.put("wczl", 0);
        } else {
            datamap.put("yczsl", yczsize);
            datamap.put("wczsl", wczsize);
            double yczld = ((double) yczsize / size) * 100;
            double dczl = new BigDecimal(yczld).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            double wczld = ((double) wczsize / size) * 100;
            double wczl = new BigDecimal(wczld).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            datamap.put("yczl", dczl);
            datamap.put("wczl", wczl);
        }
        return new ResultData(datamap);
    }

    /**
     * 租金收缴率
     * @param tenantId
     * @param startdate
     * @param enddate
     * @return
     */
    private ResultData getRentMoneyRate(String tenantId, String startdate, String enddate) {
        HashMap<String, Object> datamap = new HashMap<>();
        //租金
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("startdate", startdate + " 00:00:00");
        params.put("enddate", enddate + " 23:59:59");
        Map<String, Object> payinfo = wxBillRentMapper.queryPayInfo(params);
        if (payinfo != null) {
            BigDecimal receivepay = (BigDecimal) payinfo.get("receivepay");
            BigDecimal pay = (BigDecimal) payinfo.get("pay");
            if (receivepay.doubleValue() > 0) {
                BigDecimal divide = pay.divide(receivepay, 2, BigDecimal.ROUND_HALF_UP);
                double zjcjl = divide.multiply(new BigDecimal(100)).doubleValue();
                datamap.put("ysje", receivepay);
                datamap.put("ssje", pay);
                datamap.put("zjsjl", zjcjl);
            } else {
                datamap.put("ysje", 0);
                datamap.put("ssje", 0);
                datamap.put("zjsjl", 0);
            }
        } else {
            datamap.put("ysje", 0);
            datamap.put("ssje", 0);
            datamap.put("zjsjl", 0);
        }
        return new ResultData(datamap);
    }


    private long getCountByAge(EnumAgeInfo a, Calendar c, WxCUserBasicInfoDto dto) {
        if (a.getStart() != 0 || a.getEnd() != 0) {
            c.add(Calendar.YEAR, -a.getEnd());
            Date startTime = c.getTime();
            c.clear();
            c.setTime(startTime);
            c.add(Calendar.YEAR, a.getEnd() - a.getStart());
            Date endTime = c.getTime();
            dto.setBirthStartTime(startTime);
            dto.setBirthEndTime(endTime);
        } else {

            dto.setBirthStartTime(null);
            dto.setBirthEndTime(null);
        }

        return wxCUserBasicInfoMapper.findCountByAge(dto);
    }

    private UserStructureVo getVo(long count, long all, String name, Integer num) {
        UserStructureVo vo = new UserStructureVo();
        vo.setSortNum(num);
        vo.setName(name);
        vo.setCount(count);
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);//控制保留小数点后几位，2：表示保留2位小数点
        if (all > 0) {
            vo.setPercentage(nf.format(new Long(count).doubleValue() / new Long(all).doubleValue()));
        } else {
            vo.setPercentage("0.00%");
        }
        return vo;
    }

    public static Map<String,String> getDateMap(Date begin, Date end) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Map<String,String> map = new LinkedHashMap<>();
        map.put(format.format(begin), "0");
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(begin);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(end);
        calEnd.add(Calendar.DAY_OF_MONTH, -1);
        end = calEnd.getTime();
        while (calBegin.getTime().before(end)) {
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            map.put(format.format(calBegin.getTime()), "0");
        }
        return map;
    }

    /**
     * 首页商铺出租数据
     * @param paramMap
     * @return
     */
    private ResultData getIndexShopRentData(Map<String, String> paramMap) {
        HashMap<String, Object> datamap = new HashMap<>();
        WxShop query = new WxShop();
        String tenantId = paramMap.get("tenantId");
        String building = paramMap.get("building");
        String floor = paramMap.get("floor");
        String business = paramMap.get("businessId");

        if (StringUtils.isNotEmpty(tenantId)) {
            query.setTenantId(tenantId);
        }
        if (StringUtils.isNotEmpty(building)) {
            query.setBuilding(Long.valueOf(building));
        }
        if (StringUtils.isNotEmpty(floor)) {
            query.setFloor(Long.valueOf(floor));
        }
        if (StringUtils.isNotEmpty(business)) {
            query.setBusinessId(Integer.valueOf(business));
        }
        query.setType(null);
        Long total = wxShopMapper.getCountByWxShop(query);
        query.setType(EnumRentShopType.SHOP.getCode());
        Long totalShop = wxShopMapper.getCountByWxShop(query);
        query.setType(EnumRentShopType.POINT.getCode());
        Long totalPoint = wxShopMapper.getCountByWxShop(query);

        query.setType(null);
        query.setStatus(EnumShopStatus.RENT.getCode());
        Long rentTotal = wxShopMapper.getCountByWxShop(query);
        query.setType(EnumRentShopType.SHOP.getCode());
        Long rentTotalShop = wxShopMapper.getCountByWxShop(query);
        query.setType(EnumRentShopType.POINT.getCode());
        Long rentTotalPoint = wxShopMapper.getCountByWxShop(query);

        query.setType(null);
        query.setStatus(EnumShopStatus.NOT_RENT.getCode());
        Long notRentTotal = wxShopMapper.getCountByWxShop(query);
        query.setType(EnumRentShopType.SHOP.getCode());
        Long notRentTotalShop = wxShopMapper.getCountByWxShop(query);
        query.setType(EnumRentShopType.POINT.getCode());
        Long notRentTotalPoint = wxShopMapper.getCountByWxShop(query);

        datamap.put("total",total);
        datamap.put("totalShop",totalShop);
        datamap.put("totalPoint",totalPoint);

        datamap.put("rentTotal",rentTotal);
        datamap.put("rentTotalShop",rentTotalShop);
        datamap.put("rentTotalPoint",rentTotalPoint);

        datamap.put("notRentTotal",notRentTotal);
        datamap.put("notRentTotalShop",notRentTotalShop);
        datamap.put("notRentTotalPoint",notRentTotalPoint);

        if(total == 0){
            datamap.put("rentTotalRate",0);
        }else{
            double totalRentRate = new Double(rentTotal)/new Double(total)*100;
            datamap.put("rentTotalRate",formatDouble(totalRentRate));
        }
        if(totalShop == 0){
            datamap.put("rentTotalShopRate",0);
        }else{
            double rentTotalShopRate =  new Double(rentTotalShop)/ new Double(totalShop)*100;
            datamap.put("rentTotalShopRate",formatDouble(rentTotalShopRate));
        }
        if(totalPoint == 0){
            datamap.put("rentTotalPointRate",0);
        }else{
            double rentTotalPointRate =  new Double(rentTotalPoint)/ new Double(totalPoint)*100;
            datamap.put("rentTotalPointRate",formatDouble(rentTotalPointRate));
        }
        return new ResultData(datamap);
    }

    /**
     * 费用收缴数据
     * @param tenantId
     * @return
     */
    private ResultData getBillReceRate(String tenantId, String startDateStr) {
        HashMap<String, Object> datamap = new HashMap<>();
        Date startDate = DateUtils.getDateFromString(startDateStr,"yyyy-MM-dd HH:mm:ss").getTime();
        startDate = DateUtils.getFirstDayForCurrMonth(startDate);
        Date endDate = DateUtils.getLastDayForMonth(startDate);

        //租金收缴率 ysje 应收金额 ssje 实收金额 zjsjl收缴率
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        params.put("startdate", DateUtils.date2String(startDate,"yyyy-MM-dd") + " 00:00:00");
        params.put("enddate", DateUtils.date2String(endDate,"yyyy-MM-dd") + " 23:59:59");
        Map<String, Object> payinfo = wxBillRentMapper.queryPayInfoTotal(params);
        if (payinfo != null) {
            Double receivepay = ((BigDecimal) payinfo.get("receivepay")).doubleValue();
            Double pay = ((BigDecimal) payinfo.get("pay")).doubleValue();
            if (receivepay.doubleValue() > 0) {
                Double divide = pay/receivepay*100;
                datamap.put("rentysje", receivepay);
                datamap.put("rentssje", pay);
                datamap.put("rentzjsjl", formatDouble(divide));
            } else {
                datamap.put("rentysje", 0);
                datamap.put("rentssje", 0);
                datamap.put("rentzjsjl", 0);
            }
        } else {
            datamap.put("rentysje", 0);
            datamap.put("rentssje", 0);
            datamap.put("rentzjsjl", 0);
        }

        //物业费收缴率
        payinfo = wxBillPropertyMapper.queryPayInfoTotal(params);
        if (payinfo != null) {
            Double receivepay = ((BigDecimal) payinfo.get("receivepay")).doubleValue();
            Double pay = ((BigDecimal) payinfo.get("pay")).doubleValue();
            if (receivepay.doubleValue() > 0) {
                Double divide = pay/receivepay*100;
                datamap.put("propertyysje", receivepay);
                datamap.put("propertyssje", pay);
                datamap.put("propertyzjsjl", formatDouble(divide));
            } else {
                datamap.put("propertyysje", 0);
                datamap.put("propertyssje", 0);
                datamap.put("propertyzjsjl", 0);
            }
        } else {
            datamap.put("propertyysje", 0);
            datamap.put("propertyssje", 0);
            datamap.put("propertyzjsjl", 0);
        }

        //押金收缴率
        payinfo = wxBillDepositMapper.queryPayInfoAllTotal(params);
        if (payinfo != null) {
            Double receivepay = ((BigDecimal) payinfo.get("receivepay")).doubleValue();
            Double pay = ((BigDecimal) payinfo.get("pay")).doubleValue();
            if (receivepay.doubleValue() > 0) {
                Double divide = pay/receivepay* 100;
                datamap.put("depositysje", receivepay);
                datamap.put("depositssje", pay);
                datamap.put("depositzjsjl", formatDouble(divide));
            } else {
                datamap.put("depositysje", 0);
                datamap.put("depositssje", 0);
                datamap.put("depositzjsjl", 0);
            }
        } else {
            datamap.put("depositysje", 0);
            datamap.put("depositssje", 0);
            datamap.put("depositzjsjl", 0);
        }

        //其他费用收缴率
        payinfo = wxBillOtherMapper.queryPayInfoTotal(params);
        if (payinfo != null) {
            Double receivepay = ((BigDecimal) payinfo.get("receivepay")).doubleValue();
            Double pay = ((BigDecimal) payinfo.get("pay")).doubleValue();
            if (receivepay.doubleValue() > 0) {
                Double divide = pay/receivepay*100;
                datamap.put("otherysje", receivepay);
                datamap.put("otherssje", pay);
                datamap.put("otherzjsjl",formatDouble(divide));
            } else {
                datamap.put("otherysje", 0);
                datamap.put("otherssje", 0);
                datamap.put("otherzjsjl", 0);
            }
        } else {
            datamap.put("otherysje", 0);
            datamap.put("otherssje", 0);
            datamap.put("otherzjsjl", 0);
        }

        //==========欠缴数据=========
        BigDecimal totalOwe = new BigDecimal(0);
        WxBillAll wxBillAll = new WxBillAll();
        wxBillAll.setTenantId(tenantId);
        wxBillAll.setMonth(new SimpleDateFormat("yyyy-MM").format(startDate));
        wxBillAll.setStatus(EnumBillRentStatus.NOT_PAID.getCode());
        List<Integer> billTypeList = new ArrayList<>();
        billTypeList.add(EnumBillTypeStr.RENT.getCode());
        wxBillAll.setBillTypeList(billTypeList);
        payinfo = wxBillAllMapper.queryOweInfo(wxBillAll);
        if (payinfo != null) {
            BigDecimal owe = ((BigDecimal) payinfo.get("owe")).divide(new BigDecimal(100));
            totalOwe = totalOwe.add(owe);
            datamap.put("rentOwe", owe);
        } else {
            datamap.put("rentOwe", 0);
        }

        billTypeList = new ArrayList<>();
        billTypeList.add(EnumBillTypeStr.PROPERTY.getCode());
        wxBillAll.setBillTypeList(billTypeList);
        payinfo = wxBillAllMapper.queryOweInfo(wxBillAll);
        if (payinfo != null) {
            BigDecimal owe = ((BigDecimal) payinfo.get("owe")).divide(new BigDecimal(100));
            totalOwe = totalOwe.add(owe);
            datamap.put("propertyOwe", owe);
        } else {
            datamap.put("propertyOwe", 0);
        }

        billTypeList = new ArrayList<>();
        billTypeList.add(EnumBillTypeStr.O_D.getCode());
        billTypeList.add(EnumBillTypeStr.PROPERTY_D.getCode());
        billTypeList.add(EnumBillTypeStr.RENT_D.getCode());
        wxBillAll.setBillTypeList(billTypeList);
        payinfo = wxBillAllMapper.queryOweInfo(wxBillAll);
        if (payinfo != null) {
            BigDecimal owe = ((BigDecimal) payinfo.get("owe")).divide(new BigDecimal(100));
            totalOwe = totalOwe.add(owe);
            datamap.put("depositOwe", owe);
        } else {
            datamap.put("depositOwe", 0);
        }

        billTypeList = new ArrayList<>();
        billTypeList.add(EnumBillTypeStr.D.getCode());
        billTypeList.add(EnumBillTypeStr.W.getCode());
        billTypeList.add(EnumBillTypeStr.K.getCode());
        billTypeList.add(EnumBillTypeStr.O.getCode());
        wxBillAll.setBillTypeList(billTypeList);
        payinfo = wxBillAllMapper.queryOweInfo(wxBillAll);
        if (payinfo != null) {
            BigDecimal owe = ((BigDecimal) payinfo.get("owe")).divide(new BigDecimal(100));
            totalOwe = totalOwe.add(owe);
            datamap.put("otherOwe", owe);
        } else {
            datamap.put("otherOwe", 0);
        }

        datamap.put("totalOwe", totalOwe);
        return new ResultData(datamap);
    }

    public double formatDouble(Double d){
        String s = d+"";
        int index = s.indexOf(".");
        if(index == -1){
            logger.info("formatDouble is -1 d:"+d);
            return d;
        }
        String lt = s.substring(index,s.length());
        if(lt.length() >3){
            s = s.substring(0,s.indexOf(".")+3);
        }
        return Double.parseDouble(s);
    }

    /**
     * 营销数据
     * @param tenantId
     * @return
     */
    private ResultData getSaleDataHistory(String tenantId, String startdate,String enddate) {
        Date startDate = DateUtils.getDateFromString(startdate,"yyyy-MM-dd HH:mm:ss").getTime();
        Date endDate = DateUtils.getDateFromString(enddate,"yyyy-MM-dd HH:mm:ss").getTime();

        HashMap<String, Object> datamap = new HashMap<>();
        List<String> days = DateUtils.getTjTimeList(new SimpleDateFormat("yyyy-MM-dd").format(startDate),new SimpleDateFormat("yyyy-MM-dd").format(endDate),"0");
        TreeMap<String, Object> historyMap;
        Map<String, Integer> countMap;
        WxCoupon couponQuery = new WxCoupon();
        couponQuery.setTenantId(tenantId);
        couponQuery.setStartdate(startDate);
        couponQuery.setEnddate(endDate);

        //卡数据
        List<WxCouponStatisVo> couponStatisVoList = wxCouponService.findSaleCardCountHistory(couponQuery);
        countMap = couponStatisVoList.stream().collect(Collectors.toMap(WxCouponStatisVo::getXtime, p -> Integer.parseInt(p.getXcount())));
        historyMap = new TreeMap<>();
        for (String date:days) {
            historyMap.put(date.substring(5,date.length()).replace("-","/"),"0");
        }
        for (String key : countMap.keySet()) {
            String keySub = key.substring(5,key.length()).replace("-","/");
            historyMap.put(keySub,countMap.get(key));
        }
        datamap.put("cardHistory",historyMap);

        //砍价数据
        List<WxCouponStatisVo> wxCouponStatisVoList = wxCouponService.pressSendHistory(couponQuery);
        Map<String,String> countHistoryMap = getDateMap(startDate,endDate);
        for (WxCouponStatisVo coupon:wxCouponStatisVoList){
            countHistoryMap.put(coupon.getXtime(),coupon.getXcount());
        }
        datamap.put("pressSendHistory",countHistoryMap);

        //拼团
        wxCouponStatisVoList = wxOrderGroupMapper.queryOrderGroupCountHistory(couponQuery);
        countHistoryMap = getDateMap(startDate,endDate);
        for (WxCouponStatisVo coupon:wxCouponStatisVoList){
            countHistoryMap.put(coupon.getXtime(),coupon.getXcount());
        }
        datamap.put("groupHistory",countHistoryMap);

        //卷数据
        wxCouponStatisVoList = wxCouponService.findCouponOrderCount(couponQuery);
        countHistoryMap = getDateMap(startDate,endDate);
        for (WxCouponStatisVo coupon:wxCouponStatisVoList){
            countHistoryMap.put(coupon.getXtime(),coupon.getXcount());
        }
        datamap.put("couponHistory",countHistoryMap);

        return new ResultData(datamap);
    }

}


