package com.hzs.report.member.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.TableNameConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.store.CuParentStore;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.member.achieve.ICuMemberSettlePeriodServiceApi;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.member.store.ICuParentStoreServiceApi;
import com.hzs.report.member.service.ICuMemberAwardsStatService;
import com.hzs.report.member.service.MemberReportService;
import com.hzs.report.member.vo.*;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 会员奖衔升级记录表 前端控制器
 * </p>
 *
 * @author zhangjing
 * @since 2022-10-20
 */
@RestController
@RequestMapping("/manager/member-awards")
public class CuMemberAwardsStatController extends BaseController {

    @Autowired
    private ICuMemberAwardsStatService iCuMemberAwardsStatService;
    @DubboReference
    private ICuMemberSettlePeriodServiceApi cuMemberSettlePeriodService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @DubboReference
    private IMemberServiceApi iMemberServiceApi;
    @DubboReference
    private ICurrencyServiceApi currencyServiceApi;
    @Autowired
    private MemberReportService memberReportService;
    @DubboReference
    private ICountryServiceApi iCountryServiceApi;
    @DubboReference
    private ICuParentStoreServiceApi cuParentStoreServiceApi;
    @DubboReference
    private IAwardsServiceApi iAwardsServiceApi;
    @DubboReference
    private IGradeServiceApi iGradeServiceApi;

    /**
     * @description: 真实业绩新增奖衔查询列表
     * @author: zhang jing
     * @date: 2022/10/20 10:36
     * @param: [memberAuthorityParam]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REAL_PERFORMANCE_ADDED_AWARDS, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(CuMemberAwardsStatVO cuMemberAwardsStatVO) {
        Date date = DateUtils.currentDate();
        //当前日期前一天
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        //查询最新期数
        int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(dateStr)).getData().getPkId();
        cuMemberAwardsStatVO.setPeriod(endperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_SETTLE_D + endperiod;
        cuMemberAwardsStatVO.setAchieveTableName(achieveTableName);
        cuMemberAwardsStatVO.setPkCountry(SecurityUtils.getPkCountry());
        startPage();
        List<CuMemberAwardsStatVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsList(cuMemberAwardsStatVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                final BigDecimal[] totalSumPv = {BigDecimal.ZERO};
                List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(achieveTableName, itm.getPkMember());
                if (CollectionUtil.isNotEmpty(plmbList)) {
                    plmbList.forEach(itmm -> {
                        totalSumPv[0] = totalSumPv[0].add(itmm.getSumPv());
                    });
                }
                itm.setPlmbList(plmbList);
            });
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出 真实业绩新增奖衔查询列表
     * @author: zhang jing
     * @date: 2023/8/25 17:30
     * @param: [response, cuMemberAwardsStatVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REAL_PERFORMANCE_ADDED_AWARDS, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void exportUmbrella(HttpServletResponse response, CuMemberAwardsStatVO cuMemberAwardsStatVO) {
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(
                EnumsPrefixConstants.KEY_AWARD);
        Date date = DateUtils.currentDate();
        //当前日期前一天
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        //查询最新期数
        int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(dateStr)).getData().getPkId();
        cuMemberAwardsStatVO.setPeriod(endperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_SETTLE_D + endperiod;
        cuMemberAwardsStatVO.setAchieveTableName(achieveTableName);
        List<CuMemberAwardsStatVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsList(cuMemberAwardsStatVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
                final BigDecimal[] totalSumPv = {BigDecimal.ZERO};
                List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(achieveTableName, itm.getPkMember());
                StringBuffer str = new StringBuffer();
                if (CollectionUtil.isNotEmpty(plmbList)) {
                    plmbList.forEach(itmm -> {
                        totalSumPv[0] = totalSumPv[0].add(itmm.getSumPv());
                        str.append("第" + itmm.getPlaceDept() + "部门: 业绩:" + itmm.getSumPv());
                    });
                }
                itm.setTotalNewPv(str.toString());
                itm.setPlmbList(plmbList);
            });
        }

        ExcelUtil<CuMemberAwardsStatVO> util = new ExcelUtil<>(CuMemberAwardsStatVO.class);
        util.exportExcel(response, list, "真实业绩新增奖衔");
    }

    /**
     * @description: 真实奖衔分析
     * @author: zhang jing
     * @date: 2023/8/26 15:57
     * @param: [cuMemberAwardsStatVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.AWARD_ANALYSIS, method = EOperationMethod.SELECT)
    @GetMapping("/analysis-list")
    public TableDataInfo analysisList(CuMemberAwardsAnalysisVO cuMemberAwardsAnalysisVO) {
        cuMemberAwardsAnalysisVO.setPkCountry(SecurityUtils.getPkCountry());
        if(cuMemberAwardsAnalysisVO.getPkGrade()!=null){
            GradeDTO bgo = iGradeServiceApi.getGradeByGradeValue(cuMemberAwardsAnalysisVO.getPkGrade(),CountryConstants.CHINA_COUNTRY).getData();
            cuMemberAwardsAnalysisVO.setPkGrade(bgo.getGradeValue());
        }
        startPage();
        List<CuMemberAwardsAnalysisVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsAnalysisList(cuMemberAwardsAnalysisVO);
        for (CuMemberAwardsAnalysisVO pe : list) {
            //根据晋升日期查询晋升日期的部门业绩
            String dates =DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,pe.getCreationTime());
            //查询最新期数
            int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                    DateUtils.parseDateToStr(dates)).getData().getPkId();
            //校验表是否存在
            Integer staSettleTabl = iCuMemberAwardsStatService.queryExistOracleTable(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod);
            if(staSettleTabl != null && staSettleTabl > 0){
                pe.setAchieveTableName(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod);
            }
        }
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                if(itm.getAchieveTableName()!=null){
                    List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(itm.getAchieveTableName(), itm.getPkMember());
                    if (CollectionUtil.isNotEmpty(plmbList)) {
                        BigDecimal totalSumPv = plmbList.stream()
                                .map(PlaceDeptMemberVO::getSumPv)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        itm.setPlmbList(plmbList);
                        itm.setTotalSumPv(totalSumPv);
                    }
                }


            });
        }
        return getDataTable(list);
    }

    public TableDataInfo analysisListNew(CuMemberAwardsAnalysisVO cuMemberAwardsAnalysisVO) {
        cuMemberAwardsAnalysisVO.setPkCountry(SecurityUtils.getPkCountry());
        if (cuMemberAwardsAnalysisVO.getPkGrade() != null) {
            GradeDTO gradeDTO = iGradeServiceApi.getGradeByGradeValue(cuMemberAwardsAnalysisVO.getPkGrade(), CountryConstants.CHINA_COUNTRY).getData();
            cuMemberAwardsAnalysisVO.setPkGrade(gradeDTO.getGradeValue());
        }
        startPage();
        List<CuMemberAwardsAnalysisVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsAnalysisList(cuMemberAwardsAnalysisVO);

        Map<String, Integer> periodCache = new HashMap<>(); // 用于缓存日期到期数的映射
        Map<String, Boolean> tableExistenceCache = new HashMap<>(); // 用于缓存表名是否存在的映射

        list.forEach(pe -> {
            String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, pe.getCreationTime());
            int endperiod = periodCache.computeIfAbsent(dateStr, key -> {
                // 假设这里不会抛出异常，或者应该添加异常处理
                return cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(key).getData().getPkId();
            });

            boolean tableExists = tableExistenceCache.computeIfAbsent(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod, key -> {
                // 同样，这里应该添加异常处理
                return iCuMemberAwardsStatService.queryExistOracleTable(key) != null && iCuMemberAwardsStatService.queryExistOracleTable(key) > 0;
            });

            if (tableExists) {
                pe.setAchieveTableName(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod);
            }
        });

        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, List<PlaceDeptMemberVO>> plmbListCache = new HashMap<>(); // 用于缓存表名和成员的PLMB列表映射
            list.parallelStream().forEach(itm -> {
                if (itm.getAchieveTableName() != null) {
                    String cacheKey = itm.getAchieveTableName() + "_" + itm.getPkMember();
                    List<PlaceDeptMemberVO> plmbList = plmbListCache.computeIfAbsent(cacheKey, key -> {
                        // 这里应该添加异常处理
                        return iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(key.split("_")[0], Long.parseLong(key.split("_")[1]));
                    });
                    BigDecimal totalSumPv = plmbList.stream()
                            .map(PlaceDeptMemberVO::getSumPv)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    itm.setPlmbList(plmbList);
                    itm.setTotalSumPv(totalSumPv);
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * @description: 中国查询真实奖衔分析
     * @author: zhang jing
     * @date: 2024/9/2 16:44
     * @param: [cuMemberAwardsAnalysisVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.AWARD_ANALYSIS, method = EOperationMethod.SELECT)
    @GetMapping("/analysis-list-cn")
    public TableDataInfo analysisListCn(CuMemberAwardsAnalysisVO cuMemberAwardsAnalysisVO) {
        cuMemberAwardsAnalysisVO.setPkCountry(SecurityUtils.getPkCountry());
        if(cuMemberAwardsAnalysisVO.getPkCountry()== CountryConstants.CHINA_COUNTRY){
            cuMemberAwardsAnalysisVO.setPkCountry(null);
        }
        startPage();
        List<CuMemberAwardsAnalysisVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsAnalysisListCn(cuMemberAwardsAnalysisVO);
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberAwardsAnalysisVO pe : list) {
                //根据晋升日期查询晋升日期的部门业绩
                String dates =DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,pe.getCreationTime());
                //查询最新期数
                int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                        DateUtils.parseDateToStr(dates)).getData().getPkId();
                pe.setAchieveTableName(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod);
            }
            list.forEach(itm -> {
                final BigDecimal[] totalSumPv = {BigDecimal.ZERO};
                List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(itm.getAchieveTableName(), itm.getPkMember());
                if (CollectionUtil.isNotEmpty(plmbList)) {
                    plmbList.forEach(itmm -> {
                        totalSumPv[0] = totalSumPv[0].add(itmm.getSumPv());
                    });
                }
                itm.setTotalSumPv(totalSumPv[0]);
                itm.setPlmbList(plmbList);
            });
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出真实奖衔分析
     * @author: zhang jing
     * @date: 2023/8/26 16:41
     * @param: [response, cuMemberAwardsAnalysisVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.AWARD_ANALYSIS, method = EOperationMethod.EXPORT)
    @PostMapping("/export-analysis-cn")
    public void exportAnalysisCn(HttpServletResponse response, CuMemberAwardsAnalysisVO cuMemberAwardsAnalysisVO) {
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        cuMemberAwardsAnalysisVO.setPkCountry(SecurityUtils.getPkCountry());
        if(cuMemberAwardsAnalysisVO.getPkCountry()== CountryConstants.CHINA_COUNTRY){
            cuMemberAwardsAnalysisVO.setPkCountry(null);
        }
        List<CuMemberAwardsAnalysisVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsAnalysisListCn(cuMemberAwardsAnalysisVO);
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberAwardsAnalysisVO pe : list) {
                //根据晋升日期查询晋升日期的部门业绩
                String dates =DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,pe.getCreationTime());
                //查询最新期数
                int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                        DateUtils.parseDateToStr(dates)).getData().getPkId();
                pe.setAchieveTableName(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod);
            }
            list.forEach(itm -> {
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
                itm.setPkRegisterGradeVal(transactionMap1.get(itm.getPkRegisterGrade()));
                final BigDecimal[] totalSumPv = {BigDecimal.ZERO};
                List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(itm.getAchieveTableName(), itm.getPkMember());
                StringBuffer str = new StringBuffer();
                if (CollectionUtil.isNotEmpty(plmbList)) {
                    plmbList.forEach(itmm -> {
                        totalSumPv[0] = totalSumPv[0].add(itmm.getSumPv());
                        str.append("第" + itmm.getPlaceDept() + "部门: 业绩:" + itmm.getSumPv());
                    });
                }
                itm.setDeptAchie(str.toString());
                itm.setTotalSumPv(totalSumPv[0]);
                itm.setPlmbList(plmbList);
            });
        }
        ExcelUtil<CuMemberAwardsAnalysisVO> util = new ExcelUtil<>(CuMemberAwardsAnalysisVO.class);
        util.exportExcel(response, list, "真实奖衔分析");
    }

    /**
     * @description: 真实奖衔分析-详情（穿透页面接口）
     * @author: zhang jing
     * @date: 2023/9/26 11:52
     * @param: [cuMemberAwardsAnalysisVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.ANALYSIS_DETAILS, method = EOperationMethod.SELECT)
    @GetMapping("/analysis-details-list")
    public TableDataInfo analysisDetailsList(CuMemberAwardsAnalysisVO cuMemberAwardsAnalysisVO) {
        Date date = DateUtils.currentDate();
        //当前日期前一天
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        //查询最新期数
        int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(dateStr)).getData().getPkId();
        cuMemberAwardsAnalysisVO.setPeriod(endperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_SETTLE_D + endperiod;
        cuMemberAwardsAnalysisVO.setAchieveTableName(achieveTableName);
        startPage();
        List<CuMemberAwardsAnalysisVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsAnalysisDetailsList(cuMemberAwardsAnalysisVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                final BigDecimal[] totalSumPv = {BigDecimal.ZERO};
                List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(achieveTableName, itm.getPkMember());
                if (CollectionUtil.isNotEmpty(plmbList)) {
                    plmbList.forEach(itmm -> {
                        totalSumPv[0] = totalSumPv[0].add(itmm.getSumPv());
                    });
                }
                itm.setTotalSumPv(totalSumPv[0]);
                itm.setPlmbList(plmbList);
            });
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出真实奖衔分析-详情（穿透页面接口）
     * @author: zhang jing
     * @date: 2023/9/27 14:43
     * @param: [response, cuMemberAwardsAnalysisVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.AWARD_ANALYSIS, method = EOperationMethod.EXPORT)
    @PostMapping("/export-analysis-details")
    public void exportAnalysisDetails(HttpServletResponse response, CuMemberAwardsAnalysisVO cuMemberAwardsAnalysisVO) {
        Date date = DateUtils.currentDate();
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        //当前日期前一天
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        //查询最新期数
        int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(dateStr)).getData().getPkId();
        cuMemberAwardsAnalysisVO.setPeriod(endperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_SETTLE_D + endperiod;
        cuMemberAwardsAnalysisVO.setAchieveTableName(achieveTableName);
        startPage();
        List<CuMemberAwardsAnalysisVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsAnalysisDetailsList(cuMemberAwardsAnalysisVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
                itm.setPkRegisterGradeVal(transactionMap1.get(itm.getPkRegisterGrade()));
                final BigDecimal[] totalSumPv = {BigDecimal.ZERO};
                List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(achieveTableName, itm.getPkMember());
                if (CollectionUtil.isNotEmpty(plmbList)) {
                    plmbList.forEach(itmm -> {
                        totalSumPv[0] = totalSumPv[0].add(itmm.getSumPv());
                    });
                }
                itm.setTotalSumPv(totalSumPv[0]);
                itm.setPlmbList(plmbList);
            });
        }
        ExcelUtil<CuMemberAwardsAnalysisVO> util = new ExcelUtil<>(CuMemberAwardsAnalysisVO.class);
        util.exportExcel(response, list, "真实奖衔分析");
    }

    /**
     * @description: 收入明细
     * @author: zhang jing
     * @date: 2023/9/26 9:39
     * @param: [cuMemberAwardsAnalysisVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REVENUE_DETAI_LIST, method = EOperationMethod.SELECT)
    @GetMapping("/revenue-detai-list")
    public TableDataInfo revenueDetailsList(RevenueDetailsVO revenueDetailsVO) {
        if(SecurityUtils.getPkCountry()==CountryConstants.CHINA_COUNTRY){
            revenueDetailsVO.setPkCountry(null);
        }else{
            revenueDetailsVO.setPkCountry(SecurityUtils.getPkCountry());
        }
        Date date = DateUtils.currentDate();
        //查询当前国家的汇率
        if (StringUtils.isNull(revenueDetailsVO.getStartDate()) ||
                StringUtils.isNull(revenueDetailsVO.getEndDate())) {
            if (DateUtils.compareDateBefore(date, DateUtils.currentMonthFirstDate()) ||
                    DateUtils.compareDateEqual(date, DateUtils.currentMonthFirstDate())) {
                //之前月的第一天
                revenueDetailsVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthFirstDate()));
                revenueDetailsVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthLastDate()));
            } else {
                //当前月第一天
                revenueDetailsVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
                revenueDetailsVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
            }
        }
        startPage();
        List<RevenueDetailsVO> list = iCuMemberAwardsStatService.selectRevenueDetailsList(revenueDetailsVO);
        return getDataTable(list);
    }

    /**
     * @description: 导出收入明细
     * @author: zhang jing
     * @date: 2023/8/26 16:41
     * @param: [response, cuMemberAwardsAnalysisVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REVENUE_DETAI_LIST, method = EOperationMethod.EXPORT)
    @PostMapping("/export-revenue-detai")
    public void exportRevenueDetai(HttpServletResponse response, RevenueDetailsVO revenueDetailsVO) {
        if(SecurityUtils.getPkCountry()==CountryConstants.CHINA_COUNTRY){
            revenueDetailsVO.setPkCountry(null);
        }else{
            revenueDetailsVO.setPkCountry(SecurityUtils.getPkCountry());
        }
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        List<RevenueDetailsVO> list = iCuMemberAwardsStatService.selectRevenueDetailsList(revenueDetailsVO);
        if(CollectionUtil.isNotEmpty(list)){
            list.forEach(itm->{
                itm.setPkRegisterGradeVal(transactionMap1.get(itm.getPkRegisterGrade()));
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
            });
        }
        ExcelUtil<RevenueDetailsVO> util = new ExcelUtil<>(RevenueDetailsVO.class);
        util.exportExcel(response, list, "收入明细");
    }

    /**
     * @description: 导出真实奖衔分析
     * @author: zhang jing
     * @date: 2023/8/26 16:41
     * @param: [response, cuMemberAwardsAnalysisVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.AWARD_ANALYSIS, method = EOperationMethod.EXPORT)
    @PostMapping("/export-analysis")
    public void exportAnalysis(HttpServletResponse response, CuMemberAwardsAnalysisVO cuMemberAwardsAnalysisVO) {
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        cuMemberAwardsAnalysisVO.setPkCountry(SecurityUtils.getPkCountry());
        List<CuMemberAwardsAnalysisVO> list = iCuMemberAwardsStatService.selectCuMemberAwardsAnalysisList(cuMemberAwardsAnalysisVO);
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberAwardsAnalysisVO pe : list) {
                //根据晋升日期查询晋升日期的部门业绩
                String dates =DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,pe.getCreationTime());
                //查询最新期数
                int endperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                        DateUtils.parseDateToStr(dates)).getData().getPkId();
                //校验表是否存在
                Integer staSettleTabl = iCuMemberAwardsStatService.queryExistOracleTable(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod);
                if(staSettleTabl != null && staSettleTabl > 0){
                    pe.setAchieveTableName(TableNameConstants.CU_MEMBER_SETTLE_D + endperiod);
                }
            }
            list.forEach(itm -> {
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
                itm.setPkRegisterGradeVal(transactionMap1.get(itm.getPkRegisterGrade()));
                        if(itm.getAchieveTableName()!=null){
                            List<PlaceDeptMemberVO> plmbList = iCuMemberAwardsStatService.selectPlaceDeptMemberAnalysisList(itm.getAchieveTableName(), itm.getPkMember());
                            StringBuffer str = new StringBuffer();
                            if (CollectionUtil.isNotEmpty(plmbList)) {
                                plmbList.forEach(itmm -> {
                                    str.append("第" + itmm.getPlaceDept() + "部门: 业绩:" + itmm.getSumPv());
                                });
                            }
                            itm.setDeptAchie(str.toString());
                            BigDecimal totalSumPv = plmbList.stream()
                                    .map(PlaceDeptMemberVO::getSumPv)
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            itm.setTotalSumPv(totalSumPv);
                            itm.setPlmbList(plmbList);
                        }

            });
        }
        ExcelUtil<CuMemberAwardsAnalysisVO> util = new ExcelUtil<>(CuMemberAwardsAnalysisVO.class);
        util.exportExcel(response, list, "真实奖衔分析");
    }


    /**
     * @description: 复购pv统计
     * @author: zhang jing
     * @date: 2023/8/29 15:33
     * @param: [repurchasePVStatVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REPURCHASE_PV_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/repurchasepv-list")
    public TableDataInfo repurchasePVStat(RepurchasePVStatVO repurchasePVStatVO) {
        Date date = DateUtils.currentDate();
        //查询当前国家的汇率
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        repurchasePVStatVO.setPkCountry(SecurityUtils.getPkCountry());
        if (StringUtils.isNull(repurchasePVStatVO.getStartDate()) ||
                StringUtils.isNull(repurchasePVStatVO.getEndDate())) {
            if (DateUtils.compareDateBefore(date, DateUtils.currentMonthFirstDate()) ||
                    DateUtils.compareDateEqual(date, DateUtils.currentMonthFirstDate())) {
                //之前月的第一天
                repurchasePVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthFirstDate()));
                repurchasePVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthLastDate()));
            } else {
                //当前月第一天
                repurchasePVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
                repurchasePVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
            }
        }

        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(repurchasePVStatVO.getStartDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(repurchasePVStatVO.getStartDate()))) {
            //当前月第一天
            repurchasePVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(repurchasePVStatVO.getEndDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(repurchasePVStatVO.getEndDate()))) {
            //当前日期的前一天
            repurchasePVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        //查询最新期数
        int staperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(repurchasePVStatVO.getStartDate())).getData().getPkId();
        repurchasePVStatVO.setPeriod(staperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(repurchasePVStatVO.getStartDate());
        repurchasePVStatVO.setAchieveTableName(achieveTableName);
        Date currentDate = DateUtils.afterDate(1, ChronoUnit.DAYS, DateUtils.parseStringToDate(repurchasePVStatVO.getStartDate()));
        // 考核表
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.currentYear(currentDate);
        repurchasePVStatVO.setAssessTableName(tableName);
        startPage();
        List<RepurchasePVStatVO> list = iCuMemberAwardsStatService.selectRepurchasePVStatList(repurchasePVStatVO);
        return getDataTable(list);
    }


    /**
     * @description: 导出复购pv统计
     * @author: zhang jing
     * @date: 2023/8/30 10:14
     * @param: [response, repurchasePVStatVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REPURCHASE_PV_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/export-repurchasepv")
    public void exportRepurchasePVStat(HttpServletResponse response, RepurchasePVStatVO repurchasePVStatVO) {
        Date date = DateUtils.currentDate();
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EAssessStatus.values(), EDealerYesNo.values());
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(
                EnumsPrefixConstants.KEY_AWARD);
        //查询当前国家的汇率
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        repurchasePVStatVO.setPkCountry(SecurityUtils.getPkCountry());
        if (StringUtils.isNull(repurchasePVStatVO.getStartDate()) ||
                StringUtils.isNull(repurchasePVStatVO.getEndDate())) {
            if (DateUtils.compareDateBefore(date, DateUtils.currentMonthFirstDate()) ||
                    DateUtils.compareDateEqual(date, DateUtils.currentMonthFirstDate())) {
                //之前月的第一天
                repurchasePVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthFirstDate()));
                repurchasePVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthLastDate()));
            } else {
                //当前月第一天
                repurchasePVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
                repurchasePVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
            }
        }

        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(repurchasePVStatVO.getStartDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(repurchasePVStatVO.getStartDate()))) {
            //当前月第一天
            repurchasePVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(repurchasePVStatVO.getEndDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(repurchasePVStatVO.getEndDate()))) {
            //当前日期的前一天
            repurchasePVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        List<RepurchasePVStatVO> list = new ArrayList<>();
        //查询最新期数
        int staperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(repurchasePVStatVO.getStartDate())).getData().getPkId();
        repurchasePVStatVO.setPeriod(staperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(repurchasePVStatVO.getStartDate());
        repurchasePVStatVO.setAchieveTableName(achieveTableName);
        Date currentDate = DateUtils.afterDate(1, ChronoUnit.DAYS, DateUtils.parseStringToDate(repurchasePVStatVO.getStartDate()));
        // 考核表
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.currentYear(currentDate);
        repurchasePVStatVO.setAssessTableName(tableName);
        startPage();
        list = iCuMemberAwardsStatService.selectRepurchasePVStatList(repurchasePVStatVO);

        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setAssessStatusVal(transactionMap.get(EnumsPrefixConstants.ASSESS_STATUS + itm.getAssessStatus().toString()));
                itm.setIsExamineVal(transactionMap.get(EnumsPrefixConstants.DEALER_YES_NO + itm.getIsExamine().toString()));
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
            });
        }

        ExcelUtil<RepurchasePVStatVO> util = new ExcelUtil<>(RepurchasePVStatVO.class);
        util.exportExcel(response, list, "复购PV统计");
    }


    /**
     * @description: 商城BV统计
     * @author: zhang jing
     * @date: 2023/8/30 10:44
     * @param: [mallPVStatVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MALL_BV_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/mallPv-list")
    public TableDataInfo mallPvList(MallPVStatVO mallPVStatVO) {
        Date date = DateUtils.currentDate();
        mallPVStatVO.setPkCountry(SecurityUtils.getPkCountry());
        if (StringUtils.isNull(mallPVStatVO.getStartDate()) ||
                StringUtils.isNull(mallPVStatVO.getEndDate())) {
            if (DateUtils.compareDateBefore(date, DateUtils.currentMonthFirstDate()) ||
                    DateUtils.compareDateEqual(date, DateUtils.currentMonthFirstDate())) {
                //之前月的第一天
                mallPVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthFirstDate()));
                mallPVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthLastDate()));
            } else {
                //当前月第一天
                mallPVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
                mallPVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
            }
        }

        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(mallPVStatVO.getStartDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(mallPVStatVO.getStartDate()))) {
            //当前月第一天
            mallPVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(mallPVStatVO.getEndDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(mallPVStatVO.getEndDate()))) {
            //当前日期的前一天
            mallPVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        //查询最新期数
        int staperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(mallPVStatVO.getStartDate())).getData().getPkId();
        mallPVStatVO.setPeriod(staperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(mallPVStatVO.getStartDate());
        mallPVStatVO.setAchieveTableName(achieveTableName);
        Date currentDate = DateUtils.afterDate(1, ChronoUnit.DAYS, DateUtils.parseStringToDate(mallPVStatVO.getStartDate()));
        // 考核表
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.currentYear(currentDate);
        mallPVStatVO.setAssessTableName(tableName);
        startPage();
        List<MallPVStatVO> list = iCuMemberAwardsStatService.selectMallPVStatList(mallPVStatVO);
        return getDataTable(list);
    }

    /**
     * @description:导出-商城BV统计
     * @author: zhang jing
     * @date: 2023/8/30 11:21
     * @param: [response, mallPVStatVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MALL_BV_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/export-mallPv")
    public void exportMallPv(HttpServletResponse response, MallPVStatVO mallPVStatVO) {
        Date date = DateUtils.currentDate();
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EAssessStatus.values(), EDealerYesNo.values());
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(
                EnumsPrefixConstants.KEY_AWARD);
        mallPVStatVO.setPkCountry(SecurityUtils.getPkCountry());
        if (StringUtils.isNull(mallPVStatVO.getStartDate()) ||
                StringUtils.isNull(mallPVStatVO.getEndDate())) {
            if (DateUtils.compareDateBefore(date, DateUtils.currentMonthFirstDate()) ||
                    DateUtils.compareDateEqual(date, DateUtils.currentMonthFirstDate())) {
                //之前月的第一天
                mallPVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthFirstDate()));
                mallPVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthLastDate()));
            } else {
                //当前月第一天
                mallPVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
                mallPVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
            }
        }

        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(mallPVStatVO.getStartDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(mallPVStatVO.getStartDate()))) {
            //当前月第一天
            mallPVStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(mallPVStatVO.getEndDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(mallPVStatVO.getEndDate()))) {
            //当前日期的前一天
            mallPVStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        List<MallPVStatVO> list = new ArrayList<>();
        //查询最新期数
        int staperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(mallPVStatVO.getStartDate())).getData().getPkId();
        mallPVStatVO.setPeriod(staperiod);
        String achieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(mallPVStatVO.getStartDate());
        mallPVStatVO.setAchieveTableName(achieveTableName);
        Date currentDate = DateUtils.afterDate(1, ChronoUnit.DAYS, DateUtils.parseStringToDate(mallPVStatVO.getStartDate()));
        // 考核表
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.currentYear(currentDate);
        mallPVStatVO.setAssessTableName(tableName);
        startPage();
        list = iCuMemberAwardsStatService.selectMallPVStatList(mallPVStatVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
                itm.setAssessStatusVal(transactionMap.get(EnumsPrefixConstants.ASSESS_STATUS + itm.getAssessStatus().toString()));
                itm.setIsExamineVal(transactionMap.get(EnumsPrefixConstants.DEALER_YES_NO + itm.getIsExamine().toString()));
            });
        }
        ExcelUtil<MallPVStatVO> util = new ExcelUtil<>(MallPVStatVO.class);
        util.exportExcel(response, list, "商城BV统计");
    }


    /**
     * @description: 个人统计
     * @author: zhang jing
     * @date: 2023/9/1 11:32
     * @param: [personStatVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PERSON_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/personStatList")
    public TableDataInfo personStatList(PersonStatVO personStatVO) {
        Date date = DateUtils.currentDate();
        personStatVO.setPkCountry(SecurityUtils.getPkCountry());
        if (StringUtils.isNull(personStatVO.getStartDate()) ||
                StringUtils.isNull(personStatVO.getEndDate())) {
            if (DateUtils.compareDateBefore(date, DateUtils.currentMonthFirstDate()) ||
                    DateUtils.compareDateEqual(date, DateUtils.currentMonthFirstDate())) {
                //之前月的第一天
                personStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthFirstDate()));
                personStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthLastDate()));
            } else {
                //当前月第一天
                personStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
                personStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
            }
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(personStatVO.getStartDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(personStatVO.getStartDate()))) {
            //当前月第一天
            personStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(personStatVO.getEndDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(personStatVO.getEndDate()))) {
            //当前日期的前一天
            personStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        //查询业绩集合
        List<PersonStatVO> perList = new ArrayList<>();

        //会员集合
        List<Long> pkMemberList = new ArrayList<>();
        startPage();
        List<PersonStatVO> list = iCuMemberAwardsStatService.selectPersonStatList(personStatVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm ->
                    pkMemberList.add(itm.getPkMember())
            );
        }
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> firstDaysOfMonth = getStrideMonth(personStatVO.getStartDate(), personStatVO.getEndDate());
            if (CollectionUtil.isNotEmpty(firstDaysOfMonth)) {
                for (String dateStr : firstDaysOfMonth) {
                    //查询最新期数
                    int staperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                            DateUtils.parseDateToStr(dateStr)).getData().getPkId();
                    PersonStatVO per = new PersonStatVO();
                    per.setPeriod(staperiod);
                    String achieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(dateStr);
                    per.setAchieveTableName(achieveTableName);
                    per.setPkMemberList(pkMemberList);
                    perList.add(per);
                }
            }
            List<PersonStatVO> newPvlist = iCuMemberAwardsStatService.selectPersonPvList(perList);
            if (CollectionUtil.isNotEmpty(list) && CollectionUtil.isNotEmpty(newPvlist)) {
                list.forEach(itm -> {
                    newPvlist.forEach(itmm -> {
                        if (itm.getPkMember().equals(itmm.getPkMember())) {
                            itm.setRealityPv(itmm.getRealityPv());
                        }
                    });
                });
            }
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出 个人统计
     * @author: zhang jing
     * @date: 2023/9/1 14:26
     * @param: [personStatVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PERSON_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/export-personStat")
    public void exportPersonStat(HttpServletResponse response, PersonStatVO personStatVO) {
        Date date = DateUtils.currentDate();
        personStatVO.setPkCountry(SecurityUtils.getPkCountry());
        if (StringUtils.isNull(personStatVO.getStartDate()) ||
                StringUtils.isNull(personStatVO.getEndDate())) {
            if (DateUtils.compareDateBefore(date, DateUtils.currentMonthFirstDate()) ||
                    DateUtils.compareDateEqual(date, DateUtils.currentMonthFirstDate())) {
                //之前月的第一天
                personStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthFirstDate()));
                personStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeMonthLastDate()));
            } else {
                //当前月第一天
                personStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
                personStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
            }
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(personStatVO.getStartDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(personStatVO.getStartDate()))) {
            //当前月第一天
            personStatVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
        }
        if (DateUtils.compareDateBefore(date, DateUtils.parseStringToDate(personStatVO.getEndDate())) ||
                DateUtils.compareDateEqual(date, DateUtils.parseStringToDate(personStatVO.getEndDate()))) {
            //当前日期的前一天
            personStatVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        //查询业绩集合
        List<PersonStatVO> perList = new ArrayList<>();

        //会员集合
        List<Long> pkMemberList = new ArrayList<>();
        startPage();
        List<PersonStatVO> list = iCuMemberAwardsStatService.selectPersonStatList(personStatVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm ->
                    pkMemberList.add(itm.getPkMember())
            );
        }
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> firstDaysOfMonth = getStrideMonth(personStatVO.getStartDate(), personStatVO.getEndDate());
            if (CollectionUtil.isNotEmpty(firstDaysOfMonth)) {
                for (String dateStr : firstDaysOfMonth) {
                    //查询最新期数
                    int staperiod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                            DateUtils.parseDateToStr(dateStr)).getData().getPkId();
                    PersonStatVO per = new PersonStatVO();
                    per.setPeriod(staperiod);
                    String achieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(dateStr);
                    per.setAchieveTableName(achieveTableName);
                    per.setPkMemberList(pkMemberList);
                    perList.add(per);
                }
            }
            List<PersonStatVO> newPvlist = iCuMemberAwardsStatService.selectPersonPvList(perList);
            if (CollectionUtil.isNotEmpty(list) && CollectionUtil.isNotEmpty(newPvlist)) {
                list.forEach(itm -> {
                    newPvlist.forEach(itmm -> {
                        if (itm.getPkMember().equals(itmm.getPkMember())) {
                            itm.setRealityPv(itmm.getRealityPv());
                        }
                    });
                });
            }
        }
        ExcelUtil<PersonStatVO> util = new ExcelUtil<>(PersonStatVO.class);
        util.exportExcel(response, list, "个人统计");
    }


    /**
     * @description: 直推统计-重新提交
     * @author: zhang jing
     * @date: 2023/9/1 16:13
     * @param: [personStatVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/directPushStatList")
    public TableDataInfo directPushStatList(DirectPushVO directPushVO) {
        Date date = DateUtils.currentDate();
        if (SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            directPushVO.setPkCountry(null);
        }else{
            directPushVO.setPkCountry(SecurityUtils.getPkCountry());
        }
        if (directPushVO.getOrderType() == null) {
            directPushVO.setOrderType(EOrderBusiness.WHOLE.getValue());
        }
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(directPushVO.getOrderType());
        if (StringUtils.isNull(directPushVO.getStartDate()) ||
                StringUtils.isNull(directPushVO.getEndDate())) {
            //当前月第一天
            directPushVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
            directPushVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        startPage();
        directPushVO.setOrderTypeList(orderTypeList);
        List<DirectPushVO> list = iCuMemberAwardsStatService.selectDirectPushStatList(directPushVO);
        return getDataTable(list);
    }

    /**
     * @description: 导出直推统计
     * @author: zhang jing
     * @date: 2023/9/4 15:27
     * @param: [directPushVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/export-directPush")
    public void exportDirectPush(HttpServletResponse response, DirectPushVO directPushVO) {
        Date date = DateUtils.currentDate();
        if (SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            directPushVO.setPkCountry(null);
        }else{
            directPushVO.setPkCountry(SecurityUtils.getPkCountry());
        }
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EOrderBusiness.values());
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        if (directPushVO.getOrderType() == null) {
            directPushVO.setOrderType(EOrderBusiness.WHOLE.getValue());
        }
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(directPushVO.getOrderType());
        directPushVO.setOrderTypeList(orderTypeList);
        if (StringUtils.isNull(directPushVO.getStartDate()) ||
                StringUtils.isNull(directPushVO.getEndDate())) {
            //当前月第一天
            directPushVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
            directPushVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }

        List<DirectPushVO> list = iCuMemberAwardsStatService.selectDirectPushStatList(directPushVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
                itm.setPkRegisterGradeVal(transactionMap1.get(itm.getPkRegisterGrade()));
                itm.setOrderTypeVal(transactionMap.get(EnumsPrefixConstants.ORDER_BUSINESS + itm.getOrderType().toString()));
            });
        }
        ExcelUtil<DirectPushVO> util = new ExcelUtil<>(DirectPushVO.class);
        util.exportExcel(response, list, "直推统计");
    }


    /**
     * @description: 会员订单分布统计
     * @author: zhang jing
     * @date: 2023/9/20 14:14
     * @param: [directPushVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.ORDER_SCATTER, method = EOperationMethod.SELECT)
    @GetMapping("/memberOrderScatter")
    public TableDataInfo memberOrderScatter(OrderScatterVO orderScatterVO) {
        Date date = DateUtils.currentDate();
        Integer pkCountry = SecurityUtils.getPkCountry();
        orderScatterVO.setPkCountry(pkCountry);
        if (StringUtils.isNull(orderScatterVO.getStartDate()) ||
                StringUtils.isNull(orderScatterVO.getEndDate())) {
            //当前月第一天
            orderScatterVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
            orderScatterVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderScatterVO.getOrderType());
        orderScatterVO.setOrderTypeList(orderTypeList);
        startPage();
        List<OrderScatterVO> list = iCuMemberAwardsStatService.memberOrderScatter(orderScatterVO);
        return getDataTable(list);
    }

    /**
     * @description: 导出会员订单分布统计
     * @author: zhang jing
     * @date: 2023/9/20 15:39
     * @param: [response, orderScatterVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.ORDER_SCATTER, method = EOperationMethod.EXPORT)
    @PostMapping("/export-OrderScatter")
    public void exportOrderScatter(HttpServletResponse response, OrderScatterVO orderScatterVO) {
        Date date = DateUtils.currentDate();
        Integer pkCountry = SecurityUtils.getPkCountry();
        orderScatterVO.setPkCountry(pkCountry);
        if (StringUtils.isNull(orderScatterVO.getStartDate()) ||
                StringUtils.isNull(orderScatterVO.getEndDate())) {
            //当前月第一天
            orderScatterVO.setStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentMonthFirstDate()));
            orderScatterVO.setEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date)));
        }
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderScatterVO.getOrderType());
        orderScatterVO.setOrderTypeList(orderTypeList);
        List<OrderScatterVO> list = iCuMemberAwardsStatService.memberOrderScatter(orderScatterVO);
        ExcelUtil<OrderScatterVO> util = new ExcelUtil<>(OrderScatterVO.class);
        util.exportExcel(response, list, "会员订单分布统计");
    }

    /**
     * @description: 查询跨月时间
     * @author: zhang jing
     * @date: 2023/8/28 14:10
     * @param: [startDate, endDate]
     * @return: java.util.List<java.lang.String>
     **/
    public List<String> getStrideMonth(String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate, formatter);
        LocalDate end = LocalDate.parse(endDate, formatter);
        List<String> firstDaysOfMonth = new ArrayList<>();
        while (!start.isAfter(end)) {
            YearMonth yearMonth = YearMonth.from(start);
            LocalDate firstDayOfMonth = yearMonth.atDay(1);
            firstDaysOfMonth.add(firstDayOfMonth.format(formatter));
            start = start.plusMonths(1);
        }
        return firstDaysOfMonth;
    }


    /**
     * @description: 安置业绩统计
     * @author: zhang jing
     * @date: 2024/3/7 15:53
     * @param: [psVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.POSIT_STAT, method = EOperationMethod.SELECT)
    @GetMapping("/positStatList")
    public TableDataInfo positStatList(PositStatVO psVO) {
        if (StringUtils.isEmpty(psVO.getStartDate()) || StringUtils.isEmpty(psVO.getEndDate())) {
            return getDataTable(new ArrayList<>());
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (pkCountry == CountryConstants.CHINA_COUNTRY) {
            return getDataTable(new ArrayList<>());
        }
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
        BigDecimal exchangeRate = currency.isSuccess() ? (currency.getData().getInExchangeRate() != null ? currency.getData().getInExchangeRate() : BigDecimal.ONE) : BigDecimal.ONE;
        psVO.setRate(exchangeRate);
        psVO.setPkCountry(pkCountry);
        //查询国家全部会员
        startPage();
        List<PositStatVO> list = iCuMemberAwardsStatService.positStatList(psVO);
        List<PositStatVO> listnew = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(psVO.getOrderType());
            psVO.setOrderTypeList(orderTypeList);
            Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE, EnumsPrefixConstants.KEY_AWARD);
            for (PositStatVO ps : list) {
                psVO.setPkMember(ps.getPkMember());
                // 查询会员所有部门
                List<Integer> placeDeptList = memberReportService.queryMemberPlaceDeptList(ps.getPkMember());
                if (CollectionUtil.isNotEmpty(placeDeptList)) {
                    psVO.setPlaceDeptList(placeDeptList);
                    ps.setPkAwardsVal(transactionMap1.get(ps.getPkAwards()));
                    ps.setPkSettleGradeVal(transactionMap1.get(ps.getPkSettleGrade()));
                    //查询会员伞下安置部门业绩
                    List<PositDeptAchieveVO> deptAchieveList = iCuMemberAwardsStatService.positStatAchieve(psVO);
                    if (CollectionUtil.isNotEmpty(deptAchieveList)) {
                        ps.setPositDeptAchieveVO(deptAchieveList);
                        listnew.add(ps);
                    }
                }
            }
        }
        TableDataInfo tableDataInfo = getDataTable(list);
        tableDataInfo.setRows(listnew);
        return tableDataInfo;
    }

    /**
     * @description: 导出安置业绩统计
     * @author: zhang jing
     * @date: 2024/2/25 14:53
     * @param: [response, psVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.POSIT_STAT, method = EOperationMethod.EXPORT)
    @PostMapping("/export-positStat")
    public void exportPositStat(HttpServletResponse response, PositStatVO psVO) {
        if (StringUtils.isEmpty(psVO.getStartDate()) || StringUtils.isEmpty(psVO.getEndDate())) {
            return;
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (pkCountry == CountryConstants.CHINA_COUNTRY) {
            return;
        }
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
        BigDecimal exchangeRate = currency.isSuccess() ? (currency.getData().getInExchangeRate() != null ? currency.getData().getInExchangeRate() : BigDecimal.ONE) : BigDecimal.ONE;
        psVO.setRate(exchangeRate);
        psVO.setPkCountry(pkCountry);
        //查询国家全部会员
        List<PositStatVO> list = iCuMemberAwardsStatService.positStatList(psVO);
        List<PositStatVO> listnew = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(psVO.getOrderType());
            psVO.setOrderTypeList(orderTypeList);

            Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE, EnumsPrefixConstants.KEY_AWARD);

            for (PositStatVO ps : list) {
                // 查询会员所有部门
                List<Integer> placeDeptList = memberReportService.queryMemberPlaceDeptList(ps.getPkMember());
                if (CollectionUtil.isNotEmpty(placeDeptList)) {
                    psVO.setPkMember(ps.getPkMember());
                    psVO.setPlaceDeptList(placeDeptList);
                    //查询会员伞下安置部门业绩
                    List<PositDeptAchieveVO> deptAchieveList = iCuMemberAwardsStatService.positStatAchieve(psVO);
                    ps.setPkAwardsVal(transactionMap1.get(ps.getPkAwards()));
                    ps.setPkSettleGradeVal(transactionMap1.get(ps.getPkSettleGrade()));
                    if (CollectionUtil.isNotEmpty(deptAchieveList)) {
                        String positDeptAchieve = "";
                        for (PositDeptAchieveVO pda : deptAchieveList) {
                            positDeptAchieve += "第" + pda.getPlaceDept() + "部门：金额：" + pda.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP) + "业绩：" + pda.getAchieve().setScale(2, BigDecimal.ROUND_HALF_UP) + " ";
                        }
                        ps.setPositDeptAchieve(positDeptAchieve);
                        listnew.add(ps);
                    }
                }
            }
        }
        ExcelUtil<PositStatVO> util = new ExcelUtil<>(PositStatVO.class);
        util.exportExcel(response, listnew, "安置业绩统计");
    }

//    private void updateAchieveValues(List<PositStatVO> achieveList, BigDecimal exchangeRate,PositStatVO ps) {
//        for (PositStatVO itmm : achieveList) {
//            ps.setLeftAchieve(itmm.getLeftAchieve());
//            ps.setLeftAmount(itmm.getLeftAmount().max(BigDecimal.ZERO).divide(exchangeRate, 2, BigDecimal.ROUND_HALF_UP));
//            ps.setRightAchieve(itmm.getRightAchieve());
//            ps.setRightAmount(itmm.getRightAmount().max(BigDecimal.ZERO).divide(exchangeRate, 2, BigDecimal.ROUND_HALF_UP));
//        }
//    }


    public static void initializeStoreNumbers(QueryParentStoreVO queryParentStoreVO) {
        Field[] fields = queryParentStoreVO.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getType() == int.class || field.getType() == Integer.class) {
                String fieldName = field.getName();
                if (fieldName.startsWith("storeNumber")) {
                    try {
                        field.setAccessible(true);
                        Integer value = (Integer) field.get(queryParentStoreVO);
                        if (value == null) {
                            field.set(queryParentStoreVO, 0);
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("Failed to access field", e);
                    }
                }
            }
        }
    }

    /**
     * @description:业绩汇总
     * @author: zhang jing
     * @date: 2024/5/27 11:24
     * @param: [achieveSummaryVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.ACHIEVE_SUMMARY, method = EOperationMethod.SELECT)
    @GetMapping("/achieveSummary")
    public TableDataInfo achieveSummary(AchieveSummaryVO achieveSummaryVO) {
        List<AchieveSummaryVO> list = new ArrayList<>();
        if (StringUtils.isEmpty(achieveSummaryVO.getOrderDate())) {
            return getDataTable(list);
        }
        //中国汇率
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY);
        BigDecimal cent = new BigDecimal(100);
        //查询所有国家
        R<Map<Integer, BdCountry>> countryMap = iCountryServiceApi.getAllCountryMap();
        Set<Integer> countryIdList = new HashSet<>();
        countryMap.getData().forEach((key, value) -> {
            countryIdList.add(key);
        });
        achieveSummaryVO.setCountryIdList(countryIdList);
        //查询所有国家的汇率
        R<List<CurrencyDTO>> currencyList = currencyServiceApi.getCurrencyByPkCountryList(countryIdList);
        //查询最新期数
        achieveSummaryVO.setPeriodSta(cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(achieveSummaryVO.getOrderDate())).getData().getPkId());
        achieveSummaryVO.setSettleTableName(TableNameConstants.CU_MEMBER_SETTLE + achieveSummaryVO.getPeriodSta());
        list = iCuMemberAwardsStatService.achieveSummaryList(achieveSummaryVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setStartDate(achieveSummaryVO.getOrderDate());
                itm.setEndDate(achieveSummaryVO.getOrderDate());
                itm.setOrderDate(achieveSummaryVO.getOrderDate());
                currencyList.getData().forEach(itmm -> {
                    if (itmm.getPkCountry() != null && (itmm.getPkCountry().equals(itm.getPkSettleCountry()))) {
                        itm.setOrderAmount(itm.getOrderAmount().divide(itmm.getInExchangeRate(), 4, RoundingMode.HALF_UP));
                        itm.setOrderAmount(itm.getOrderAmount().multiply(currency.getData().getInExchangeRate()));
                        itm.setOrderAmountSum(itm.getOrderAmountSum().divide(itmm.getInExchangeRate(), 4, RoundingMode.HALF_UP));
                        itm.setOrderAmountSum(itm.getOrderAmountSum().multiply(currency.getData().getInExchangeRate()));
                        BigDecimal exchangeRate = itmm.getInExchangeRate() == null ? BigDecimal.ONE : itmm.getInExchangeRate();
                        //查询奖金扣项配置参数
                        List<AchieveSummaryVO> bonus = iCuMemberAwardsStatService.bonusDeduct(itm);
                        if (CollectionUtil.isNotEmpty(bonus)) {
                            itm.setBackRatio(BigDecimal.ONE.subtract(bonus.get(0).getBackRatio()));
                        } else {
                            itm.setBackRatio(BigDecimal.ONE);
                        }
                        //查询首购奖金拨比
                        itm.setPerCent(exchangeRate.multiply(cent));
                        itm.setMainBonusRate(iCuMemberAwardsStatService.queryForeignCountryCuBonusStatisSum(itm));
                    }
                });
            });
        }
        return getDataTable(list);
    }

    /**
     * @description:业绩汇总
     * @author: zhang jing
     * @date: 2024/5/27 11:24
     * @param: [achieveSummaryVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.ACHIEVE_SUMMARY, method = EOperationMethod.SELECT)
    @PostMapping("/excel-achieveSummary")
    public void excelAchieveSummary(HttpServletResponse response, AchieveSummaryVO achieveSummaryVO) {
        List<AchieveSummaryVO> list = new ArrayList<>();
        if (StringUtils.isEmpty(achieveSummaryVO.getOrderDate())) {
            return;
        }
        //中国汇率
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY);
        BigDecimal cent = new BigDecimal(100);
        //查询所有国家
        R<Map<Integer, BdCountry>> countryMap = iCountryServiceApi.getAllCountryMap();
        Set<Integer> countryIdList = new HashSet<>();
        countryMap.getData().forEach((key, value) -> {
            countryIdList.add(key);
        });
        achieveSummaryVO.setCountryIdList(countryIdList);
        //查询所有国家的汇率
        R<List<CurrencyDTO>> currencyList = currencyServiceApi.getCurrencyByPkCountryList(countryIdList);
        //查询最新期数
        achieveSummaryVO.setPeriodSta(cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(achieveSummaryVO.getOrderDate())).getData().getPkId());
        achieveSummaryVO.setSettleTableName(TableNameConstants.CU_MEMBER_SETTLE + achieveSummaryVO.getPeriodSta());
        list = iCuMemberAwardsStatService.achieveSummaryList(achieveSummaryVO);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setStartDate(achieveSummaryVO.getOrderDate());
                itm.setEndDate(achieveSummaryVO.getOrderDate());
                itm.setOrderDate(achieveSummaryVO.getOrderDate());
                currencyList.getData().forEach(itmm -> {
                    if (itmm.getPkCountry() != null && (itmm.getPkCountry().equals(itm.getPkSettleCountry()))) {
                        itm.setOrderAmount(itm.getOrderAmount().divide(itmm.getInExchangeRate(), 4, RoundingMode.HALF_UP));
                        itm.setOrderAmount(itm.getOrderAmount().multiply(currency.getData().getInExchangeRate()));
                        itm.setOrderAmountSum(itm.getOrderAmountSum().divide(itmm.getInExchangeRate(), 4, RoundingMode.HALF_UP));
                        itm.setOrderAmountSum(itm.getOrderAmountSum().multiply(currency.getData().getInExchangeRate()));
                        BigDecimal exchangeRate = itmm.getInExchangeRate() == null ? BigDecimal.ONE : itmm.getInExchangeRate();
                        //查询奖金扣项配置参数
                        List<AchieveSummaryVO> bonus = iCuMemberAwardsStatService.bonusDeduct(itm);
                        if (CollectionUtil.isNotEmpty(bonus)) {
                            itm.setBackRatio(BigDecimal.ONE.subtract(bonus.get(0).getBackRatio()));
                        } else {
                            itm.setBackRatio(BigDecimal.ONE);
                        }
                        //查询首购奖金拨比
                        itm.setPerCent(exchangeRate.multiply(cent));
                        itm.setMainBonusRate(iCuMemberAwardsStatService.queryForeignCountryCuBonusStatisSum(itm));
                    }
                });
            });
        }
        ExcelUtil<AchieveSummaryVO> util = new ExcelUtil<>(AchieveSummaryVO.class);
        util.exportExcel(response, list, "业绩汇总统计");
    }

    /**
     * @description: 推荐店铺查询统计（查询的数据存入表中）
     * @author: zhang jing
     * @date: 2024/8/1 10:12
     * @param: [queryParentStoreVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.QUERY_PARENT_STORE, method = EOperationMethod.SUBMIT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/parent-store-stat")
    public AjaxResult parentStoreStat() {
        //查询开通店铺会员的推荐
        List<QueryParentStoreVO> list = iCuMemberAwardsStatService.queryReferenceList(null);
        if (CollectionUtil.isNotEmpty(list)) {
            //初始化数据
            cuParentStoreServiceApi.delCuParentStore();
            list.parallelStream().forEach(itm -> {
                StoreNumberVO snb = iCuMemberAwardsStatService.queryParentStoreList(itm);
                if (snb != null) {
                    itm.setPlaceDept(snb.getPlaceDept());
                    itm.setStoreNumber(snb.getStoreNumber());
                }
                CuParentStore cuParentStore = BeanUtil.copyProperties(itm, CuParentStore.class);
                cuParentStore.setPkCreator(SecurityUtils.getUserId());
                cuParentStoreServiceApi.saveCuParentStore(cuParentStore);
            });
        }
        return AjaxResult.success();
    }

    /**
     * @description: 推荐店铺查询
     * @author: zhang jing
     * @date: 2024/7/26 16:10
     * @param: [queryParentStoreVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.QUERY_PARENT_STORE, method = EOperationMethod.SELECT)
    @GetMapping("/query-parent-store")
    public TableDataInfo queryParentStore(QueryParentStoreVO queryParentStoreVO) {
        List<Integer> storeNumberList = new ArrayList<>();
        initializeStoreNumbers(queryParentStoreVO);
        storeNumberList.add(queryParentStoreVO.getStoreNumber1());
        storeNumberList.add(queryParentStoreVO.getStoreNumber2());
        storeNumberList.add(queryParentStoreVO.getStoreNumber3());
        storeNumberList.add(queryParentStoreVO.getStoreNumber4());
        storeNumberList.add(queryParentStoreVO.getStoreNumber5());
        Collections.sort(storeNumberList);
        queryParentStoreVO.setStoreNumber1(storeNumberList.get(4));
        queryParentStoreVO.setStoreNumber2(storeNumberList.get(3));
        queryParentStoreVO.setStoreNumber3(storeNumberList.get(2));
        queryParentStoreVO.setStoreNumber4(storeNumberList.get(1));
        queryParentStoreVO.setStoreNumber5(storeNumberList.get(0));
        // 使用流式操作过滤并计数
        long count = storeNumberList.stream()
                .filter(num -> num > 0)
                .count();
        queryParentStoreVO.setStoreSize((int) count);
        startPage();
        //查询开通店铺会员的推荐
        List<QueryParentStoreVO> list = iCuMemberAwardsStatService.getParentStoreList(queryParentStoreVO);
        List<Long> pkMemberList = new ArrayList<>();
        pkMemberList.addAll(list.stream().map(QueryParentStoreVO::getPkMember).collect(Collectors.toList()));
        queryParentStoreVO.setPkMemberList(pkMemberList);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                List<StoreNumberVO> storList = new ArrayList<>();
                List<Integer> dsList = Arrays.stream(itm.getPlaceDeptStr().split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                List<Integer> snList = Arrays.stream(itm.getStoreNumberStr().split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                for (int i = 0; i < dsList.size(); i++) {
                    int placeDept = dsList.get(i);
                    int storeNumber = snList.get(i);
                    StoreNumberVO storeNumberVO = new StoreNumberVO();
                    storeNumberVO.setPlaceDept(placeDept);
                    storeNumberVO.setStoreNumber(storeNumber);
                    storList.add(storeNumberVO);
                }
                Collections.sort(storList, Comparator.comparing(StoreNumberVO::getPlaceDept));
                itm.setStorList(storList);
            });
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出推荐店铺查询
     * @author: zhang jing
     * @date: 2024/7/30 15:41
     * @param: [response, queryParentStoreVO]
     * @return: void
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.QUERY_PARENT_STORE, method = EOperationMethod.EXPORT)
    @PostMapping("/excel-parentStore")
    public void excelParentStore(HttpServletResponse response, QueryParentStoreVO queryParentStoreVO) {

        List<Integer> storeNumberList = new ArrayList<>();
        storeNumberList.add(queryParentStoreVO.getStoreNumber1());
        storeNumberList.add(queryParentStoreVO.getStoreNumber2());
        storeNumberList.add(queryParentStoreVO.getStoreNumber3());
        storeNumberList.add(queryParentStoreVO.getStoreNumber4());
        storeNumberList.add(queryParentStoreVO.getStoreNumber5());
        Collections.sort(storeNumberList);
        queryParentStoreVO.setStoreNumber1(storeNumberList.get(4));
        queryParentStoreVO.setStoreNumber2(storeNumberList.get(3));
        queryParentStoreVO.setStoreNumber3(storeNumberList.get(2));
        queryParentStoreVO.setStoreNumber4(storeNumberList.get(1));
        queryParentStoreVO.setStoreNumber5(storeNumberList.get(0));
        // 使用流式操作过滤并计数
        long count = storeNumberList.stream()
                .filter(num -> num > 0)
                .count();
        queryParentStoreVO.setStoreSize((int) count);
        startPage();
        //查询开通店铺会员的推荐
        List<QueryParentStoreVO> list = iCuMemberAwardsStatService.getParentStoreList(queryParentStoreVO);
        List<Long> pkMemberList = new ArrayList<>();
        pkMemberList.addAll(list.stream().map(QueryParentStoreVO::getPkMember).collect(Collectors.toList()));
        queryParentStoreVO.setPkMemberList(pkMemberList);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                StringBuffer str = new StringBuffer();
                List<Integer> dsList = Arrays.stream(itm.getPlaceDeptStr().split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                List<Integer> snList = Arrays.stream(itm.getStoreNumberStr().split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                for (int i = 0; i < dsList.size(); i++) {
                    int placeDept = dsList.get(i);
                    int storeNumber = snList.get(i);
                    str.append("第" + placeDept + "部门: 门店铺数量:" + storeNumber);
                }
                itm.setPlaceDeptSetOf(str.toString());
            });
        }
        ExcelUtil<QueryParentStoreVO> util = new ExcelUtil<>(QueryParentStoreVO.class);
        util.exportExcel(response, list, "推荐店铺查询");
    }

    /**
     * @description: 推荐店铺查询详情
     * @author: zhang jing
     * @date: 2024/7/30 16:52
     * @param: [pkId]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.QUERY_PARENT_STORE, method = EOperationMethod.SELECT)
    @GetMapping("/parent-store-details")
    public TableDataInfo parentStoreDetails(ParentStoreDetailsVO psdVo) {
        startPage();
        //推荐店铺查询详情
        List<ParentStoreDetailsVO> listId=iCuMemberAwardsStatService.parentStoreDetailsId(psdVo);
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(ELevelValue.values());
        List<ParentStoreDetailsVO> list=new ArrayList<>();
        for(ParentStoreDetailsVO ps:listId){
            ParentStoreDetailsVO psd= iCuMemberAwardsStatService.parentStoreDetails(ps.getPkId(),psdVo.getPkId());
            psd.setStoreLevelName(transactionMap.get(EnumsPrefixConstants.ELEVEL_VALUE+psd.getLevelValue()));
            list.add(psd);
        }
        return getDataTable(list);
    }

}
