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.TableNameConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
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.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.achieve.ext.CuMemberAchieveExt;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.report.member.param.*;
import com.hzs.report.member.service.IMemberService;
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.IAreaServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequestMapping("/manager/member-report")
@RestController
public class MemberReportController extends BaseController {

    @Autowired
    private MemberReportService memberReportService;
    @Autowired
    private IMemberService iMemberService;
    @Autowired
    private ICuMemberSettlePeriodService iCuMemberSettlePeriodService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    IAreaServiceApi iAreaServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;

    /**
     * 伞下直推新增业绩
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW, method = EOperationMethod.SELECT)
    @GetMapping("/direct-push-new")
    public TableDataInfo directPushNew(String memberCode, Integer pkCountry,
                                       Date startPayTime, Date endPayTime) {

        if (StringUtils.isNull(startPayTime) || StringUtils.isNull(endPayTime)) {
            return getDataTable(new ArrayList<>());
        }
        if (pkCountry == null) {
            pkCountry = SecurityUtils.getPkCountry();
        }

        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(startPayTime, date) > 0 || DateUtils.compareDate(endPayTime, date) > 0) {
            return getDataTable(new ArrayList<>());
        }
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, startPayTime));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        DirectPushNewVo dpo = new DirectPushNewVo();
        if (date1.equals(date2) || (DateUtils.compareDate(endPayTime, date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        }
        Date zonpayTime = DateUtils.afterDate(1, ChronoUnit.DAYS, endPayTime);
        dpo.setZonpayTime(zonpayTime);
        dpo.setEndPayTime(endPayTime);

        CuMemberSettlePeriod startPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr);
        if (null == startPeriod) {
            throw new ServiceException("查询开始时间不存在数据");
        }
        int periodSta = startPeriod.getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();

        dpo.setPkCountry(pkCountry);
        //查询最新期数
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_RETAIL_RANGE + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_RETAIL_RANGE + periodEnd);
        if (memberReportService.selectExistTable(dpo.getAchieveTableNameSta()) == 0 ||
                memberReportService.selectExistTable(dpo.getAchieveTableNameEnd()) == 0
        ) {
            return getDataTable(new ArrayList<>());
        }
        if (StringUtils.isEmpty(memberCode)) {
            return getDataTable(new ArrayList<>());
        }
        //查询会员
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(Collections.singletonList(memberCode), pkCountry, startPayTime, endPayTime);
        if (CollectionUtil.isEmpty(memberList)) {
            return getDataTable(new ArrayList<>());
        }
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        //伞下直推新增业绩
        List<DirectPushNewVo> achieList = memberReportService.directPushNewAchieUpList(dpo, Collections.singletonList(memberList.get(0).getPkMember()));
        //查询大小区业绩
        DirectPushNewVo sizeZoneAchie = memberReportService.sizeZoneAchie(dpo, memberList.get(0).getPkMember(), currency.getData().getInExchangeRate());
        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                if (null != achieList.get(0)) {
                    if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                        //中国业绩转为人民币
                        itm.setOrderAchieve(achieList.get(0).getOrderAchieve().multiply(currency.getData().getInExchangeRate()));
                    }
                    itm.setOrderAmount(achieList.get(0).getOrderAmount());
                    if (sizeZoneAchie != null) {
                        itm.setSmallAreaPv(sizeZoneAchie.getSmallAreaPv());
                        itm.setBigArealPv(sizeZoneAchie.getBigArealPv());
                    }
                    itm.setOrderAmount(itm.getOrderAmount().multiply(currency.getData().getInExchangeRate()));
                }
            });
        }
        return getDataTable(memberList);
    }


    /**
     * 导入批量查询会员信息
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW, method = EOperationMethod.IMPORT)
    @PostMapping("/batch-importData")
    public AjaxResult batchImportData(@RequestParam("file") MultipartFile file) throws Exception {
        ExcelUtil<CuMemberImportVO> util = new ExcelUtil<>(CuMemberImportVO.class);
        StringBuilder memberCodeStr = new StringBuilder();
        List<CuMemberImportVO> memberCodeList = util.importExcel(file.getInputStream());
        if (memberCodeList.size() > 30) {
            return AjaxResult.error("导入Excel的会员数据不能超过30条");
        }
        if (CollectionUtil.isNotEmpty(memberCodeList)) {
            List<CuMemberImportVO> distinctList = new ArrayList<>(memberCodeList.stream()
                    .collect(Collectors.toMap(CuMemberImportVO::getMemberCode,
                            vo -> vo,
                            (existing, replacement) -> existing))
                    .values());
            for (CuMemberImportVO cu : distinctList) {
                memberCodeStr.append(cu.getMemberCode()).append(",");
            }
        }
        DirectPushNewVo dpo = new DirectPushNewVo();
        dpo.setMemberCodeStr(memberCodeStr.toString());
        dpo.setStartPayTime(memberCodeList.get(0).getStartPayTime());
        dpo.setEndPayTime(memberCodeList.get(0).getEndPayTime());
        return AjaxResult.success(dpo);
    }


    /**
     * 导出伞下直推新增业绩
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW, method = EOperationMethod.EXPORT)
    @PostMapping("/export-direct-push-new")
    public void batchImportExport(HttpServletResponse response, DirectPushNewVo dpo) throws Exception {
        List<String> memberCodeList;
        if (StringUtils.isNotEmpty(dpo.getMemberCodeStr())) {
            memberCodeList = Arrays.asList(dpo.getMemberCodeStr().split(","));
            if (CollectionUtil.isNotEmpty(memberCodeList)) {
                dpo.setMemberCodeList(memberCodeList);
            }
        }

        Date startPayTime = dpo.getStartPayTime();
        Date endPayTime = dpo.getEndPayTime();
        if (StringUtils.isNull(startPayTime) || StringUtils.isNull(endPayTime)) {
            return;
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(startPayTime, date) > 0 || DateUtils.compareDate(endPayTime, date) > 0) {
            return;
        }
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, startPayTime));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        if (date1.equals(date2) || (DateUtils.compareDate(endPayTime, date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        }
        Date zonpayTime = DateUtils.afterDate(1, ChronoUnit.DAYS, dpo.getEndPayTime());
        dpo.setZonpayTime(zonpayTime);
        //查询最新期数
        int periodSta = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr).getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();
        dpo.setPkCountry(pkCountry);
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_RETAIL_RANGE + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_RETAIL_RANGE + periodEnd);
        //伞下直推新增业绩
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(dpo.getMemberCodeList(), pkCountry, startPayTime, endPayTime);
        List<Long> pkMemberList = memberList.stream().map(DirectPushNewVo::getPkMember).collect(Collectors.toList());
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        List<DirectPushNewVo> achieList = memberReportService.directPushNewAchieUpList(dpo, pkMemberList);

        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                //查询大小区业绩
                DirectPushNewVo sizeZoneAchie = memberReportService.sizeZoneAchie(dpo, itm.getPkMember(), currency.getData().getInExchangeRate());
                if (sizeZoneAchie != null) {
                    itm.setSmallAreaPv(sizeZoneAchie.getSmallAreaPv());
                    itm.setBigArealPv(sizeZoneAchie.getBigArealPv());
                }
                achieList.forEach(itmm -> {
                    if (itm.getPkMember().equals(itmm.getPkMember())) {
                        itm.setOrderAchieve(itmm.getOrderAchieve());
                        itm.setOrderAmount(itmm.getOrderAmount());
                    }
                });
                if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                    //中国业绩转为人民币
                    itm.setOrderAchieve(itm.getOrderAchieve().multiply(currency.getData().getInExchangeRate()));
                    itm.setOrderAmount(itm.getOrderAmount().multiply(currency.getData().getInExchangeRate()));
                }
            });
        }
        ExcelUtil<DirectPushNewVo> util = new ExcelUtil<>(DirectPushNewVo.class);
        util.exportExcel(response, memberList, "伞下直推新增业绩导出");
    }

    /**
     * 伞下直推新增业金额绩大小区金额业绩详情
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW_DETAILS, method = EOperationMethod.SELECT)
    @GetMapping("/directPush-up-details")
    public TableDataInfo directPushUpDetails(DirectPushNewVo dpo) {
        if (StringUtils.isNull(dpo.getStartPayTime()) || StringUtils.isNull(dpo.getEndPayTime())) {
            return getDataTable(new ArrayList<>());
        }
        if (StringUtils.isNull(dpo.getMemberCode())) {
            return getDataTable(new ArrayList<>());
        }
        R<CuMember> memberDto = iMemberServiceApi.getMember(dpo.getMemberCode());
        CuMember member = memberDto.getData();
        if (member == null) {
            return getDataTable(new ArrayList<>());
        }
        dpo.setPkMember(member.getPkId());
        dpo.setMemberCode(null);
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(dpo.getStartPayTime(), date) > 0 || DateUtils.compareDate(dpo.getEndPayTime(), date) > 0) {
            return getDataTable(new ArrayList<>());
        }
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dpo.getEndPayTime());
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, dpo.getStartPayTime()));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dpo.getEndPayTime());
        if (date1.equals(date2) || (DateUtils.compareDate(dpo.getEndPayTime(), date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        }
        dpo.setEndPayTime(dpo.getEndPayTime());
        int periodSta = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr).getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();
        dpo.setPkCountry(pkCountry);
        //查询最新期数
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodEnd);
        if (memberReportService.selectExistTable(dpo.getAchieveTableNameSta()) == 0 ||
                memberReportService.selectExistTable(dpo.getAchieveTableNameEnd()) == 0
        ) {
            return getDataTable(new ArrayList<>());
        }
        //查询会员
        List<DirectPushNewVo> memberList = memberReportService.querDirectPushDetails(dpo);
        if (CollectionUtil.isEmpty(memberList)) {
            return getDataTable(new ArrayList<>());
        }
        List<Long> pkMemberList = memberList.stream().map(DirectPushNewVo::getPkMember).collect(Collectors.toList());
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        //伞下直推新增业绩
        List<DirectPushNewVo> achieList = memberReportService.directPushNewAchieList(dpo, pkMemberList);
        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                if (CollectionUtil.isNotEmpty(achieList)) {
                    achieList.forEach(itmm -> {
                        if (itm.getPkMember().equals(itmm.getPkMember())) {
                            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                                //中国业绩转为人民币
                                itm.setOrderAchieve(itmm.getOrderAchieve().multiply(currency.getData().getInExchangeRate()));
                            } else {
                                itm.setOrderAchieve(itmm.getOrderAchieve());
                            }
                            itm.setOrderAmount(itmm.getOrderAmount());
                        }
                    });
                }
            });
        }
        List<DirectPushNewDetailsVo> dpdVoList = new ArrayList<>();
        memberList.forEach(itm -> dpdVoList.add(BeanUtil.copyProperties(itm, DirectPushNewDetailsVo.class)));
        return getDataTable(dpdVoList);
    }

    /**
     * 导出伞下直推新增业金额绩大小区金额业绩详情
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW_DETAILS, method = EOperationMethod.EXPORT)
    @PostMapping("/export-directPush-up-details")
    public void exportDirectPushUpDetails(HttpServletResponse response, DirectPushNewVo dpo) {
        if (StringUtils.isNull(dpo.getStartPayTime()) || StringUtils.isNull(dpo.getEndPayTime())) {
            return;
        }
        if (StringUtils.isNull(dpo.getMemberCode())) {
            return;
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(dpo.getStartPayTime(), date) > 0 || DateUtils.compareDate(dpo.getEndPayTime(), date) > 0) {
            return;
        }
        R<CuMember> memberDto = iMemberServiceApi.getMember(dpo.getMemberCode());
        CuMember member = memberDto.getData();
        if (member == null) {
            return;
        }
        dpo.setPkMember(member.getPkId());
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dpo.getEndPayTime());
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, dpo.getStartPayTime()));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dpo.getEndPayTime());
        if (date1.equals(date2) || (DateUtils.compareDate(dpo.getEndPayTime(), date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        }
        dpo.setEndPayTime(dpo.getEndPayTime());
        int periodSta = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr).getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();
        dpo.setPkCountry(pkCountry);
        //查询最新期数
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodEnd);
        if (memberReportService.selectExistTable(dpo.getAchieveTableNameSta()) == 0 ||
                memberReportService.selectExistTable(dpo.getAchieveTableNameEnd()) == 0
        ) {
            return;
        }
        //查询会员
        List<DirectPushNewVo> memberList = memberReportService.querDirectPushDetails(dpo);
        if (CollectionUtil.isEmpty(memberList)) {
            return;
        }
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        //伞下直推新增业绩
        List<DirectPushNewVo> achieList = memberReportService.directPushNewAchieList(dpo, Arrays.asList(memberList.get(0).getPkMember()));
        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                if (CollectionUtil.isNotEmpty(achieList)) {
                    achieList.forEach(itmm -> {
                        if (itm.getPkMember().equals(itmm.getPkMember())) {
                            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                                //中国业绩转为人民币
                                itm.setOrderAchieve(itmm.getOrderAchieve().multiply(currency.getData().getInExchangeRate()));
                            } else {
                                itm.setOrderAchieve(itmm.getOrderAchieve());
                            }
                            itm.setOrderAmount(itmm.getOrderAmount());
                        }
                    });
                }
            });
        }
        List<DirectPushNewDetailsVo> dpdVoList = new ArrayList<>();
        memberList.forEach(itm -> dpdVoList.add(BeanUtil.copyProperties(itm, DirectPushNewDetailsVo.class)));
        ExcelUtil<DirectPushNewDetailsVo> util = new ExcelUtil<>(DirectPushNewDetailsVo.class);
        util.exportExcel(response, dpdVoList, "伞下直推新增业绩详情导出");
    }

    /**
     * 伞下直推新增业金额绩大小区金额业绩(新)
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW, method = EOperationMethod.SELECT)
    @GetMapping("/direct-push-new-up")
    public TableDataInfo directPushNewUp(String memberCode, Integer pkCountry,
                                         Date startPayTime, Date endPayTime) {
        if (StringUtils.isNull(startPayTime) || StringUtils.isNull(endPayTime)) {
            return getDataTable(new ArrayList<>());
        }
        if (pkCountry == null) {
            pkCountry = SecurityUtils.getPkCountry();
        }

        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(startPayTime, date) > 0 || DateUtils.compareDate(endPayTime, date) > 0) {
            return getDataTable(new ArrayList<>());
        }
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, startPayTime));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        DirectPushNewVo dpo = new DirectPushNewVo();
        if (date1.equals(date2) || (DateUtils.compareDate(endPayTime, date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
            String dateNow = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
            dpo.setAchieveTableNameNow(TableNameConstants.CU_MEMBER_RETAIL_S + iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(dateNow).getPkId());
        }
        Date zonpayTime = DateUtils.afterDate(1, ChronoUnit.DAYS, endPayTime);
        dpo.setZonpayTime(zonpayTime);
        dpo.setEndPayTime(endPayTime);

        CuMemberSettlePeriod startPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr);
        if (null == startPeriod) {
            throw new ServiceException("查询开始时间不存在数据");
        }
        int periodSta = startPeriod.getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();
        dpo.setPkCountry(pkCountry);
        //查询最新期数
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodEnd);
        if (memberReportService.selectExistTable(dpo.getAchieveTableNameSta()) == 0 ||
                memberReportService.selectExistTable(dpo.getAchieveTableNameEnd()) == 0
        ) {
            return getDataTable(new ArrayList<>());
        }
        if (StringUtils.isEmpty(memberCode)) {
            return getDataTable(new ArrayList<>());
        }
        //查询会员
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(Collections.singletonList(memberCode), pkCountry, startPayTime, endPayTime);
        if (CollectionUtil.isEmpty(memberList)) {
            return getDataTable(new ArrayList<>());
        }
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        //伞下直推新增业绩
        List<DirectPushNewVo> achieList = memberReportService.directPushNewAchieList(dpo, Collections.singletonList(memberList.get(0).getPkMember()));
        //查询大小区业绩
        DirectPushNewVo sizeZoneAchie = memberReportService.sizeZoneAchieAmount(dpo, memberList.get(0).getPkMember(), currency.getData().getInExchangeRate());
        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                if (CollectionUtil.isNotEmpty(achieList)) {
                    if (null != achieList.get(0)) {
                        itm.setOrderAchieve(achieList.get(0).getOrderAchieve());
                        itm.setOrderAmount(achieList.get(0).getOrderAmount());
                        itm.setRegAmount(achieList.get(0).getRegAmount());
                        itm.setRegAchieve(achieList.get(0).getRegAchieve());
                        itm.setUpgAmount(achieList.get(0).getUpgAmount());
                        itm.setUpgAchieve(achieList.get(0).getUpgAchieve());
                        itm.setRepAmount(achieList.get(0).getRepAmount());
                        itm.setRepAchieve(achieList.get(0).getRepAchieve());
                        itm.setConAmount(achieList.get(0).getConAmount());
                        itm.setConAchieve(achieList.get(0).getConAchieve());
                        if (sizeZoneAchie != null) {
                            itm.setSmallAreaPv(sizeZoneAchie.getSmallAreaPv());
                            itm.setBigArealPv(sizeZoneAchie.getBigArealPv());
                            itm.setSmallAreaAm(sizeZoneAchie.getSmallAreaAm());
                            itm.setBigArealAm(sizeZoneAchie.getBigArealAm());
                        }
                        //中国业绩转为人民币
                        itm.setOrderAchieve(itm.getOrderAchieve().multiply(currency.getData().getInExchangeRate()));
                        itm.setRegAchieve(itm.getRegAchieve().multiply(currency.getData().getInExchangeRate()));
                        itm.setUpgAchieve(itm.getUpgAchieve().multiply(currency.getData().getInExchangeRate()));
                        itm.setRepAchieve(itm.getRepAchieve().multiply(currency.getData().getInExchangeRate()));
                        itm.setConAchieve(itm.getConAchieve().multiply(currency.getData().getInExchangeRate()));
                    }
                }
            });
        }
        return getDataTable(memberList);
    }

    /**
     * 导出伞下直推新增业金额绩大小区金额业绩(新)
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW, method = EOperationMethod.EXPORT)
    @PostMapping("/export-direct-push-new-up")
    public void exportUp(HttpServletResponse response, DirectPushNewVo dpo) {
        List<String> memberCodeList;
        if (StringUtils.isNotEmpty(dpo.getMemberCodeStr())) {
            memberCodeList = Arrays.asList(dpo.getMemberCodeStr().split(","));
            if (CollectionUtil.isNotEmpty(memberCodeList)) {
                dpo.setMemberCodeList(memberCodeList);
            }
        }

        Date startPayTime = dpo.getStartPayTime();
        Date endPayTime = dpo.getEndPayTime();
        if (StringUtils.isNull(startPayTime) || StringUtils.isNull(endPayTime)) {
            return;
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(startPayTime, date) > 0 || DateUtils.compareDate(endPayTime, date) > 0) {
            return;
        }
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, startPayTime));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        if (date1.equals(date2) || (DateUtils.compareDate(endPayTime, date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
            String dateNow = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
            dpo.setAchieveTableNameNow(TableNameConstants.CU_MEMBER_RETAIL_S + iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(dateNow).getPkId());
        }
        Date zonpayTime = DateUtils.afterDate(1, ChronoUnit.DAYS, dpo.getEndPayTime());
        dpo.setZonpayTime(zonpayTime);
        //查询最新期数
        int periodSta = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr).getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();
        dpo.setPkCountry(pkCountry);
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodEnd);
        //伞下直推新增业绩
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(dpo.getMemberCodeList(), pkCountry, startPayTime, endPayTime);
        List<Long> pkMemberList = memberList.stream().map(DirectPushNewVo::getPkMember).collect(Collectors.toList());
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        List<DirectPushNewVo> achieList = memberReportService.directPushNewAchieList(dpo, pkMemberList);

        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                //查询大小区业绩
                DirectPushNewVo sizeZoneAchie = memberReportService.sizeZoneAchieAmount(dpo, itm.getPkMember(), currency.getData().getInExchangeRate());
                if (sizeZoneAchie != null) {
                    itm.setSmallAreaPv(sizeZoneAchie.getSmallAreaPv());
                    itm.setBigArealPv(sizeZoneAchie.getBigArealPv());
                    itm.setSmallAreaAm(sizeZoneAchie.getSmallAreaAm());
                    itm.setBigArealAm(sizeZoneAchie.getBigArealAm());
                }
                achieList.forEach(itmm -> {
                    if (itm.getPkMember().equals(itmm.getPkMember())) {
                        itm.setOrderAchieve(itmm.getOrderAchieve());
                        itm.setOrderAmount(itmm.getOrderAmount());
                        itm.setRegAmount(itmm.getRegAmount());
                        itm.setRegAchieve(itmm.getRegAchieve());
                        itm.setUpgAmount(itmm.getUpgAmount());
                        itm.setUpgAchieve(itmm.getUpgAchieve());
                        itm.setRepAmount(itmm.getRepAmount());
                        itm.setRepAchieve(itmm.getRepAchieve());
                        itm.setConAmount(itmm.getConAmount());
                        itm.setConAchieve(itmm.getConAchieve());
                    }
                });

                if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                    //中国业绩转为人民币
                    itm.setOrderAchieve(itm.getOrderAchieve().multiply(currency.getData().getInExchangeRate()));
                    itm.setRegAchieve(itm.getRegAchieve().multiply(currency.getData().getInExchangeRate()));
                    itm.setUpgAchieve(itm.getUpgAchieve().multiply(currency.getData().getInExchangeRate()));
                    itm.setRepAchieve(itm.getRepAchieve().multiply(currency.getData().getInExchangeRate()));
                    itm.setConAchieve(itm.getConAchieve().multiply(currency.getData().getInExchangeRate()));
                }
            });
        }
        ExcelUtil<DirectPushNewVo> util = new ExcelUtil<>(DirectPushNewVo.class);
        util.exportExcel(response, memberList, "伞下直推新增业绩导出");
    }

    /**
     * 伞下直推新增盒数大小区盒数
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_BOX, method = EOperationMethod.SELECT)
    @GetMapping("/direct-push-box")
    public TableDataInfo directPushBox(String memberCode, Integer pkCountry,
                                       Date startPayTime, Date endPayTime) {
        if (StringUtils.isNull(startPayTime) || StringUtils.isNull(endPayTime)) {
            return getDataTable(new ArrayList<>());
        }
        if (StringUtils.isEmpty(memberCode)) {
            return getDataTable(new ArrayList<>());
        }
        if (pkCountry == null) {
            pkCountry = SecurityUtils.getPkCountry();
        }

        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(startPayTime, date) > 0 || DateUtils.compareDate(endPayTime, date) > 0) {
            return getDataTable(new ArrayList<>());
        }
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, startPayTime));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        DirectPushBoxVo dpo = new DirectPushBoxVo();
        //查询会员是否激活
        Integer enableStatus = EYesNo.NO.getIntValue();
        if (date1.equals(date2) || (DateUtils.compareDate(endPayTime, date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            Date zonpayTime = DateUtils.afterDate(1, ChronoUnit.DAYS, endPayTime);
            dpo.setZonpayTime(zonpayTime);
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
            String dateNow = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
            dpo.setAchieveTableNameNow(TableNameConstants.CU_MEMBER_RETAIL_S + iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(dateNow).getPkId());
        }
        dpo.setEndPayTime(endPayTime);
        dpo.setStartPayTime(startPayTime);


        int periodSta = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr).getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();
        dpo.setPkCountry(pkCountry);
        //查询最新期数
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodEnd);
        dpo.setMemberRetailTable(TableNameConstants.CU_MEMBER_RETAIL_RANGE + periodEnd);
        if (StringUtils.isNotEmpty(dpo.getPayTime())) {
            //查询会员是否激活
            int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(dpo.getPayTime()).getPkId();
            dpo.setMemberRetailSTable(TableNameConstants.CU_MEMBER_RETAIL_S + period);
        }

        dpo.setEnableStatus(enableStatus);

        if (memberReportService.selectExistTable(dpo.getAchieveTableNameSta()) == 0 ||
                memberReportService.selectExistTable(dpo.getAchieveTableNameEnd()) == 0
        ) {
            return getDataTable(new ArrayList<>());
        }

        dpo.setMemberCode(memberCode);
        //查询会员
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(Arrays.asList(memberCode), pkCountry, startPayTime, endPayTime);
        if (CollectionUtil.isEmpty(memberList)) {
            return getDataTable(new ArrayList<>());
        }
        List<DirectPushBoxVo> boxVoList = new ArrayList<>();
        memberList.forEach(item -> boxVoList.add(BeanUtil.copyProperties(item, DirectPushBoxVo.class)));
        //查询会员是否激活
        List<DirectPushBoxVo> enableStatusList = memberReportService.selectMemberActiveState(dpo, Arrays.asList(memberList.get(0).getPkMember()));
        //伞下直推新增盒数
        List<DirectPushBoxVo> boxList = memberReportService.directPushNewBoxList(dpo, enableStatusList);
        //查询大小区盒数
        DirectPushBoxVo sizeZoneBox = memberReportService.sizeZoneBox(dpo, dpo.getMemberCode(), memberList.get(0).getPkMember());
        if (CollectionUtil.isNotEmpty(boxVoList)) {
            boxVoList.forEach(itm -> {
                if (CollectionUtil.isNotEmpty(boxList)) {
                    itm.setTotalBox(boxList.get(0).getTotalBox());
                }
                if (sizeZoneBox != null) {
                    itm.setBigAreaBox(sizeZoneBox.getBigAreaBox());
                    itm.setSmallAreaBox(sizeZoneBox.getSmallAreaBox());
                }
            });
        }
        return getDataTable(boxVoList);
    }


    /**
     * 导出伞下直推新增盒数大小区盒数
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_BOX, method = EOperationMethod.EXPORT)
    @PostMapping("export-direct-push-box")
    public void exportUp(HttpServletResponse response, DirectPushBoxVo dpo) {
        List<String> memberCodeList;
        if (StringUtils.isNotEmpty(dpo.getMemberCodeStr())) {
            memberCodeList = Arrays.asList(dpo.getMemberCodeStr().split(","));
            if (CollectionUtil.isNotEmpty(memberCodeList)) {
                dpo.setMemberCodeList(memberCodeList);
            }
        }

        if (StringUtils.isNull(dpo.getStartPayTime()) || StringUtils.isNull(dpo.getEndPayTime())) {
            return;
        }
        if (StringUtils.isEmpty(dpo.getMemberCodeStr())) {
            return;
        }
        dpo.setPkCountry(SecurityUtils.getPkCountry());
        Date date = DateUtils.currentDate();
        if (DateUtils.compareDate(dpo.getStartPayTime(), date) > 0 || DateUtils.compareDate(dpo.getEndPayTime(), date) > 0) {
            return;
        }
        String date1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        String date2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dpo.getEndPayTime());
        //开始时间减一天
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, dpo.getStartPayTime()));
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dpo.getEndPayTime());
        //查询会员是否激活
        Integer enableStatus = EYesNo.NO.getIntValue();
        //结束日期是否大于等于当前日期，大于等于则需要查询订单
        if (date1.equals(date2) || (DateUtils.compareDate(dpo.getEndPayTime(), date) >= 0)) {
            dpo.setPayTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
            Date zonpayTime = DateUtils.afterDate(1, ChronoUnit.DAYS, dpo.getEndPayTime());
            dpo.setZonpayTime(zonpayTime);
            String dateNow = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
            dpo.setAchieveTableNameNow(TableNameConstants.CU_MEMBER_RETAIL_S + iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(dateNow).getPkId());
        }

        int periodSta = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDateStr).getPkId();
        int periodEnd = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(endDateStr).getPkId();
        //查询最新期数
        dpo.setAchieveTableNameSta(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodSta);
        dpo.setAchieveTableNameEnd(TableNameConstants.CU_MEMBER_AMOUNT_BOX + periodEnd);
        dpo.setMemberRetailTable(TableNameConstants.CU_MEMBER_RETAIL_RANGE + periodEnd);
        if (StringUtils.isNotEmpty(dpo.getPayTime())) {
            //查询会员是否激活
            int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(dpo.getPayTime()).getPkId();
            dpo.setMemberRetailSTable(TableNameConstants.CU_MEMBER_RETAIL_S + period);
        }

        dpo.setEnableStatus(enableStatus);

        if (memberReportService.selectExistTable(dpo.getAchieveTableNameSta()) == 0 ||
                memberReportService.selectExistTable(dpo.getAchieveTableNameEnd()) == 0
        ) {
            return;
        }
        //伞下直推新增业绩
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(dpo.getMemberCodeList(), dpo.getPkCountry(),
                dpo.getStartPayTime(), dpo.getEndPayTime());
        List<Long> pkMemberList = new ArrayList<>();
        pkMemberList.addAll(memberList.stream().map(DirectPushNewVo::getPkMember).collect(Collectors.toList()));
        //查询会员是否激活
        List<DirectPushBoxVo> enableStatusList = memberReportService.selectMemberActiveState(dpo, pkMemberList);
        List<DirectPushBoxVo> boxVoList = new ArrayList<>();
        memberList.forEach(item -> boxVoList.add(BeanUtil.copyProperties(item, DirectPushBoxVo.class)));
        //伞下直推新增盒数
        List<DirectPushBoxVo> boxList = memberReportService.directPushNewBoxList(dpo, enableStatusList);
        if (CollectionUtil.isNotEmpty(boxVoList)) {
            boxVoList.forEach(itm -> {
                //查询大小区盒数
                DirectPushBoxVo sizeZoneBox = memberReportService.sizeZoneBox(dpo, itm.getMemberCode(), itm.getPkMember());
                if (sizeZoneBox != null) {
                    itm.setBigAreaBox(sizeZoneBox.getBigAreaBox());
                    itm.setSmallAreaBox(sizeZoneBox.getSmallAreaBox());
                }
                boxList.forEach(itmm -> {
                    if (itm.getPkMember().equals(itmm.getPkMember())) {
                        itm.setTotalBox(itmm.getTotalBox());
                    }
                });
            });
        }
        ExcelUtil<DirectPushBoxVo> util = new ExcelUtil<>(DirectPushBoxVo.class);
        util.exportExcel(response, boxVoList, "伞下直推新增盒数导出");
    }


    /**
     * 用户消费统计
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_CONSUMPTION, method = EOperationMethod.SELECT)
    @GetMapping("/member-consumption")
    public TableDataInfo memberConsumptionList(String memberCode, String memberName, Date startPayTime, Date endPayTime, Integer pkWares) {
        startPage();
        List<MemberConsumptionVo> memberReportList = memberReportService.memberConsumptionList(memberCode, memberName, startPayTime, endPayTime, pkWares);
        return getDataTable(memberReportList);
    }

    /**
     * 用户消费统计导出
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_CONSUMPTION, method = EOperationMethod.EXPORT)
    @PostMapping("/member-consumption-export")
    public void memberConsumptionListExport(MemberConsumptionParam memberConsumptionParam, HttpServletResponse response) {
        List<MemberConsumptionVo> memberReportList = memberReportService.memberConsumptionList(memberConsumptionParam.getMemberCode(), memberConsumptionParam.getMemberName(), memberConsumptionParam.getStartPayTime(), memberConsumptionParam.getEndPayTime(), memberConsumptionParam.getPkWares());
        ExcelUtil<MemberConsumptionVo> util = new ExcelUtil<>(MemberConsumptionVo.class);
        util.exportExcel(response, memberReportList, "用户消费统计导出");
    }


    /**
     * 伞下新增安置业绩 列表
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_RESETTLE_ACHIEVE, method = EOperationMethod.SELECT)
    @GetMapping("/member-resettle-achieve")
    public TableDataInfo memberResettleAchieve(String memberCode, String memberName, Date startPayTime, Date endPayTime, Integer pkVertex, Integer pkTeamCode, Integer orderType, Integer pkAwards) {
        if (startPayTime != null) {
            startPayTime = DateUtils.getStartTime(startPayTime);
        }
        if (endPayTime != null) {
            endPayTime = DateUtils.getEndTime(endPayTime);
        }
        R<CuMember> memberDto = iMemberServiceApi.getMember(memberCode);
        CuMember member = memberDto.getData();
        Integer pkCountry = null;
        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            pkCountry = SecurityUtils.getPkCountry();
        }

        if (member == null) {
            return getDataTable(new ArrayList<>());
        }
        R<CurrencyDTO> currencyDto = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        CurrencyDTO currency = currencyDto.getData();
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderType);

        List<MemberResettleAchieveVo> memberResettleAchieveList = memberReportService.memberResettleAchieve(member.getPkId(), memberName, startPayTime, endPayTime, pkVertex, pkTeamCode, pkCountry, pkAwards, orderTypeList);
        Map<Integer, MemberResettleAchieveVo> memberResettleAchieveMap = memberResettleAchieveList.stream().collect(Collectors.toMap(MemberResettleAchieveVo::getPlaceDept, Function.identity()));
        // 左区新增业绩

        BigDecimal leftNewAddAchieve = memberResettleAchieveMap.get(EPlaceDept.LEFT_DEPT.getValue()).getAchieve();
        // 右区新增业绩
        BigDecimal rightNewAddAchieve = memberResettleAchieveMap.get(EPlaceDept.RIGHT_DEPT.getValue()).getAchieve();

        // 左区新增金额
        BigDecimal leftNewAddAmount = memberResettleAchieveMap.get(EPlaceDept.LEFT_DEPT.getValue()).getAmount();
        // 右区新增金额
        BigDecimal rightNewAddAmount = memberResettleAchieveMap.get(EPlaceDept.RIGHT_DEPT.getValue()).getAmount();
        MemberResettleAchieveVo mr = memberResettleAchieveList.get(0);
        // 查询会员业绩
        MemberResettleAchieveVo memberResettleAchieveVo = new MemberResettleAchieveVo();
        memberResettleAchieveVo.setPkMember(member.getPkId());
        memberResettleAchieveVo.setNationalFlag(mr.getNationalFlag());
        memberResettleAchieveVo.setShortName(mr.getShortName());
        memberResettleAchieveVo.setMemberCode(mr.getMemberCode());
        memberResettleAchieveVo.setMemberName(mr.getMemberName());
        memberResettleAchieveVo.setPhone(mr.getPhone());
        memberResettleAchieveVo.setAwardsName(mr.getAwardsName());
        memberResettleAchieveVo.setVertexName(mr.getVertexName());
        memberResettleAchieveVo.setTeamCodeName(mr.getTeamCodeName());
        BigDecimal inExchangeRate = currency.getInExchangeRate();

        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            memberResettleAchieveVo.setLeftNewAddAmount(leftNewAddAmount);
            memberResettleAchieveVo.setRightNewAddAmount(rightNewAddAmount);
            memberResettleAchieveVo.setLeftNewAddAchieve(leftNewAddAchieve.multiply(inExchangeRate));
            memberResettleAchieveVo.setRightNewAddAchieve(rightNewAddAchieve.multiply(inExchangeRate));
        } else {
            memberResettleAchieveVo.setLeftNewAddAmount(leftNewAddAmount.divide(inExchangeRate, 2, BigDecimal.ROUND_HALF_UP));
            memberResettleAchieveVo.setRightNewAddAmount(rightNewAddAmount.divide(inExchangeRate, 2, BigDecimal.ROUND_HALF_UP));
            memberResettleAchieveVo.setLeftNewAddAchieve(leftNewAddAchieve);
            memberResettleAchieveVo.setRightNewAddAchieve(rightNewAddAchieve);
        }

        memberResettleAchieveVo.setOrderTime(mr.getOrderTime());

        return getDataTable(Collections.singletonList(memberResettleAchieveVo));
    }

    /**
     * 伞下新增安置业绩列表（历史）
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_RESETTLE_ACHIEVE, method = EOperationMethod.SELECT)
    @GetMapping("/member-resettle-achieve_up")
    public TableDataInfo memberResettleAchieveUp(String memberCode, String memberName, Date startPayTime,
                                                 Date endPayTime, Integer pkVertex, Integer pkTeamCode,
                                                 Integer orderType, Integer pkAwards) {
        if (startPayTime == null || endPayTime == null) {
            return getDataTable(new ArrayList<>());
        }
        Date date = new Date();
        String startDateStr = "";
        String endDateStr = "";
        if (DateUtils.compareDate(startPayTime, date) > 0) {
            startPayTime = date;
            startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startPayTime);
            startDateStr = DateUtils.beforeDateStr(2, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, startDateStr);
        } else {
            startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startPayTime);
            startDateStr = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, startDateStr);
        }
        if (DateUtils.compareDate(endPayTime, date) > 0) {
            endPayTime = date;
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
            endDateStr = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, endDateStr);
        } else {
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        }

        if (StringUtils.isEmpty(memberCode)) {
            return getDataTable(new ArrayList<>());
        }
        R<CuMemberExt> memberDto = iMemberServiceApi.getMemberByCode(memberCode);
        CuMember member = memberDto.getData();
        if (member == null) {
            return getDataTable(new ArrayList<>());
        }
        Integer pkCountry = SecurityUtils.getPkCountry();

        R<CurrencyDTO> currencyDto = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        CurrencyDTO currency = currencyDto.getData();

        List<MemberResettleAchieveVo> memberResettleAchieveList = new ArrayList<>();
        BigDecimal inExchangeRate = currency.getInExchangeRate();
        //查询最新期数
        int staPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(startDateStr)).getPkId();
        int endPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(endDateStr)).getPkId();
        String staAchieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(startDateStr);
        String endAchieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(endDateStr);
        List<MemberResettleAchieveVo> staAchieveList = memberReportService.selectBrollyNewABAchieve(member.getPkId(), memberName, startPayTime, endPayTime,
                pkVertex, pkTeamCode, pkCountry, pkAwards, staAchieveTableName, staPeriod);
        List<MemberResettleAchieveVo> endAchieveList = memberReportService.selectBrollyNewABAchieve(member.getPkId(), memberName, startPayTime, endPayTime,
                pkVertex, pkTeamCode, pkCountry, pkAwards, endAchieveTableName, endPeriod);
        if (CollectionUtil.isNotEmpty(staAchieveList) && CollectionUtil.isNotEmpty(endAchieveList)) {
            for (MemberResettleAchieveVo end : endAchieveList) {
                for (MemberResettleAchieveVo sta : staAchieveList) {
                    if (end.getPkMember().equals(sta.getPkMember())) {
                        end.setLeftNewAddAmount(end.getASumAmount().subtract(sta.getASumAmount()));
                        end.setRightNewAddAmount(end.getBSumAmount().subtract(sta.getBSumAmount()));
                        end.setLeftNewAddAchieve(end.getASumPv().subtract(sta.getASumPv()));
                        end.setRightNewAddAchieve(end.getBSumPv().subtract(sta.getBSumPv()));
                        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                            end.setLeftNewAddAmount(end.getLeftNewAddAmount().multiply(inExchangeRate));
                            end.setRightNewAddAmount(end.getRightNewAddAmount().multiply(inExchangeRate));
                            end.setLeftNewAddAchieve(end.getLeftNewAddAchieve().multiply(inExchangeRate));
                            end.setRightNewAddAchieve(end.getRightNewAddAchieve().multiply(inExchangeRate));
                        }
                    }
                }
                memberResettleAchieveList.add(end);
            }
        }

        return getDataTable(memberResettleAchieveList);
    }

    /**
     * 导出伞下新增安置业绩列表
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_RESETTLE_ACHIEVE, method = EOperationMethod.EXPORT)
    @PostMapping("/member-resettle-achieve_up_export")
    public void memberResettleAchieveUpExport(HttpServletResponse response, String memberCode, String memberName, Date startPayTime,
                                              Date endPayTime, Integer pkVertex, Integer pkTeamCode,
                                              Integer orderType, Integer pkAwards) {
        if (startPayTime == null || endPayTime == null) {
            return;
        }
        Date date = new Date();
        String startDateStr = "";
        String endDateStr = "";
        if (DateUtils.compareDate(startPayTime, date) > 0) {
            startPayTime = date;
            startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startPayTime);
            startDateStr = DateUtils.beforeDateStr(2, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, startDateStr);
        } else {
            startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startPayTime);
            startDateStr = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, startDateStr);
        }
        if (DateUtils.compareDate(endPayTime, date) > 0) {
            endPayTime = date;
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
            endDateStr = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, endDateStr);
        } else {
            endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endPayTime);
        }

        if (StringUtils.isEmpty(memberCode)) {
            return;
        }
        R<CuMemberExt> memberDto = iMemberServiceApi.getMemberByCode(memberCode);
        CuMember member = memberDto.getData();
        Integer pkCountry = null;
        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            pkCountry = SecurityUtils.getPkCountry();
        }

        if (member == null) {
            return;
        }
        R<CurrencyDTO> currencyDto = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        CurrencyDTO currency = currencyDto.getData();
        List<MemberResettleAchieveVo> memberResettleAchieveList = new ArrayList<>();
        BigDecimal inExchangeRate = currency.getInExchangeRate();
        //查询最新期数
        int staPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(startDateStr)).getPkId();
        int endPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                DateUtils.parseDateToStr(endDateStr)).getPkId();
        String staAchieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(startDateStr);

        String endAchieveTableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(endDateStr);
        List<MemberResettleAchieveVo> staAchieveList = memberReportService.selectBrollyNewABAchieve(member.getPkId(), memberName, startPayTime, endPayTime,
                pkVertex, pkTeamCode, pkCountry, pkAwards, staAchieveTableName, staPeriod);
        List<MemberResettleAchieveVo> endAchieveList = memberReportService.selectBrollyNewABAchieve(member.getPkId(), memberName, startPayTime, endPayTime,
                pkVertex, pkTeamCode, pkCountry, pkAwards, endAchieveTableName, endPeriod);
        if (CollectionUtil.isNotEmpty(staAchieveList) && CollectionUtil.isNotEmpty(endAchieveList)) {
            for (MemberResettleAchieveVo end : endAchieveList) {
                for (MemberResettleAchieveVo sta : staAchieveList) {
                    if (end.getPkMember().equals(sta.getPkMember())) {
                        end.setLeftNewAddAmount(end.getASumAmount().subtract(sta.getASumAmount()));
                        end.setRightNewAddAmount(end.getBSumAmount().subtract(sta.getBSumAmount()));
                        end.setLeftNewAddAchieve(end.getASumPv().subtract(sta.getASumPv()));
                        end.setRightNewAddAchieve(end.getBSumPv().subtract(sta.getBSumPv()));
                        if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                            end.setLeftNewAddAmount(end.getLeftNewAddAmount().multiply(inExchangeRate));
                            end.setRightNewAddAmount(end.getRightNewAddAmount().multiply(inExchangeRate));
                            end.setLeftNewAddAchieve(end.getLeftNewAddAchieve().multiply(inExchangeRate));
                            end.setRightNewAddAchieve(end.getRightNewAddAchieve().multiply(inExchangeRate));
                        }
                    }
                }
                memberResettleAchieveList.add(end);
            }
        }
        ExcelUtil<MemberResettleAchieveVo> util = new ExcelUtil<>(MemberResettleAchieveVo.class);
        util.exportExcel(response, memberResettleAchieveList, "伞下新增安置业绩导出");
    }

    /**
     * 伞下新增安置业绩导出
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_RESETTLE_ACHIEVE, method = EOperationMethod.EXPORT)
    @PostMapping("/member-resettle-achieve-export")
    public void memberResettleAchieveExport(MemberResettleAchieveParam memberResettleAchieveParam, HttpServletResponse response) {
        if (memberResettleAchieveParam.getStartPayTime() != null) {
            memberResettleAchieveParam.setStartPayTime(DateUtils.getStartTime(memberResettleAchieveParam.getStartPayTime()));
        }
        if (memberResettleAchieveParam.getEndPayTime() != null) {
            memberResettleAchieveParam.setEndPayTime(DateUtils.getEndTime(memberResettleAchieveParam.getEndPayTime()));
        }
        R<CuMember> memberDto = iMemberServiceApi.getMember(memberResettleAchieveParam.getMemberCode());
        CuMember member = memberDto.getData();
        if (member == null) {
            ExcelUtil<MemberResettleAchieveVo> util = new ExcelUtil<>(MemberResettleAchieveVo.class);
            util.exportExcel(response, Collections.singletonList(new MemberResettleAchieveVo()), "伞下新增安置业绩导出");
        } else {
            if (memberResettleAchieveParam.getStartPayTime() != null) {
                memberResettleAchieveParam.setStartPayTime(DateUtils.getStartTime(memberResettleAchieveParam.getStartPayTime()));
            }
            if (memberResettleAchieveParam.getEndPayTime() != null) {
                memberResettleAchieveParam.setEndPayTime(DateUtils.getEndTime(memberResettleAchieveParam.getEndPayTime()));
            }

            Integer pkCountry = null;
            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                pkCountry = SecurityUtils.getPkCountry();
            }
            R<CurrencyDTO> currencyDto = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            CurrencyDTO currency = currencyDto.getData();
            List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(memberResettleAchieveParam.getOrderType());

            List<MemberResettleAchieveVo> memberResettleAchieveList = memberReportService.memberResettleAchieve(member.getPkId(), memberResettleAchieveParam.getMemberName(), memberResettleAchieveParam.getStartPayTime(), memberResettleAchieveParam.getEndPayTime(), memberResettleAchieveParam.getPkVertex(), memberResettleAchieveParam.getPkTeamCode(), pkCountry, memberResettleAchieveParam.getPkAwards(), orderTypeList);
            Map<Integer, MemberResettleAchieveVo> memberResettleAchieveMap = memberResettleAchieveList.stream().collect(Collectors.toMap(MemberResettleAchieveVo::getPlaceDept, Function.identity()));
            // 左区新增业绩

            BigDecimal leftNewAddAchieve = memberResettleAchieveMap.get(EPlaceDept.LEFT_DEPT.getValue()).getAchieve();
            // 右区新增业绩
            BigDecimal rightNewAddAchieve = memberResettleAchieveMap.get(EPlaceDept.RIGHT_DEPT.getValue()).getAchieve();

            // 左区新增金额
            BigDecimal leftNewAddAmount = memberResettleAchieveMap.get(EPlaceDept.LEFT_DEPT.getValue()).getAmount();
            // 右区新增金额
            BigDecimal rightNewAddAmount = memberResettleAchieveMap.get(EPlaceDept.RIGHT_DEPT.getValue()).getAmount();
            MemberResettleAchieveVo mr = memberResettleAchieveList.get(0);
            // 查询会员业绩
            MemberResettleAchieveVo memberResettleAchieveVo = new MemberResettleAchieveVo();
            memberResettleAchieveVo.setPkMember(member.getPkId());
            memberResettleAchieveVo.setNationalFlag(mr.getNationalFlag());
            memberResettleAchieveVo.setShortName(mr.getShortName());
            memberResettleAchieveVo.setMemberCode(mr.getMemberCode());
            memberResettleAchieveVo.setMemberName(mr.getMemberName());
            memberResettleAchieveVo.setPhone(mr.getPhone());
            memberResettleAchieveVo.setAwardsName(mr.getAwardsName());
            memberResettleAchieveVo.setVertexName(mr.getVertexName());
            memberResettleAchieveVo.setTeamCodeName(mr.getTeamCodeName());
            BigDecimal inExchangeRate = currency.getInExchangeRate();
            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                memberResettleAchieveVo.setLeftNewAddAmount(leftNewAddAmount);
                memberResettleAchieveVo.setRightNewAddAmount(rightNewAddAmount);
                memberResettleAchieveVo.setLeftNewAddAchieve(leftNewAddAchieve.multiply(inExchangeRate));
                memberResettleAchieveVo.setRightNewAddAchieve(rightNewAddAchieve.multiply(inExchangeRate));
            } else {
                memberResettleAchieveVo.setLeftNewAddAmount(leftNewAddAmount.divide(inExchangeRate, 2, BigDecimal.ROUND_HALF_UP));
                memberResettleAchieveVo.setRightNewAddAmount(rightNewAddAmount.divide(inExchangeRate, 2, BigDecimal.ROUND_HALF_UP));
                memberResettleAchieveVo.setLeftNewAddAchieve(leftNewAddAchieve);
                memberResettleAchieveVo.setRightNewAddAchieve(rightNewAddAchieve);
            }
            memberResettleAchieveVo.setOrderTime(mr.getOrderTime());
            ExcelUtil<MemberResettleAchieveVo> util = new ExcelUtil<>(MemberResettleAchieveVo.class);
            util.exportExcel(response, Collections.singletonList(memberResettleAchieveVo), "伞下新增安置业绩导出");
        }

    }

    /**
     * 订单币种查询
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.ORDER_CURRENCY_LIST, method = EOperationMethod.SELECT)
    @GetMapping("/order-currency-list")
    public TableDataInfo orderCurrencyList(String memberCode, String memberName, String orderCode, Integer orderType) {
        if (StringUtils.isBlank(memberCode)) {
            return getDataTable(new ArrayList<>());
        }
        startPage();
        List<OrderCurrencyVo> memberResettleAchieveList = memberReportService.getOrderCurrencyList(memberCode, memberName, orderCode, orderType);
        List<String> orderCodeList = memberResettleAchieveList.stream().map(OrderCurrencyVo::getOrderCode).collect(Collectors.toList());
        List<MemberTradeVo> memberTradeVoList = new ArrayList<>();
        if (orderCodeList.size() > 0) {
            memberTradeVoList = memberReportService.getBySourceCodeMemberTradeList(orderCodeList);
        }

        for (OrderCurrencyVo orderCurrencyVo : memberResettleAchieveList) {
            // 现金
            BigDecimal cashAccount = BigDecimal.ZERO;
            // 奖金
            BigDecimal bonusAccount = BigDecimal.ZERO;
            // 消费
            BigDecimal expendAccount = BigDecimal.ZERO;
            // 政策
            BigDecimal policyAccount = BigDecimal.ZERO;
            // 积分账户
            BigDecimal integralAccount = BigDecimal.ZERO;
            EOrderType enumByValue = EOrderType.getEnumByValue(orderCurrencyVo.getOrderType());
            if (enumByValue != null) {
                orderCurrencyVo.setOrderTypeStr(enumByValue.getLabel());
            }
            for (MemberTradeVo memberTradeVo : memberTradeVoList) {
                if (orderCurrencyVo.getOrderCode().equals(memberTradeVo.getSourceCode())) {
                    if (memberTradeVo.getPkAccount().equals(EAccount.CASH.getValue())) {
                        // 现金
                        cashAccount = cashAccount.add(memberTradeVo.getTradeAmount());
                    }
                    if (memberTradeVo.getPkAccount().equals(EAccount.BONUS.getValue())) {
                        // 奖金
                        bonusAccount = bonusAccount.add(memberTradeVo.getTradeAmount());
                    }
                    if (memberTradeVo.getPkAccount().equals(EAccount.CONSUME.getValue())) {
                        // 消费
                        expendAccount = expendAccount.add(memberTradeVo.getTradeAmount());
                    }
                    if (memberTradeVo.getPkAccount().equals(EAccount.POLICY.getValue())) {
                        // 政策
                        policyAccount = policyAccount.add(memberTradeVo.getTradeAmount());
                    }
                    if (memberTradeVo.getPkAccount().equals(EAccount.INTEGRAL.getValue())) {
                        // 积分
                        integralAccount = integralAccount.add(memberTradeVo.getTradeAmount());
                    }
                }
                orderCurrencyVo.setCashAccount(cashAccount);
                orderCurrencyVo.setBonusAccount(bonusAccount);
                orderCurrencyVo.setExpendAccount(expendAccount);
                orderCurrencyVo.setPolicyAccount(policyAccount);
                orderCurrencyVo.setIntegralAccount(integralAccount);
            }
        }
        return getDataTable(memberResettleAchieveList);
    }

    /**
     * 订单分布统计
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.GET_ORDER_DISTRIBUTION, method = EOperationMethod.SELECT)
    @GetMapping("/get-order-distribution")
    public TableDataInfo getOrderDistribution(Integer area, Date startTime, Date endTime) {
        // area 1=省 2=市 3=区
        if (area == null) {
            return getDataTable(new ArrayList<>());
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<OrderDistribution> orderDistributionList = new ArrayList<>();
        startPage();
        if (area == 1) {
            // 查询省
            orderDistributionList = memberReportService.getByProvinceOrderDistribution(startTime, endTime, pkCountry);
        } else if (area == 2) {
            // 查询市
            orderDistributionList = memberReportService.getByCityOrderDistribution(startTime, endTime, pkCountry);
        } else if (area == 3) {
            // 查询区县
            orderDistributionList = memberReportService.getByDistrictOrderDistribution(startTime, endTime, pkCountry);
        }

        return getDataTable(orderDistributionList);
    }
//
//    /**
//     * 出货明细汇总统计
//     */
//    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING_DETAILS_LIST, method = EOperationMethod.SELECT)
//    @GetMapping("/product-shipping-details-list")
//    public TableDataInfo productShippingDetailsList(String productName, Integer pkClassify, Date startTime, Date endTime, Integer orderType) {
//        startPage();
//        Integer pkCountry = SecurityUtils.getPkCountry();
//        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderType);
//        if (endTime != null) {
//            endTime = DateUtils.getEndTime(endTime);
//        }
//        List<ProductOrderInfoVo> memberReportList = memberReportService.getProductOrderInfo(productName, pkClassify, startTime, endTime, pkCountry, orderTypeList);
//        for (ProductOrderInfoVo productOrderInfoVo : memberReportList) {
//            if (productOrderInfoVo.getProductPrice() != null) {
//                productOrderInfoVo.setProductTotalPrice(productOrderInfoVo.getProductPrice());
//            } else {
//                productOrderInfoVo.setProductTotalPrice(BigDecimal.ZERO);
//            }
//
//            if (productOrderInfoVo.getOrderType() != null) {
//                productOrderInfoVo.setOrderTypeStr(EOrderType.getEnumByValue(productOrderInfoVo.getOrderType()).getLabel());
//            }
//        }
//        // 计算总计
//        Integer count = memberReportService.sumQuantity(productName, pkClassify, startTime, endTime, pkCountry, orderTypeList);
//        ProductOrderInfoVo productOrderInfoVo = new ProductOrderInfoVo();
//        productOrderInfoVo.setProductCode("总计");
//        productOrderInfoVo.setProductName("-");
//        productOrderInfoVo.setQuantity(count);
//        productOrderInfoVo.setProductTotalPrice(BigDecimal.ZERO);
//        memberReportList.add(productOrderInfoVo);
//        return getDataTable(memberReportList);
//    }
//
//    /**
//     * 出货明细汇总导出
//     *
//     * @return
//     */
//    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING_DETAILS_LIST, method = EOperationMethod.EXPORT)
//    @PostMapping("/product-shipping-details-export")
//    public void productShippingDetailsExport(String productName, Integer pkClassify, Date startTime, Date endTime, Integer orderType, HttpServletResponse response) {
//        Integer pkCountry = SecurityUtils.getPkCountry();
//        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderType);
//        if (endTime != null) {
//            endTime = DateUtils.getEndTime(endTime);
//        }
//        List<ProductOrderInfoVo> memberReportList = memberReportService.getProductOrderInfo(productName, pkClassify, startTime, endTime, pkCountry, orderTypeList);
//        for (ProductOrderInfoVo productOrderInfoVo : memberReportList) {
//            if (productOrderInfoVo.getProductPrice() != null) {
//                productOrderInfoVo.setProductTotalPrice(productOrderInfoVo.getProductPrice());
//            } else {
//                productOrderInfoVo.setProductTotalPrice(BigDecimal.ZERO);
//            }
//            if (productOrderInfoVo.getOrderType() != null) {
//                productOrderInfoVo.setOrderTypeStr(EOrderType.getEnumByValue(productOrderInfoVo.getOrderType()).getLabel());
//            }
//        }
//        ExcelUtil<ProductOrderInfoVo> util = new ExcelUtil<>(ProductOrderInfoVo.class);
//        util.exportExcel(response, memberReportList, "出货明细汇总导出");
//    }

    /**
     * 出货明细汇总统计详情
     *
     * @param productName
     * @param pkProduct
     * @return
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING_DETAILS_INFO_LIST, method = EOperationMethod.SELECT)
    @GetMapping("/product-shipping-details-info-list")
    public TableDataInfo productShippingDetailsList(String productName, Integer pkProduct, Integer pkClassify, Integer pkAwards, Integer orderType, Date startTime, Date endTime) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<Integer> orderTypeList = new ArrayList<>();
        orderTypeList.add(orderType);
        if (endTime != null) {
            endTime = DateUtils.getEndTime(endTime);
        }
        List<ProductShippingDetailsInfoVo> productOrderInfoVoList = memberReportService.productShippingDetailsList(pkProduct, productName, pkClassify, pkAwards, orderTypeList, startTime, endTime, pkCountry);
        for (ProductShippingDetailsInfoVo productShippingDetailsInfoVo : productOrderInfoVoList) {
            productShippingDetailsInfoVo.setAwardsPrice(productShippingDetailsInfoVo.getPrice());
            productShippingDetailsInfoVo.setPriceTotal(productShippingDetailsInfoVo.getPrice().multiply(BigDecimal.valueOf(productShippingDetailsInfoVo.getQuantity())));
        }
        return getDataTable(productOrderInfoVoList);
    }

    /**
     * 出货明细汇总统计详情导出
     *
     * @param
     * @param
     * @return
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING_DETAILS_INFO_LIST, method = EOperationMethod.EXPORT)
    @PostMapping("/product-shipping-details-info-list-export")
    public void productShippingDetailsListExport(ProductShippingDetailsParam productShippingDetailsParam, HttpServletResponse response) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<Integer> orderTypeList = new ArrayList<>();
        orderTypeList.add(productShippingDetailsParam.getOrderType());
        if (productShippingDetailsParam.getEndTime() != null) {
            productShippingDetailsParam.setEndTime(productShippingDetailsParam.getEndTime());
        }
        List<ProductShippingDetailsInfoVo> productOrderInfoVoList = memberReportService.productShippingDetailsList(productShippingDetailsParam.getPkProduct(), productShippingDetailsParam.getProductName(), productShippingDetailsParam.getPkClassify(), productShippingDetailsParam.getPkAwards(), orderTypeList, productShippingDetailsParam.getStartTime(), productShippingDetailsParam.getEndTime(), pkCountry);
        for (ProductShippingDetailsInfoVo productShippingDetailsInfoVo : productOrderInfoVoList) {
            productShippingDetailsInfoVo.setAwardsPrice(productShippingDetailsInfoVo.getPrice());
            productShippingDetailsInfoVo.setPriceTotal(productShippingDetailsInfoVo.getPrice().multiply(BigDecimal.valueOf(productShippingDetailsInfoVo.getQuantity())));
        }
        ExcelUtil<ProductShippingDetailsInfoVo> util = new ExcelUtil<>(ProductShippingDetailsInfoVo.class);
        util.exportExcel(response, productOrderInfoVoList, "出货明细汇总统计详情");
    }

    /**
     * 报单汇总
     *
     * @return
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REPORT_SUMMARY_LIST, method = EOperationMethod.SELECT)
    @GetMapping("/report-summary-list")
    public TableDataInfo reportSummaryList(ReportSummaryVo reportSummaryVo) {
        if (null != reportSummaryVo.getEndCreateTime()) {
            // 补全23:59:59
            reportSummaryVo.setEndCreateTime(DateUtils.getEndTime(reportSummaryVo.getEndCreateTime()));
        }
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        startPage();
        reportSummaryVo.setPkCountry(SecurityUtils.getPkCountry());
        List<ReportSummaryVo> reportSummaryList = memberReportService.reportSummaryList(reportSummaryVo);
        for (ReportSummaryVo summaryVo : reportSummaryList) {
            if (summaryVo.getRegisterAuthority() != null) {
                summaryVo.setRegisterName(ERegistrationAuthority.getEnumByValue(summaryVo.getRegisterAuthority()).getLabel());
            }
            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                summaryVo.setConsumeAchieve(summaryVo.getConsumeAchieve().multiply(currency.getData().getInExchangeRate()));
            } else {
                summaryVo.setConsumeAchieve(summaryVo.getConsumeAchieve());
            }

        }
        return getDataTable(reportSummaryList);
    }

    /**
     * 报单汇总
     *
     * @return
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.REPORT_SUMMARY_LIST, method = EOperationMethod.EXPORT)
    @PostMapping("/report-summary-list-export")
    public void reportSummaryListExport(ReportSummaryVo reportSummaryVo, HttpServletResponse response) {
        if (null != reportSummaryVo.getEndCreateTime()) {
            // 补全23:59:59
            reportSummaryVo.setEndCreateTime(DateUtils.getEndTime(reportSummaryVo.getEndCreateTime()));
        }
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        reportSummaryVo.setPkCountry(SecurityUtils.getPkCountry());
        List<ReportSummaryVo> reportSummaryList = memberReportService.reportSummaryList(reportSummaryVo);
        for (ReportSummaryVo summaryVo : reportSummaryList) {
            if (summaryVo.getRegisterAuthority() != null) {
                summaryVo.setRegisterName(ERegistrationAuthority.getEnumByValue(summaryVo.getRegisterAuthority()).getLabel());
            }
            if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                summaryVo.setConsumeAchieve(summaryVo.getConsumeAchieve().multiply(currency.getData().getInExchangeRate()));
            } else {
                summaryVo.setConsumeAchieve(summaryVo.getConsumeAchieve());
            }
        }
        ExcelUtil<ReportSummaryVo> util = new ExcelUtil<>(ReportSummaryVo.class);
        util.exportExcel(response, reportSummaryList, "报单汇总导出");
    }

    /**
     * 推荐反查
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PARENT_PEG, method = EOperationMethod.SELECT)
    @PostMapping("/parent-peg")
    public TableDataInfo memberParentPeg(@RequestBody CuMemberUmbrellaParam cuMemberUmbrellaParam) {
        List<CuMemberPushAchieveVO> cuMemberPushAchieveVOList = new ArrayList<>();
        if (StringUtils.isNotEmpty(cuMemberUmbrellaParam.getMemberCode())) {
            startPage();
            List<CuMemberAchieveExt> cuMemberAchieveExtList = iMemberService.queryParentCuMemberAchieveExt(cuMemberUmbrellaParam);
            for (CuMemberAchieveExt cuMemberAchieveExt : cuMemberAchieveExtList) {
                CuMemberPushAchieveVO vo = BeanUtil.copyProperties(cuMemberAchieveExt, CuMemberPushAchieveVO.class);
                cuMemberPushAchieveVOList.add(vo);
            }
            TableDataInfo tableDataInfo = getDataTable(cuMemberAchieveExtList);
            tableDataInfo.setRows(cuMemberPushAchieveVOList);
            return tableDataInfo;
        }
        return getDataTable(cuMemberPushAchieveVOList);
    }

    /**
     * 导出推荐反查
     **/
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PARENT_PEG, method = EOperationMethod.EXPORT)
    @PostMapping("/export-parent-peg")
    public void exportParentPeg(HttpServletResponse response, CuMemberUmbrellaParam cuMemberUmbrellaParam) {
        List<CuMemberPushAchieveVO> cuMemberPushAchieveVOList = new ArrayList<>();

        if (StringUtils.isNotEmpty(cuMemberUmbrellaParam.getMemberCode())) {
            List<CuMemberAchieveExt> cuMemberAchieveExtList = iMemberService.queryParentCuMemberAchieveExt(cuMemberUmbrellaParam);
            if (CollectionUtil.isNotEmpty(cuMemberAchieveExtList)) {
                for (CuMemberAchieveExt cuMemberAchieveExt : cuMemberAchieveExtList) {
                    CuMemberPushAchieveVO vo = BeanUtil.copyProperties(cuMemberAchieveExt, CuMemberPushAchieveVO.class);
                    vo.setCategoryVal(ECategory.getLableByValue(cuMemberAchieveExt.getCategory()));
                    cuMemberPushAchieveVOList.add(vo);
                }
            }
        }
        ExcelUtil<CuMemberPushAchieveVO> util = new ExcelUtil<>(CuMemberPushAchieveVO.class);
        util.exportExcel(response, cuMemberPushAchieveVOList, "推荐反查");
    }

    /**
     * 产品明细查询
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_DETAIL_QUERY_LIST, method = EOperationMethod.SELECT)
    @GetMapping("/product-detail-query-list")
    public TableDataInfo productDetailQuery(ProductDetailQueryParam productDetailQueryParam) {
        if (productDetailQueryParam.getStartPayTime() != null) {
            productDetailQueryParam.setStartPayTime(DateUtils.getStartTime(productDetailQueryParam.getStartPayTime()));
        }
        if (productDetailQueryParam.getEndPayTime() != null) {
            productDetailQueryParam.setEndPayTime(DateUtils.getEndTime(productDetailQueryParam.getEndPayTime()));
        }

        R<Map<Integer, String>> areaMap = iAreaServiceApi.getAreaMap(SecurityUtils.getPkCountry());
        Map<Integer, String> map = areaMap.getData();
        startPage();
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(productDetailQueryParam.getOrderType());
        productDetailQueryParam.setOrderTypeList(orderTypeList);
        productDetailQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        List<ProductDetailQueryVo> productDetailList = memberReportService.productDetailQueryList(productDetailQueryParam);
        for (ProductDetailQueryVo productDetailQueryVo : productDetailList) {
            if (productDetailQueryVo.getPayType() != null) {
                EPayType payType = EPayType.getEnumByValue(productDetailQueryVo.getPayType());
                // 支付类型
                if (payType != null) {
                    productDetailQueryVo.setPayTypeStr(payType.getLabel());
                }
            }
            if (productDetailQueryVo.getOrderType() != null) {
                EOrderType orderType = EOrderType.getEnumByValue(productDetailQueryVo.getOrderType());
                // 订单类型
                if (orderType != null) {
                    productDetailQueryVo.setOrderTypeVal(orderType.getLabel());
                }
            }
            // 发货方式
            if (productDetailQueryVo.getDeliveryWay() != null) {
                EDelivery delivery = EDelivery.getDelivery(productDetailQueryVo.getDeliveryWay());
                if (delivery != null) {
                    productDetailQueryVo.setDeliveryWayVal(delivery.getLabel());
                }
            }
            productDetailQueryVo.setRecProvinceVal(map.get(productDetailQueryVo.getRecProvince()));
            productDetailQueryVo.setRecCityVal(map.get(productDetailQueryVo.getRecCity()));
            productDetailQueryVo.setRecCountyVal(map.get(productDetailQueryVo.getRecCounty()));

            // 产品名称
            productDetailQueryVo.setProductName(productDetailQueryVo.getProductName());
            // 产品总价
            productDetailQueryVo.setPriceTotal(productDetailQueryVo.getPrice().multiply(BigDecimal.valueOf(productDetailQueryVo.getQuantity())));
            // 订单编号
            productDetailQueryVo.setOrderCode(productDetailQueryVo.getOrderCode());
            // 创建日期
            productDetailQueryVo.setCreateTime(productDetailQueryVo.getCreateTime());
        }
        return getDataTable(productDetailList);
    }

    /**
     * 产品明细查询导出
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_DETAIL_QUERY_LIST, method = EOperationMethod.EXPORT)
    @PostMapping("/product-detail-query-list-export")
    public void productDetailQueryExport(ProductDetailQueryParam productDetailQueryParam, HttpServletResponse response) {
        R<Map<Integer, String>> areaMap = iAreaServiceApi.getAreaMap(SecurityUtils.getPkCountry());
        Map<Integer, String> map = areaMap.getData();
        if (productDetailQueryParam.getStartPayTime() != null) {
            productDetailQueryParam.setStartPayTime(DateUtils.getStartTime(productDetailQueryParam.getStartPayTime()));
        }
        if (productDetailQueryParam.getEndPayTime() != null) {
            productDetailQueryParam.setEndPayTime(DateUtils.getEndTime(productDetailQueryParam.getEndPayTime()));
        }
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(productDetailQueryParam.getOrderType());
        productDetailQueryParam.setOrderTypeList(orderTypeList);
        productDetailQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        List<ProductDetailQueryVo> productDetailList = memberReportService.productDetailQueryList(productDetailQueryParam);
        for (ProductDetailQueryVo productDetailQueryVo : productDetailList) {
            if (productDetailQueryVo.getPayType() != null) {
                EPayType payType = EPayType.getEnumByValue(productDetailQueryVo.getPayType());
                // 支付类型
                if (payType != null) {
                    productDetailQueryVo.setPayTypeStr(payType.getLabel());
                }
            }
            if (productDetailQueryVo.getOrderType() != null) {
                EOrderType orderType = EOrderType.getEnumByValue(productDetailQueryVo.getOrderType());
                // 订单类型
                if (orderType != null) {
                    productDetailQueryVo.setOrderTypeVal(orderType.getLabel());
                }
            }
            // 发货方式
            if (productDetailQueryVo.getDeliveryWay() != null) {
                EDelivery delivery = EDelivery.getDelivery(productDetailQueryVo.getDeliveryWay());
                if (delivery != null) {
                    productDetailQueryVo.setDeliveryWayVal(delivery.getLabel());
                }
            }
            productDetailQueryVo.setRecProvinceVal(map.get(productDetailQueryVo.getRecProvince()));
            productDetailQueryVo.setRecCityVal(map.get(productDetailQueryVo.getRecCity()));
            productDetailQueryVo.setRecCountyVal(map.get(productDetailQueryVo.getRecCounty()));

            // 产品名称
            productDetailQueryVo.setProductName(productDetailQueryVo.getProductName());
            // 产品总价
            productDetailQueryVo.setPriceTotal(productDetailQueryVo.getPrice().multiply(BigDecimal.valueOf(productDetailQueryVo.getQuantity())));
            // 订单编号
            productDetailQueryVo.setOrderCode(productDetailQueryVo.getOrderCode());
            // 创建日期
            productDetailQueryVo.setCreateTime(productDetailQueryVo.getCreateTime());
        }
        ExcelUtil<ProductDetailQueryVo> util = new ExcelUtil<>(ProductDetailQueryVo.class);
        util.exportExcel(response, productDetailList, "产品明细查询");
    }

    /**
     * 下载模板
     *
     * @param response
     * @param
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.DIRECT_PUSH_NEW, method = EOperationMethod.DOWNLOAD)
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        List<CuMemberImportVO> list = new ArrayList<>();
        ExcelUtil<CuMemberImportVO> util = new ExcelUtil<>(CuMemberImportVO.class);
        util.exportExcel(response, list, "会员编号");
    }

    /**
     * 手动统计会员直推金额业绩盒数数据
     **/
    @GetMapping("/staAmountBox")
    public AjaxResult staAmountBox(String staDate, String endDate) {
        memberReportService.repeatPushAmountBoxmethod(staDate, endDate);
        return AjaxResult.success();
    }

    /**
     * 初始化数据会员直推金额业绩盒数数据
     **/
    @GetMapping("/initial")
    public AjaxResult initial(String staDate, String endDate) {
        memberReportService.washMemberAmountBox(staDate, endDate);
        return AjaxResult.success();
    }


    /**
     * 产品销售统计列表
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING, method = EOperationMethod.SELECT)
    @GetMapping("/product-shipping")
    public TableDataInfo productShipping(ProductShippingParam param) {
        startPage();
        List<ProductShippingVO> productShippingList = memberReportService.listProductShipping(param);
        return getDataTable(productShippingList);
    }

    /**
     * 产品销售统计导出
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING, method = EOperationMethod.EXPORT)
    @PostMapping("/product-shipping-export")
    public void productShippingExport(HttpServletResponse response, ProductShippingParam param) {
        List<ProductShippingVO> productShippingList = memberReportService.listProductShipping(param);
        ExcelUtil<ProductShippingVO> util = new ExcelUtil<>(ProductShippingVO.class);
        util.exportExcel(response, productShippingList, "出货明细汇总导出");
    }

    /**
     * 产品销售统计详情
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING_DETAILS, method = EOperationMethod.SELECT)
    @GetMapping("/product-shipping-details")
    public TableDataInfo productShippingDetails(ProductShippingParam param) {
        startPage();
        List<ProductShippingDetailsVO> productOrderInfoVoList = memberReportService.listProductShippingDetail(param);
        if (CollectionUtil.isNotEmpty(productOrderInfoVoList)) {
            for (ProductShippingDetailsVO productShippingDetailsVO : productOrderInfoVoList) {
                productShippingDetailsVO.setSpecialAreaVal(ESpecialArea.getLabelByValue(productShippingDetailsVO.getSpecialArea()));
                productShippingDetailsVO.setIsMakerGiftVal(EWaresType.getEnumLabelByValue(productShippingDetailsVO.getIsMakerGift()));
            }
        }
        return getDataTable(productOrderInfoVoList);
    }

    /**
     * 产品销售统计详情导出
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.PRODUCT_SHIPPING_DETAILS, method = EOperationMethod.EXPORT)
    @PostMapping("/product-shipping-details-export")
    public void productShippingDetailsExport(HttpServletResponse response, ProductShippingParam param) {
        List<ProductShippingDetailsVO> productOrderInfoVoList = memberReportService.listProductShippingDetail(param);
        if (CollectionUtil.isNotEmpty(productOrderInfoVoList)) {
            for (ProductShippingDetailsVO productShippingDetailsVO : productOrderInfoVoList) {
                productShippingDetailsVO.setSpecialAreaVal(ESpecialArea.getLabelByValue(productShippingDetailsVO.getSpecialArea()));
                productShippingDetailsVO.setIsMakerGiftVal(EWaresType.getEnumLabelByValue(productShippingDetailsVO.getIsMakerGift()));
            }
        }
        ExcelUtil<ProductShippingDetailsVO> util = new ExcelUtil<>(ProductShippingDetailsVO.class);
        util.exportExcel(response, productOrderInfoVoList, "出货明细汇总统计详情");
    }
}
