package com.hzs.report.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.TableNameConstants;
import com.hzs.common.core.enums.ETradeType;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.system.config.BdAccount;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.report.member.mapper.MemberReportMapper;
import com.hzs.report.member.param.ProductDetailQueryParam;
import com.hzs.report.member.service.MemberReportService;
import com.hzs.report.member.vo.*;
import com.hzs.report.report.service.ICuMemberSettlePeriodService;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAccountServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MemberReportServiceImpl implements MemberReportService {

    @Resource
    private MemberReportMapper memberReportMapper;
    @Autowired
    private ICuMemberSettlePeriodService iCuMemberSettlePeriodService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    IAccountServiceApi iAccountServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;

    @Override
    public List<DirectPushNewVo> directPushNewList(List<String> memberCodeList,
                                                   Integer pkCountry, Date startPayTime,
                                                   Date endPayTime) {
        return memberReportMapper.directPushNewList(memberCodeList, pkCountry, startPayTime, endPayTime);
    }

    @Override
    public List<DirectPushNewVo> directPushNewAchieList(DirectPushNewVo dpo, List<Long> pkMemberList) {
        return memberReportMapper.directPushNewAchieList(dpo, pkMemberList);
    }

    @Override
    public List<DirectPushBoxVo> directPushNewBoxList(DirectPushBoxVo dpb, List<DirectPushBoxVo> dpbList) {
        return memberReportMapper.directPushNewBoxList(dpb, dpbList);
    }

    @Override
    public List<DirectPushNewVo> directPushNewAchieUpList(DirectPushNewVo dpo, List<Long> pkMemberList) {
        return memberReportMapper.directPushNewAchieUpList(dpo, pkMemberList);
    }

    @Override
    public List<MemberConsumptionVo> memberConsumptionList(String memberCode, String memberName, Date startPayTime, Date endPayTime, Integer pkWares) {
        return memberReportMapper.memberConsumptionList(memberCode, memberName, startPayTime, endPayTime, pkWares);
    }

    @Override
    public List<MemberResettleAchieveVo> memberResettleAchieve(Long pkMember, String memberName, Date startPayTime, Date endPayTime, Integer pkVertex, Integer pkTeamCode, Integer pkCountry, Integer pkAwards, List<Integer> orderTypeList) {
        return memberReportMapper.memberResettleAchieve(pkMember, memberName, startPayTime, endPayTime, pkVertex, pkTeamCode, pkCountry, pkAwards, orderTypeList);
    }

    @Override
    public List<MemberResettleAchieveVo> selectBrollyNewABAchieve(Long pkMember, String memberName, Date startPayTime, Date endPayTime, Integer pkVertex,
                                                                  Integer pkTeamCode, Integer pkCountry, Integer pkAwards, String achieveTableName,
                                                                  int period) {
        return memberReportMapper.selectBrollyNewABAchieve(pkMember, memberName, startPayTime, endPayTime,
                pkVertex, pkTeamCode, pkCountry, pkAwards, achieveTableName, period);
    }

    @Override
    public List<OrderCurrencyVo> getOrderCurrencyList(String memberCode, String memberName, String orderCode, Integer orderType) {
        return memberReportMapper.getOrderCurrencyList(memberCode, memberName, orderCode, orderType);
    }

    @Override
    public List<MemberTradeVo> getBySourceCodeMemberTradeList(List<String> orderCodeList) {
        return memberReportMapper.getBySourceCodeMemberTradeList(orderCodeList);
    }

    @Override
    public List<OrderDistribution> getByProvinceOrderDistribution(Date startTime, Date endTime, Integer pkCountry) {
        return memberReportMapper.getByProvinceOrderDistribution(startTime, endTime, pkCountry);
    }

    @Override
    public List<OrderDistribution> getByCityOrderDistribution(Date startTime, Date endTime, Integer pkCountry) {
        return memberReportMapper.getByCityOrderDistribution(startTime, endTime, pkCountry);
    }

    @Override
    public List<OrderDistribution> getByDistrictOrderDistribution(Date startTime, Date endTime, Integer pkCountry) {
        return memberReportMapper.getByDistrictOrderDistribution(startTime, endTime, pkCountry);
    }

    @Override
    public List<ProductOrderInfoVo> getProductOrderInfo(String productName, Integer pkClassify, Date startTime, Date endTime, Integer pkCountry, List<Integer> orderTypeList) {
        return memberReportMapper.getProductOrderInfo(productName, pkClassify, startTime, endTime, pkCountry, orderTypeList);
    }

    @Override
    public List<ReportSummaryVo> reportSummaryList(ReportSummaryVo reportSummaryVo) {
        return memberReportMapper.reportSummaryList(reportSummaryVo);
    }

    @Override
    public List<ProductShippingDetailsInfoVo> productShippingDetailsList(Integer pkProduct, String productName, Integer pkClassify, Integer pkAwards, List<Integer> orderTypeList, Date startTime, Date endTime, Integer pkCountry) {
        return memberReportMapper.productShippingDetailsList(pkProduct, productName, pkClassify, pkAwards, orderTypeList, startTime, endTime, pkCountry);
    }

    @Override
    public List<ProductDetailQueryVo> productDetailQueryList(ProductDetailQueryParam productDetailQueryParam) {
        return memberReportMapper.productDetailQueryList(productDetailQueryParam);
    }

    @Override
    public List<SmallAreaNewAddAchieveVO> selectSmallAreaNewAdd(SmallAreaNewAddAchieveVO addAchieveVO) {
        List<SmallAreaNewAddAchieveVO> areaNewAddAchieveVOList = null;
        //小区新增业绩
        //先计算开始时间减一天期数的业绩，算出大小区，再查询大小区的业绩（历史的）
        //查询时间段内的新增：查询会员表中新增会员的业绩左右区都大于参数的业绩，再区分大小区业绩
        String startDate = addAchieveVO.getStartDate();
        //开始时间的前一天
        LocalDate beforeLocalDate = DateUtils.getStringToLocalDate(startDate).minus(1, ChronoUnit.DAYS);
        //获取期数
        String date = beforeLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //开始时间减一天的期数
        int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date).getPkId();
        addAchieveVO.setBeforePeriod(period);
        //查询大小区业绩表
        addAchieveVO.setSettleTable(getMonthTableName(beforeLocalDate));
        addAchieveVO.setMonthAchieveVOList(getAchieveMonthTable(startDate, addAchieveVO.getEndDate()));
        if (addAchieveVO.getAchieve().compareTo(new BigDecimal("10000")) > -1) {
            //查询开始时间前一天大小区的新增业绩
            areaNewAddAchieveVOList = memberReportMapper.selectSmallAreaNewAdd(addAchieveVO);
            //查询时间段时新增会员的大小区新增业绩
            List<SmallAreaNewAddAchieveVO> newMemberList = memberReportMapper.selectSmallAreaNewAddNemMember(addAchieveVO);
            if (CollUtil.isNotEmpty(newMemberList)) {
                areaNewAddAchieveVOList.addAll(newMemberList);
            }
        } else {
            areaNewAddAchieveVOList = memberReportMapper.selectSmallAreaNewAddPage(addAchieveVO);
        }
        return areaNewAddAchieveVOList;
    }

    /**
     * 根据时间获取业绩表名
     *
     * @param localDate 时间
     * @return String
     */
    private String getMonthTableName(LocalDate localDate) {
        return TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }

    /**
     * 根据开始时间、结束时间获取业绩表信息
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return List<MonthAchieveVO>
     */
    private List<MonthAchieveVO> getAchieveMonthTable(String startDate, String endDate) {
        MonthAchieveVO monthAchieveVO;
        List<MonthAchieveVO> monthAchieveVOList = new ArrayList<>();
        LocalDate startLocalDate = DateUtils.getStringToLocalDate(startDate);
        LocalDate endLocalDate = DateUtils.getStringToLocalDate(endDate);
        Period between = Period.between(startLocalDate, endLocalDate);
        //相差的天数
        int months = between.getMonths();
        //相差两个月及以上
        if (months >= 2) {
            //初月信息
            int startPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDate).getPkId();
            MonthAchieveVO startMonthAchieveVO = MonthAchieveVO.builder().achieveTable(getMonthTableName(startLocalDate))
                    .startPeriod(startPeriod)
                    .build();
            monthAchieveVOList.add(startMonthAchieveVO);
            //中间月信息
            for (int i = 1; i < months; i++) {
                System.out.println(startLocalDate.plusMonths(i));
                monthAchieveVO = MonthAchieveVO.builder().achieveTable(getMonthTableName(startLocalDate.plusMonths(i))).build();
                monthAchieveVOList.add(monthAchieveVO);
            }
            //末月信息
            int endPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDate).getPkId();
            MonthAchieveVO endMonthAchieveVO = MonthAchieveVO.builder().achieveTable(getMonthTableName(endLocalDate))
                    .endPeriod(endPeriod)
                    .build();
            monthAchieveVOList.add(endMonthAchieveVO);
            //同一个月
        } else if (months == 0) {
            int startPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDate).getPkId();
            int endPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDate).getPkId();
            monthAchieveVO = MonthAchieveVO.builder().achieveTable(getMonthTableName(startLocalDate))
                    .startPeriod(startPeriod).endPeriod(endPeriod).build();
            monthAchieveVOList.add(monthAchieveVO);
        } else {
            //初月信息
            int startPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDate).getPkId();
            MonthAchieveVO startMonthAchieveVO = MonthAchieveVO.builder().achieveTable(getMonthTableName(startLocalDate))
                    .startPeriod(startPeriod)
                    .build();
            monthAchieveVOList.add(startMonthAchieveVO);
            //末月信息
            int endPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDate).getPkId();
            MonthAchieveVO endMonthAchieveVO = MonthAchieveVO.builder().achieveTable(getMonthTableName(endLocalDate))
                    .endPeriod(endPeriod)
                    .build();
            monthAchieveVOList.add(endMonthAchieveVO);
        }
        return monthAchieveVOList;
    }

    @Override
    public List<CuMemberWalletVO> selectMemberUnderWalletList(CuMemberWalletVO walletVO) {
        List<CuMemberWalletVO> cuMemberWalletVOList = memberReportMapper.selectMemberUnderWalletList(walletVO);
        if (CollUtil.isNotEmpty(cuMemberWalletVOList)) {
            Integer pkCountry = walletVO.getPkCountry();
            //查询币种值
            List<BdAccount> allAccounts = iAccountServiceApi.queryAccountByType(null, pkCountry).getData();
            Map<Integer, BdAccount> map = allAccounts.stream().collect(Collectors.toMap(BdAccount::getPkId, o -> o));
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(ETradeType.values());
            //根据国家查询汇率
            CurrencyDTO currency = iCurrencyServiceApi.getCurrency(pkCountry).getData();
            //汇率
            BigDecimal exchangeRate = currency.getInExchangeRate();
            for (CuMemberWalletVO cuMemberWalletVO : cuMemberWalletVOList) {
                //交易金额
                BigDecimal settleTradeAmount = cuMemberWalletVO.getTradeAmount().divide(exchangeRate, 4, RoundingMode.HALF_UP);
                //交易余额
                BigDecimal settleTradeBalance = cuMemberWalletVO.getTradeBalance().divide(exchangeRate, 4, RoundingMode.HALF_UP);
                cuMemberWalletVO.setSettleTradeAmount(settleTradeAmount);
                cuMemberWalletVO.setSettleTradeBalance(settleTradeBalance);

                //转化备注
                String remarks = cuMemberWalletVO.getRemarks();
                if (StringUtils.isNotEmpty(remarks) && remarks.startsWith(EnumsPrefixConstants.TRADE_TYPE)) {
                    cuMemberWalletVO.setRemarks(transactionMap.get(remarks));
                }

                Integer pkAccount = cuMemberWalletVO.getPkAccount();
                if (null != pkAccount) {
                    cuMemberWalletVO.setPkAccount(map.get(pkAccount).getPkTransactionKey());
                }
            }
        }
        return cuMemberWalletVOList;
    }

    @Override
    public List<ProductSaleStatVo> productSaleStatList(String skuCode, String productName, Integer orderType, Date startTime, Date endTime, Integer pkCountry) {
        return memberReportMapper.productSaleStatList(skuCode, productName, orderType, startTime, endTime, pkCountry);
    }

    @Override
    public Integer sumQuantity(String productName, Integer pkClassify, Date startTime, Date endTime, Integer pkCountry, List<Integer> orderTypeList) {
        return memberReportMapper.sumQuantity(productName, pkClassify, startTime, endTime, pkCountry, orderTypeList);
    }

    @Override
    public Integer selectExistTable(String tableName) {
        return memberReportMapper.selectExistTable(tableName);
    }

    @Override
    public DirectPushNewVo sizeZoneAchie(DirectPushNewVo dpo, Long pkMember, BigDecimal rate) {
        //查询直推会员
        List<Long> pkMemberList = memberReportMapper.selectDirectPushByPkMember(pkMember);
        //查询自己业绩
        List<DirectPushNewVo> memberSelfAchieveList = new ArrayList<>();
        //会员业绩（需求修改，注册、升级上传业绩、复购、复消算自己的业绩）
        DirectPushNewVo memberAchieveVO = DirectPushNewVo.builder().achieveTableNameEnd(dpo.getAchieveTableNameEnd()).pkMember(pkMember).build();
        memberAchieveVO.setEndPayTime(dpo.getEndPayTime());
        memberAchieveVO.setZonpayTime(dpo.getZonpayTime());
        DirectPushNewVo orderAchieveVO = memberReportMapper.selectMemberOrderAchieveByPkMember(memberAchieveVO);
        if (null != orderAchieveVO && orderAchieveVO.getArealPv().compareTo(BigDecimal.ZERO) > 0) {
            orderAchieveVO.setPkMember(pkMember);
            memberSelfAchieveList.add(orderAchieveVO);
        }
        //查询伞下业绩
        if (CollUtil.isNotEmpty(pkMemberList)) {
            List<DirectPushNewVo> memberPushAchieveList = getMemberPushAchieve(pkMemberList, dpo.getAchieveTableNameEnd(), dpo.getEndPayTime(), dpo.getZonpayTime());
            if (CollUtil.isNotEmpty(memberPushAchieveList)) {
                memberSelfAchieveList.addAll(memberPushAchieveList);
            }
        }
        if (CollUtil.isEmpty(memberSelfAchieveList)) {
            return DirectPushNewVo.builder().smallAreaPv(BigDecimal.ZERO).bigArealPv(BigDecimal.ZERO).build();
        }
        return getMemberBigAndSmallAchieve(memberSelfAchieveList, rate);
    }

    @Override
    public DirectPushNewVo sizeZoneAchieAmount(DirectPushNewVo dpo, Long pkMember, BigDecimal rate) {
        //会员业绩（需求修改，注册、升级上传业绩、复购、复消算自己的业绩）
        dpo.setPkMember(pkMember);
        //查询伞下业绩金额
        List<DirectPushNewVo> memberPushAchieveList = querMemberAchieveAmountTeam(dpo);
        if (CollUtil.isEmpty(memberPushAchieveList)) {
            return DirectPushNewVo
                    .builder()
                    .smallAreaPv(BigDecimal.ZERO)
                    .bigArealPv(BigDecimal.ZERO)
                    .bigArealAm(BigDecimal.ZERO)
                    .smallAreaAm(BigDecimal.ZERO)
                    .build();
        }
        return getMemberBigAndSmallAchieve(memberPushAchieveList, rate);
    }

    /**
     * 查询会员推荐伞下业绩
     **/
    private List<DirectPushNewVo> getMemberPushAchieve(List<Long> pkMemberList, String memberRangeTable, Date endPayTime, Date zonpayTime) {
        DirectPushNewVo memberAchieveVO = DirectPushNewVo.builder()
                .achieveTableNameEnd(memberRangeTable)
                .pkMemberList(pkMemberList)
                .endPayTime(endPayTime)
                .zonpayTime(zonpayTime)
                .build();
        return memberReportMapper.selectMemberAchieve(memberAchieveVO);
    }

    /**
     * 查询伞下业绩金额
     **/
    private List<DirectPushNewVo> querMemberAchieveAmountTeam(DirectPushNewVo dpo) {
        return memberReportMapper.querMemberAchieveAmountTeam(dpo);
    }

    /**
     * 获取直推大区业绩、小区业绩
     **/
    private DirectPushNewVo getMemberBigAndSmallAchieve(List<DirectPushNewVo> memberAchieveList, BigDecimal rate) {
        //查询最大业绩
        DirectPushNewVo maxAchieveVO = memberAchieveList.stream().max(Comparator.comparing(DirectPushNewVo::getArealPv)).get();
        //查询小区业绩
        BigDecimal smallAreaPv = memberAchieveList.stream().filter(achieveVO -> !achieveVO.getPkMember().equals(maxAchieveVO.getPkMember())).map(vo -> null == vo.getArealPv() ? BigDecimal.ZERO : vo.getArealPv()).reduce(BigDecimal.ZERO, BigDecimal::add);
        //查询最大金额
        DirectPushNewVo maxAmountVO = memberAchieveList.stream().max(Comparator.comparing(DirectPushNewVo::getArealAm)).get();
        //查询小区金额
        BigDecimal smallAmount = memberAchieveList.stream().filter(achieveVO -> !achieveVO.getPkMember().equals(maxAchieveVO.getPkMember())).map(vo -> null == vo.getArealAm() ? BigDecimal.ZERO : vo.getArealAm()).reduce(BigDecimal.ZERO, BigDecimal::add);
        return DirectPushNewVo.builder()
                .smallAreaPv(smallAreaPv.multiply(rate))
                .bigArealPv(maxAchieveVO.getArealPv().multiply(rate))
                .smallAreaAm(smallAmount)
                .bigArealAm(maxAmountVO.getArealAm())
                .build();
    }

    /**
     * 根据大业绩查询大小区盒数
     **/
    private DirectPushBoxVo getMemberBigAndSmallBox(List<DirectPushBoxVo> memberAchieveList) {
        // 2. 找到 ArealPv 最大的对象
        DirectPushBoxVo maxAchieveVO = memberAchieveList.stream()
                .max(Comparator.comparing(DirectPushBoxVo::getArealPv))
                .orElseThrow(() -> new IllegalStateException("逻辑错误：列表非空但未找到最大值"));

        // 3. 排除最大对象后，累加其他对象的 smallAreaBox
        int totalSmallAreaBox = memberAchieveList.stream()
                .filter(vo -> !vo.getPkMember().equals(maxAchieveVO.getPkMember())) // 排除最大 ArealPv 的对象
                .mapToInt(DirectPushBoxVo::getArealBox)
                .sum();

        // 4. 返回结果：最大 bigAreaBox 和累加后的 smallAreaBox
        return DirectPushBoxVo.builder()
                .bigAreaBox(maxAchieveVO.getArealBox())  // 最大 ArealPv 对应的 bigAreaBox
                .smallAreaBox(totalSmallAreaBox)          // 其他对象的 smallAreaBox 累加值
                .build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushAmountBoxmethod() {
        //查询当前日期
        String date = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, (DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date())));
        int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date).getPkId();
        String rangeTabeName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
        if (selectExistTable(rangeTabeName) == 0) {
            return;
        }
        //查询上一期的统计金额业绩盒数表
        String beforeDate = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date);
        int beforePeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(beforeDate).getPkId();
        String beforeTabeName = TableNameConstants.CU_MEMBER_AMOUNT_BOX + beforePeriod;
        String tabeName = TableNameConstants.CU_MEMBER_AMOUNT_BOX + period;

        //表不存在则创建表
        if (selectExistTable(beforeTabeName) == 0) {
            memberReportMapper.createCuMemberAmountBoxTable(beforeTabeName);
        }
        //表不存在则创建表
        if (selectExistTable(tabeName) == 0) {
            memberReportMapper.createCuMemberAmountBoxTable(tabeName);
        }
        //创建表索引
        String indexName = TableNameConstants.CU_MEMBER_AMOUNT_BOX_INDEX + period;
        try {
            memberReportMapper.createPkMemberIndex(indexName, tabeName);
            log.info("索引创建成功！");
        } catch (Exception e) {
            log.info("索引创建失败: " + e.getMessage());
        }
        //添加会员统计金额业绩盒数数据
        memberReportMapper.innertMemberAmountBoxTable(date, date, tabeName, beforeTabeName, rangeTabeName);
        List<DirectPushAmountPvBoxVo> orderList = memberReportMapper.querMemberOrder(date, date);
        if (CollectionUtil.isNotEmpty(orderList)) {
            orderList.forEach(itm -> {
                //添加会员伞下业绩金额盒数数据
                memberReportMapper.innertTeamAmountBoxTable(itm, date, date, tabeName, beforeTabeName, rangeTabeName);
            });
        }
        //将未激活的会员盒数更新为0
        memberReportMapper.updMemberBox(tabeName, rangeTabeName);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void repeatPushAmountBoxmethod(String startDateStr, String endDateStr) {
        log.info("手动直推统计开始：{}", startDateStr + " ==== " + endDateStr);
        List<String> dateList = getDateRange(startDateStr, endDateStr);
        if (CollectionUtil.isNotEmpty(dateList)) {
            dateList.forEach(date -> {
                //查询当前日期
                int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date).getPkId();
                String rangeTabeName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
                if (selectExistTable(rangeTabeName) == 0) {
                    return;
                }
                //查询上一期的统计金额业绩盒数表
                String beforeDate = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date);
                int beforePeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(beforeDate).getPkId();
                String beforeTabeName = TableNameConstants.CU_MEMBER_AMOUNT_BOX + beforePeriod;
                String tabeName = TableNameConstants.CU_MEMBER_AMOUNT_BOX + period;

                //表不存在则创建表
                if (selectExistTable(beforeTabeName) == 0) {
                    memberReportMapper.createCuMemberAmountBoxTable(beforeTabeName);
                }
                //表不存在则创建表
                if (selectExistTable(tabeName) == 0) {
                    memberReportMapper.createCuMemberAmountBoxTable(tabeName);
                }

                //删除表数据重新统计
                memberReportMapper.delMemberAmountBox(tabeName);
                //创建表索引
                String indexName = TableNameConstants.CU_MEMBER_AMOUNT_BOX_INDEX + period;
                try {
                    memberReportMapper.createPkMemberIndex(indexName, tabeName);
                    log.info("索引创建成功！");
                } catch (Exception e) {
                    log.info("索引创建失败: " + e.getMessage());
                }
                log.info("开始批量添加数据：{}" + "date= " + date + "tabeName= " + tabeName + "beforeTabeName= "
                        + beforeTabeName + "rangeTabeName= " + rangeTabeName);
                //添加会员统计金额业绩盒数数据
                memberReportMapper.innertMemberAmountBoxTable(date, date, tabeName, beforeTabeName, rangeTabeName);
                List<DirectPushAmountPvBoxVo> orderList = memberReportMapper.querMemberOrder(date, date);
                if (CollectionUtil.isNotEmpty(orderList)) {
                    orderList.forEach(itm -> {
                        //添加会员伞下业绩金额盒数数据
                        memberReportMapper.innertTeamAmountBoxTable(itm, date, date, tabeName, beforeTabeName, rangeTabeName);
                    });
                }
                //将未激活的会员盒数更新为0
                memberReportMapper.updMemberBox(tabeName, rangeTabeName);
                log.info("统计完成");
            });
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void washMemberAmountBox(String startDateStr, String endDateStr) {
        List<String> dateList = getDateRange(startDateStr, endDateStr);
        if (CollectionUtil.isNotEmpty(dateList)) {
            dateList.forEach(date -> {
                //查询当前日期
                int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date).getPkId();
                String rangeTabeName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
                if (selectExistTable(rangeTabeName) == 0) {
                    return;
                }
                String tabeName = TableNameConstants.CU_MEMBER_AMOUNT_BOX + period;
                //表不存在则创建表
                if (selectExistTable(tabeName) == 0) {
                    memberReportMapper.createCuMemberAmountBoxTable(tabeName);
                }
                //创建表索引
                String indexName = TableNameConstants.CU_MEMBER_AMOUNT_BOX_INDEX + period;
                try {
                    memberReportMapper.createPkMemberIndex(indexName, tabeName);
                    log.info("索引创建成功！");
                } catch (Exception e) {
                    log.info("索引创建失败: " + e.getMessage());
                }
                //添加会员统计金额业绩盒数数据
                memberReportMapper.washMemberAmountBox(tabeName, rangeTabeName);
            });
        }
    }


    public List<String> getDateRange(String startDateStr, String endDateStr) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串转换为 LocalDate
        LocalDate startDate = LocalDate.parse(startDateStr, formatter);
        LocalDate endDate = LocalDate.parse(endDateStr, formatter);
        // 存储日期的列表
        List<String> dateList = new ArrayList<>();
        // 循环生成日期
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            dateList.add(currentDate.format(formatter));
            currentDate = currentDate.plusDays(1); // 增加一天
        }
        return dateList;
    }

    @Override
    public DirectPushBoxVo sizeZoneBox(DirectPushBoxVo dpbVo, String memberCode, Long pkMember) {
        dpbVo.setPkMember(pkMember);
        DirectPushNewVo dpo = BeanUtil.copyProperties(dpbVo, DirectPushNewVo.class);
        //查询伞下业绩金额盒数
        List<DirectPushNewVo> memberPushAchieveList = querMemberAchieveAmountTeam(dpo);
        if (CollUtil.isNotEmpty(memberPushAchieveList)) {
            List<DirectPushBoxVo> boxList = new ArrayList<>();
            memberPushAchieveList.forEach(item -> boxList.add(BeanUtil.copyProperties(item, DirectPushBoxVo.class)));
            return getMemberBigAndSmallBox(boxList);
        } else {
            return dpbVo;
        }
    }

    @Override
    public List<DirectPushBoxVo> selectMemberActiveState(DirectPushBoxVo dpbVo, List<Long> pkMemberList) {
        return memberReportMapper.selectMemberActiveState(dpbVo, pkMemberList);
    }

    @Override
    public List<DirectPushNewVo> querDirectPushDetails(DirectPushNewVo directPushNewVo) {
        return memberReportMapper.querDirectPushDetails(directPushNewVo);
    }

    @Override
    public void createCuMemberAmountBoxTable(String tabeName) {
        memberReportMapper.createCuMemberAmountBoxTable(tabeName);
    }


}
