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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
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.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.common.service.ITransactionCommonService;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.report.member.service.IMemberService;
import com.hzs.report.member.service.MemberReportService;
import com.hzs.report.member.param.CuMemberUmbrellaParam;
import com.hzs.report.member.vo.*;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: hzs_cloud
 * @BelongsPackage: com.hzs.report.member.controller
 * @Author: yh
 * @CreateTime: 2023-08-26  09:40
 * @Description: TODO
 * @Version: 1.0
 */
@RequestMapping("/manager/member-report")
@RestController
public class MemberReportController extends BaseController {

    @Autowired
    private MemberReportService memberReportService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private IMemberService memberService;

    @DubboReference
    IGradeServiceApi gradeServiceApi;
    @DubboReference
    IMemberServiceApi memberServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    /**
     * 伞下直推新增业绩
     *
     * @return
     */
    @GetMapping("/direct-push-new")
    public TableDataInfo directPushNew(String memberCode, String memberName,
                                       Integer pkAwards, Integer pkTeamCode, Integer pkCountry,
                                       Date startPayTime, Date endPayTime, Integer pkVertex,
                                       Integer orderType, Integer pushMethods) {

        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderType);
        Long pkMember = null;
        pkCountry = SecurityUtils.getPkCountry();
        if (pkCountry == CountryConstants.CHINA_COUNTRY) {
            pkCountry = null;
        }

        if (StringUtils.isNotBlank(memberCode)) {
            R<CuMember> memberDto = memberServiceApi.getMember(memberCode);
            CuMember member = memberDto.getData();
            if (null != member) {
                pkMember = member.getPkId();
            } else {
                return getDataTable(new ArrayList<>());
            }
        } else {
            return getDataTable(new ArrayList<>());
        }
        Date date = DateUtils.currentDate();
        if (StringUtils.isNull(startPayTime) ||
                StringUtils.isNull(endPayTime)) {
            //当前月的第一天
            startPayTime = DateUtils.currentMonthFirstDate();
            endPayTime = date;
        }
        //伞下直推新增业绩
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(pkMember, memberName, pkAwards, pkTeamCode, pkCountry, startPayTime, endPayTime, pkVertex);
        startPayTime = DateUtils.getStartTime(startPayTime);
        endPayTime = DateUtils.getEndTime(endPayTime);
        List<DirectPushNewVo> achieList;
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        if (pushMethods != null && pushMethods == EDirectPushMode.UMBRELLA_PUSH.getValue()) {
            achieList = memberReportService.directPushNewAchieList(pkMember, startPayTime, endPayTime, orderTypeList, pkCountry);
        } else {
            achieList = memberReportService.personDirectPushAchieList(pkMember, startPayTime, endPayTime, orderTypeList, pkCountry);
        }
        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                if (null != achieList.get(0)) {
                    if (SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
                        //当前国家汇率
                        R<CurrencyDTO> currencyLocal = currencyServiceApi.getCurrency(itm.getPkCountry());
                        //中国业绩转为人民币,把金额转为人民币
                        itm.setOrderAchieve(achieList.get(0).getOrderAchieve().multiply(currency.getData().getInExchangeRate()));
                        itm.setOrderAmount(achieList.get(0).getOrderAmount().divide(currencyLocal.getData().getInExchangeRate(), 4, BigDecimal.ROUND_HALF_UP));
                    } else {
                        //新增金额转为美元
                        if (achieList.get(0).getOrderAmount() != null) {
                            itm.setOrderAmount(achieList.get(0).getOrderAmount().divide(currency.getData().getInExchangeRate(), 4, BigDecimal.ROUND_HALF_UP));
                        }
                        itm.setOrderAchieve(achieList.get(0).getOrderAchieve());
                    }
                    itm.setOrderType(orderType);
                }
            });
        }
        return getDataTable(memberList);
    }

    /**
     * 伞下直推新增业绩导出
     *
     * @return
     */
    @PostMapping("/export-direct-push-new")
    public void export(String memberCode, String memberName, Integer pkAwards, Integer pkTeamCode, Integer pkCountry,
                       Date startPayTime, Date endPayTime, Integer pkVertex, Integer pushMethods,
                       HttpServletResponse response, Integer orderType) {
        Long pkMember = null;
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderType);
        if (StringUtils.isNotBlank(memberCode)) {
            R<CuMember> memberDto = memberServiceApi.getMember(memberCode);
            CuMember member = memberDto.getData();
            pkMember = member.getPkId();
        } else {
            List<DirectPushNewVo> mList = new ArrayList<>();
            ExcelUtil<DirectPushNewVo> util = new ExcelUtil<>(DirectPushNewVo.class);
            util.exportExcel(response, mList, "伞下直推新增业绩导出");
        }
        if (pkCountry == null) {
            pkCountry = SecurityUtils.getPkCountry();
        }
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EOrderBusiness.values());
        //伞下直推新增业绩
        List<DirectPushNewVo> memberList = memberReportService.directPushNewList(pkMember, memberName, pkAwards, pkTeamCode, pkCountry, startPayTime, endPayTime, pkVertex);
        if (startPayTime != null) {
            startPayTime = DateUtils.getStartTime(startPayTime);
        }
        if (endPayTime != null) {
            endPayTime = DateUtils.getEndTime(endPayTime);
        }
        Date date = DateUtils.currentDate();
        if (StringUtils.isNull(startPayTime) ||
                StringUtils.isNull(endPayTime)) {
            //当前月的第一天
            startPayTime = DateUtils.currentMonthFirstDate();
            endPayTime = date;
        }
        List<DirectPushNewVo> achieList;
        if (pushMethods != null && pushMethods == EDirectPushMode.UMBRELLA_PUSH.getValue()) {
            achieList = memberReportService.directPushNewAchieList(pkMember, startPayTime, endPayTime, orderTypeList, pkCountry);
        } else {
            achieList = memberReportService.personDirectPushAchieList(pkMember, startPayTime, endPayTime, orderTypeList, pkCountry);
        }
        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.forEach(itm -> {
                if (null != achieList.get(0)) {
                    itm.setOrderTypeVal(transactionMap.get(EnumsPrefixConstants.ORDER_BUSINESS + orderType));
                    itm.setOrderAchieve(achieList.get(0).getOrderAchieve());
                    //新增金额转为美元
                    if (achieList.get(0).getOrderAmount() != null) {
                        itm.setOrderAmount(achieList.get(0).getOrderAmount().divide(currency.getData().getInExchangeRate(), 4, BigDecimal.ROUND_HALF_UP));
                    }
                }
            });
        }
        ExcelUtil<DirectPushNewVo> util = new ExcelUtil<>(DirectPushNewVo.class);
        util.exportExcel(response, memberList, "伞下直推新增业绩导出");
    }


    /**
     * 用户消费统计
     */
    @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);
    }

    /**
     * 用户消费统计导出
     */
    @PostMapping("member-consumption-export")
    public void memberConsumptionListExport(String memberCode, String memberName, Date startPayTime, Date endPayTime, Integer pkWares, HttpServletResponse response) {
        List<MemberConsumptionVo> memberReportList = memberReportService.memberConsumptionList(memberCode, memberName, startPayTime, endPayTime, pkWares);
        ExcelUtil<MemberConsumptionVo> util = new ExcelUtil<>(MemberConsumptionVo.class);
        util.exportExcel(response, memberReportList, "用户消费统计导出");
    }


    /**
     * 伞下新增安置业绩 列表
     */
    @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);
        }
        if (StringUtils.isEmpty(memberCode)) {
            return getDataTable(new ArrayList<>());
        }
        R<CuMember> memberDto = memberServiceApi.getMember(memberCode);
        CuMember member = memberDto.getData();
        if (member == null) {
            return getDataTable(new ArrayList<>());
        }

        Integer pkCountry = SecurityUtils.getPkCountry();
//        R<CurrencyDTO> currencyDto = currencyServiceApi.getCurrency(pkCountry);
//        CurrencyDTO currency = currencyDto.getData();
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderType);

        if (pkCountry == CountryConstants.CHINA_COUNTRY) {
            pkCountry = null;
        }
        MemberResettleAchieveVo memberResettleAchieve = memberReportService.memberResettleAchieveInfo(member.getPkId(), memberName, startPayTime, endPayTime, pkVertex, pkTeamCode, pkCountry, pkAwards, orderTypeList);
        // 查询会员所有部门
        List<Integer> memberPlaceDeptList = memberReportService.queryMemberPlaceDeptList(member.getPkId());
        // 排序
        Collections.sort(memberPlaceDeptList);
        List<MemberAchieveVO> memberAchieveList = new ArrayList<>();
        for (Integer placeDept : memberPlaceDeptList) {
            MemberAchieveVO memberAchieveVO = memberReportService.queryMemberPlaceDeptAchieve(member.getPkId(), placeDept, pkCountry, memberName, startPayTime, endPayTime, pkVertex, pkTeamCode, pkAwards, orderTypeList);
            if (StringUtils.isNull(memberAchieveVO)) {
                memberAchieveVO = new MemberAchieveVO();
                memberAchieveVO.setPlaceDept(placeDept);
            }
            memberAchieveList.add(memberAchieveVO);
        }
        memberAchieveList.stream().sorted(Comparator.comparing(MemberAchieveVO::getPlaceDept).reversed()).collect(Collectors.toList());
        //   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 inExchangeRate = currency.getInExchangeRate();
//        List<MemberAchieveVO> memberAchieveList = new ArrayList<>();
//        for (Map.Entry<Integer, MemberResettleAchieveVo> im : memberResettleAchieveMap.entrySet()) {
//            MemberAchieveVO memberAchieveVO = new MemberAchieveVO();
//            memberAchieveVO.setAchieve(im.getValue().getAchieve().multiply(inExchangeRate));
//            memberAchieveVO.setPlaceDept(im.getValue().getPlaceDept());
//            memberAchieveList.add(memberAchieveVO);
//        }

        // 查询会员业绩
        MemberResettleAchieveVo memberResettleAchieveVo = new MemberResettleAchieveVo();
        memberResettleAchieveVo.setPkMember(member.getPkId());
        memberResettleAchieveVo.setNationalFlag(memberResettleAchieve.getNationalFlag());
        memberResettleAchieveVo.setShortName(memberResettleAchieve.getShortName());
        memberResettleAchieveVo.setMemberCode(memberResettleAchieve.getMemberCode());
        memberResettleAchieveVo.setMemberName(memberResettleAchieve.getMemberName());
        memberResettleAchieveVo.setPhone(memberResettleAchieve.getPhone());
        memberResettleAchieveVo.setAwardsName(memberResettleAchieve.getAwardsName());
        memberResettleAchieveVo.setVertexName(memberResettleAchieve.getVertexName());
        memberResettleAchieveVo.setTeamCodeName(memberResettleAchieve.getTeamCodeName());
        memberResettleAchieveVo.setOrderTime(memberResettleAchieve.getOrderTime());

        memberResettleAchieveVo.setMemberAchieveList(memberAchieveList);

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

    /**
     * 伞下新增安置业绩导出
     */
    @PostMapping("member-resettle-achieve-export")
    public void memberResettleAchieveExport(String memberCode, String memberName, Date startPayTime, Date endPayTime, Integer pkVertex, Integer pkTeamCode, Integer orderType, Integer pkAwards, HttpServletResponse response) {
        if (startPayTime != null) {
            startPayTime = DateUtils.getStartTime(startPayTime);
        }
        if (endPayTime != null) {
            endPayTime = DateUtils.getEndTime(endPayTime);
        }
        if (StringUtils.isEmpty(memberCode)) {
            ExcelUtil<MemberResettleAchieveVo> util = new ExcelUtil<>(MemberResettleAchieveVo.class);
            util.exportExcel(response, new ArrayList<>(), "伞下新增安置业绩导出");
        }
        R<CuMember> memberDto = memberServiceApi.getMember(memberCode);
        CuMember member = memberDto.getData();
        if (member == null) {
            ExcelUtil<MemberResettleAchieveVo> util = new ExcelUtil<>(MemberResettleAchieveVo.class);
            util.exportExcel(response, new ArrayList<>(), "伞下新增安置业绩导出");
        }

        Integer pkCountry = SecurityUtils.getPkCountry();
//        R<CurrencyDTO> currencyDto = currencyServiceApi.getCurrency(pkCountry);
//        CurrencyDTO currency = currencyDto.getData();
        List<Integer> orderTypeList = EOrderBusiness.getOrderTypeList(orderType);


        MemberResettleAchieveVo memberResettleAchieve = memberReportService.memberResettleAchieveInfo(member.getPkId(), memberName, startPayTime, endPayTime, pkVertex, pkTeamCode, pkCountry, pkAwards, orderTypeList);
        // 查询会员所有部门
        List<Integer> memberPlaceDeptList = memberReportService.queryMemberPlaceDeptList(member.getPkId());
        // 排序
        Collections.sort(memberPlaceDeptList);
        List<MemberAchieveVO> memberAchieveList = new ArrayList<>();
        for (Integer placeDept : memberPlaceDeptList) {
            MemberAchieveVO memberAchieveVO = memberReportService.queryMemberPlaceDeptAchieve(member.getPkId(), placeDept, pkCountry, memberName, startPayTime, endPayTime, pkVertex, pkTeamCode, pkAwards, orderTypeList);
            memberAchieveList.add(memberAchieveVO);
        }
        memberAchieveList.stream().sorted(Comparator.comparing(MemberAchieveVO::getPlaceDept).reversed()).collect(Collectors.toList());
        //   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 inExchangeRate = currency.getInExchangeRate();
//        List<MemberAchieveVO> memberAchieveList = new ArrayList<>();
//        for (Map.Entry<Integer, MemberResettleAchieveVo> im : memberResettleAchieveMap.entrySet()) {
//            MemberAchieveVO memberAchieveVO = new MemberAchieveVO();
//            memberAchieveVO.setAchieve(im.getValue().getAchieve().multiply(inExchangeRate));
//            memberAchieveVO.setPlaceDept(im.getValue().getPlaceDept());
//            memberAchieveList.add(memberAchieveVO);
//        }

        MemberResettleAchieveVo memberResettleAchieveVo = new MemberResettleAchieveVo();
        memberResettleAchieveVo.setPkMember(member.getPkId());
        memberResettleAchieveVo.setNationalFlag(memberResettleAchieve.getNationalFlag());
        memberResettleAchieveVo.setShortName(memberResettleAchieve.getShortName());
        memberResettleAchieveVo.setMemberCode(memberResettleAchieve.getMemberCode());
        memberResettleAchieveVo.setMemberName(memberResettleAchieve.getMemberName());
        memberResettleAchieveVo.setPhone(memberResettleAchieve.getPhone());
        // memberResettleAchieveVo.setAchieve(totalAchieve);
        memberResettleAchieveVo.setAwardsName(memberResettleAchieve.getAwardsName());
        memberResettleAchieveVo.setVertexName(memberResettleAchieve.getVertexName());
        memberResettleAchieveVo.setTeamCodeName(memberResettleAchieve.getTeamCodeName());
        memberResettleAchieveVo.setOrderTime(memberResettleAchieve.getOrderTime());
        StringBuilder str = new StringBuilder();
        for (MemberAchieveVO memberAchieveVO : memberAchieveList) {
            str.append("第" + memberAchieveVO.getPlaceDept() + "部门: 业绩:" + memberAchieveVO.getAchieve());
        }
        memberResettleAchieveVo.setMemberAchieveStr(str.toString());
        //     memberResettleAchieveVo.setMemberAchieveList(memberAchieveList);

        ExcelUtil<MemberResettleAchieveVo> util = new ExcelUtil<>(MemberResettleAchieveVo.class);
        util.exportExcel(response, Collections.singletonList(memberResettleAchieveVo), "伞下新增安置业绩导出");
    }

    /**
     * 订单币种查询
     *
     * @param
     * @return
     */
    @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.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());
                    }
                }
                orderCurrencyVo.setCashAccount(cashAccount);
                orderCurrencyVo.setBonusAccount(bonusAccount);
                orderCurrencyVo.setExpendAccount(expendAccount);
                orderCurrencyVo.setPolicyAccount(policyAccount);
                orderCurrencyVo.setIntegralAccount(integralAccount);
            }
        }
        return getDataTable(memberResettleAchieveList);
    }

    /**
     * 订单分布统计
     *
     * @param
     * @return
     */
    @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);
    }

    /**
     * 出货明细汇总统计
     *
     * @param
     * @return
     */
    @GetMapping("product-shipping-details-list")
    public TableDataInfo productShippingDetailsList(String productName, Integer pkClassify, Date startTime, Date endTime, Integer orderType) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (pkCountry == CountryConstants.CHINA_COUNTRY) {
            pkCountry = null;
        }
        List<Integer> orderTypeList = new ArrayList<>();
        if (orderType != null) {
            if (orderType.equals(99)) {
                // 订单类型 99 表示查询全部复购订单
                orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
            } else {
                orderTypeList.add(orderType);
            }
        }

        List<ProductOrderInfoVo> memberReportList = memberReportService.getProductOrderInfo(productName, pkClassify, startTime, endTime, pkCountry, orderTypeList);
        for (ProductOrderInfoVo productOrderInfoVo : memberReportList) {
            //根据国家查询汇率，金额转为美元
            //当前国家汇率
            R<CurrencyDTO> currencyLocal = currencyServiceApi.getCurrency(productOrderInfoVo.getPkCountry());
            if (SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
                productOrderInfoVo.setProductPrice(productOrderInfoVo.getProductPrice().divide(currencyLocal.getData().getInExchangeRate(), 4, BigDecimal.ROUND_HALF_UP));
            }
            productOrderInfoVo.setProductTotalPrice(productOrderInfoVo.getProductPrice().multiply(BigDecimal.valueOf(productOrderInfoVo.getQuantity())));
            if (productOrderInfoVo.getOrderType() != null) {
                productOrderInfoVo.setOrderTypeStr(EOrderType.getEnumByValue(productOrderInfoVo.getOrderType()).getLabel());
            }
        }
        return getDataTable(memberReportList);
    }

    /**
     * 出货明细汇总导出
     *
     * @return
     */
    @PostMapping("product-shipping-details-export")
    public void productShippingDetailsExport(String productName, Integer pkClassify, Date startTime, Date endTime, Integer orderType, HttpServletResponse response) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (pkCountry == CountryConstants.CHINA_COUNTRY) {
            pkCountry = null;
        }
        List<Integer> orderTypeList = new ArrayList<>();
        if (orderType != null) {
            if (orderType.equals(99)) {
                // 订单类型 99 表示查询全部复购订单
                orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
            } else {
                orderTypeList.add(orderType);
            }
        }
        List<ProductOrderInfoVo> memberReportList = memberReportService.getProductOrderInfo(productName, pkClassify, startTime, endTime, pkCountry, orderTypeList);
        for (ProductOrderInfoVo productOrderInfoVo : memberReportList) {
            //根据国家查询汇率，金额转为美元
            //当前国家汇率
            R<CurrencyDTO> currencyLocal = currencyServiceApi.getCurrency(productOrderInfoVo.getPkCountry());
            if (SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
                productOrderInfoVo.setProductPrice(productOrderInfoVo.getProductPrice().divide(currencyLocal.getData().getInExchangeRate(), 4, BigDecimal.ROUND_HALF_UP));
            }
            productOrderInfoVo.setProductTotalPrice(productOrderInfoVo.getProductPrice().multiply(BigDecimal.valueOf(productOrderInfoVo.getQuantity())));
            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
     */
    @GetMapping("product-shipping-details-info-list")
    public TableDataInfo productShippingDetailsList(String productName, Integer pkProduct, Integer pkClassify, Integer pkAwards, Integer orderType) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<ProductShippingDetailsInfoVo> productOrderInfoVoList = memberReportService.productShippingDetailsList(pkProduct, productName, pkClassify, pkAwards, pkCountry, orderType);
        return getDataTable(productOrderInfoVoList);
    }

    /**
     * 出货明细汇总统计详情
     *
     * @param productName
     * @param pkProduct
     * @return
     */
    @PostMapping("product-shipping-details-info-list-export")
    public void productShippingDetailsListExport(String productName, Integer pkProduct, HttpServletResponse response, Integer pkClassify, Integer pkAwards, Integer orderType) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<ProductShippingDetailsInfoVo> productOrderInfoVoList = memberReportService.productShippingDetailsList(pkProduct, productName, pkClassify, pkAwards, pkCountry, orderType);
        ExcelUtil<ProductShippingDetailsInfoVo> util = new ExcelUtil<>(ProductShippingDetailsInfoVo.class);
        util.exportExcel(response, productOrderInfoVoList, "出货明细汇总统计详情");
    }

    /**
     * 报单汇总
     *
     * @return
     */
    @GetMapping("report-summary-list")
    public TableDataInfo reportSummaryList(ReportSummaryVo reportSummaryVo) {
        if (null != reportSummaryVo.getEndCreateTime()) {
            // 补全23:59:59
            reportSummaryVo.setEndCreateTime(DateUtils.getEndTime(reportSummaryVo.getEndCreateTime()));
        }

        startPage();
        reportSummaryVo.setPkCountry(SecurityUtils.getPkCountry());
        //中国查询全部
        if (reportSummaryVo.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            reportSummaryVo.setPkCountry(null);
        }
        List<ReportSummaryVo> reportSummaryList = memberReportService.reportSummaryList(reportSummaryVo);
        for (ReportSummaryVo summaryVo : reportSummaryList) {
            if (summaryVo.getConsumeMoney() != null) {
                //转换为美元
                R<CurrencyDTO> currency = currencyServiceApi.getCurrency(summaryVo.getPkCountry());
                summaryVo.setConsumeMoney(summaryVo.getConsumeMoney().divide(currency.getData().getInExchangeRate(), 4, BigDecimal.ROUND_HALF_UP));
            }
            if (summaryVo.getRegisterAuthority() != null) {
                summaryVo.setRegisterName(ERegistrationAuthority.getEnumByValue(summaryVo.getRegisterAuthority()).getLabel());
            }
        }
        return getDataTable(reportSummaryList);
    }

    /**
     * 报单汇总
     *
     * @return
     */
    @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()));
        }
        //中国查询全部
        reportSummaryVo.setPkCountry(SecurityUtils.getPkCountry());
        if (reportSummaryVo.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            reportSummaryVo.setPkCountry(null);
        }
        List<ReportSummaryVo> reportSummaryList = memberReportService.reportSummaryList(reportSummaryVo);
        for (ReportSummaryVo summaryVo : reportSummaryList) {
            if (summaryVo.getConsumeMoney() != null) {
                //转换为美元
                R<CurrencyDTO> currency = currencyServiceApi.getCurrency(summaryVo.getPkCountry());
                //转换为美元
                summaryVo.setConsumeMoney(summaryVo.getConsumeMoney().divide(currency.getData().getInExchangeRate(), 4, BigDecimal.ROUND_HALF_UP));
            }
            if (summaryVo.getRegisterAuthority() != null) {
                summaryVo.setRegisterName(ERegistrationAuthority.getEnumByValue(summaryVo.getRegisterAuthority()).getLabel());
            }
        }
        ExcelUtil<ReportSummaryVo> util = new ExcelUtil<>(ReportSummaryVo.class);
        util.exportExcel(response, reportSummaryList, "报单汇总导出");
    }

    /*
     * @description: 安置反查
     * @author: sui q
     * @date: 2023/8/28 10:07
     * @param: null null
     **/
    @PostMapping("/place-peg")
    public TableDataInfo memberPlacePeg(@RequestBody CuMemberUmbrellaParam cuMemberUmbrellaParam) {
        List<CuMemberPushAchieveVO> cuMemberPushAchieveVOList = new ArrayList<>();
        if (StringUtils.isNotEmpty(cuMemberUmbrellaParam.getMemberCode())) {
            if (null != cuMemberUmbrellaParam.getUpDown() &&
                    EUpDown.UP.getValue() == cuMemberUmbrellaParam.getUpDown()) {
                // 反查，没有安置部门
                cuMemberUmbrellaParam.setPlaceDept(null);
            }

            startPage();
            List<CuMemberAchieveExt> cuMemberAchieveExtList = memberService.queryPlaceCuMemberAchieveExt(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);
    }

    /**
     * @description: 导出安置反查
     * @author: zhang jing
     * @date: 2023/9/12 10:04
     * @param: [response, cuMemberUmbrellaParam]
     * @return: void
     **/
    @PostMapping("/export-place-peg")
    public void exportPlacePeg(HttpServletResponse response, CuMemberUmbrellaParam cuMemberUmbrellaParam) {
        List<CuMemberPushAchieveVO> cuMemberPushAchieveVOList = new ArrayList<>();

        if (StringUtils.isNotEmpty(cuMemberUmbrellaParam.getMemberCode())) {
            if (null != cuMemberUmbrellaParam.getUpDown() &&
                    EUpDown.UP.getValue() == cuMemberUmbrellaParam.getUpDown()) {
                // 反查，没有安置部门
                cuMemberUmbrellaParam.setPlaceDept(null);
            }

            List<CuMemberAchieveExt> cuMemberAchieveExtList = memberService.queryPlaceCuMemberAchieveExt(cuMemberUmbrellaParam);
            if (CollectionUtil.isNotEmpty(cuMemberAchieveExtList)) {
                // 获取需要翻译的枚举翻译
                Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EDealerYesNo.values(), ECategory.values());
                Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE, EnumsPrefixConstants.KEY_AWARD);

                for (CuMemberAchieveExt cuMemberAchieveExt : cuMemberAchieveExtList) {
                    CuMemberPushAchieveVO vo = BeanUtil.copyProperties(cuMemberAchieveExt, CuMemberPushAchieveVO.class);
                    vo.setPkRegisterGradeVal(transactionMap1.get(cuMemberAchieveExt.getPkRegisterGrade()));
                    vo.setPkGradeVal(transactionMap1.get(cuMemberAchieveExt.getPkGrade()));
                    vo.setPkAwardsVal(transactionMap1.get(cuMemberAchieveExt.getPkAwards()));
                    vo.setPlaceDeptVal("第" + cuMemberAchieveExt.getPlaceDept() + "部门");
                    vo.setCategoryVal(transactionMap.get(EnumsPrefixConstants.ENU_CAT + cuMemberAchieveExt.getCategory()));
                    cuMemberPushAchieveVOList.add(vo);
                }
            }
        }
        ExcelUtil<CuMemberPushAchieveVO> util = new ExcelUtil<>(CuMemberPushAchieveVO.class);
        util.exportExcel(response, cuMemberPushAchieveVOList, "安置反查");
    }

    /*
     * @description: 推荐反查
     * @author: sui q
     * @date: 2023/8/28 10:07
     * @param: null null
     **/
    @PostMapping("/parent-peg")
    public TableDataInfo memberParentPeg(@RequestBody CuMemberUmbrellaParam cuMemberUmbrellaParam) {
        List<CuMemberPushAchieveVO> cuMemberPushAchieveVOList = new ArrayList<>();
        if (StringUtils.isNotEmpty(cuMemberUmbrellaParam.getMemberCode())) {
            startPage();
            List<CuMemberAchieveExt> cuMemberAchieveExtList = memberService.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);
    }

    /**
     * @description: 导出推荐反查
     * @author: zhang jing zj
     * @date: 2023/9/12 10:04
     * @param: [response, cuMemberUmbrellaParam]
     * @return: void
     **/
    @PostMapping("/export-parent-peg")
    public void exportParentPeg(HttpServletResponse response, CuMemberUmbrellaParam cuMemberUmbrellaParam) {
        List<CuMemberPushAchieveVO> cuMemberPushAchieveVOList = new ArrayList<>();

        if (StringUtils.isNotEmpty(cuMemberUmbrellaParam.getMemberCode())) {
            List<CuMemberAchieveExt> cuMemberAchieveExtList = memberService.queryParentCuMemberAchieveExt(cuMemberUmbrellaParam);
            if (CollectionUtil.isNotEmpty(cuMemberAchieveExtList)) {
                // 获取需要翻译的枚举翻译
                Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EDealerYesNo.values(), ECategory.values());
                Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE, EnumsPrefixConstants.KEY_AWARD);

                for (CuMemberAchieveExt cuMemberAchieveExt : cuMemberAchieveExtList) {
                    CuMemberPushAchieveVO vo = BeanUtil.copyProperties(cuMemberAchieveExt, CuMemberPushAchieveVO.class);
                    vo.setPkRegisterGradeVal(transactionMap1.get(cuMemberAchieveExt.getPkRegisterGrade()));
                    vo.setPkGradeVal(transactionMap1.get(cuMemberAchieveExt.getPkGrade()));
                    vo.setPkAwardsVal(transactionMap1.get(cuMemberAchieveExt.getPkAwards()));
                    vo.setPlaceDeptVal("第" + cuMemberAchieveExt.getPlaceDept() + "部门");
                    vo.setCategoryVal(transactionMap.get(EnumsPrefixConstants.ENU_CAT + cuMemberAchieveExt.getCategory()));
                    cuMemberPushAchieveVOList.add(vo);
                }
            }
        }
        ExcelUtil<CuMemberPushAchieveVO> util = new ExcelUtil<>(CuMemberPushAchieveVO.class);
        util.exportExcel(response, cuMemberPushAchieveVOList, "推荐反查");
    }

    /**
     * 会员等级占比
     */
    @GetMapping("grade-proportion")
    public AjaxResult gradeProportion(Date startTime, Date endTime) {
        R<List<GradeDTO>> gradeListData = gradeServiceApi.queryGradeList(SecurityUtils.getPkCountry());
        List<GradeDTO> gradeList = gradeListData.getData();
        List<Integer> gradeId = gradeList.stream().map(GradeDTO::getPkId).collect(Collectors.toList());
        // 查询会员总人数
        R<List<CuMemberExt>> memberDto = memberServiceApi.getMemberAll(gradeId, SecurityUtils.getPkCountry(), startTime, endTime);
        // 会员总数
        List<CuMemberExt> memberList = memberDto.getData();
        Map<Integer, List<CuMemberExt>> memberMap = memberList.stream().collect(Collectors.groupingBy(CuMemberExt::getPkSettleGrade));
        List<GradeProportionVo> resultList = new ArrayList<>();
        for (GradeDTO gradeDTO : gradeList) {
            GradeProportionVo gradeProportionVo = new GradeProportionVo();
            List<CuMemberExt> cuMemberExts = memberMap.get(gradeDTO.getPkId());
            int count = 0;
            if (cuMemberExts != null) {
                count = cuMemberExts.size();
            }
            gradeDTO.setMemberCount(count);
            // 总数
            int memberSum = memberList.size();
            if (memberSum == 0) {
                gradeDTO.setProportion(BigDecimal.ZERO);
            } else {
                BigDecimal proportion = new BigDecimal(count).divide(new BigDecimal(memberSum), 2, BigDecimal.ROUND_HALF_UP).setScale(2, RoundingMode.HALF_UP);
                gradeDTO.setProportion(proportion.multiply(new BigDecimal(100)));
            }
            gradeProportionVo.setGradeName(gradeDTO.getGradeName());
            gradeProportionVo.setMemberCount(gradeDTO.getMemberCount());
            gradeProportionVo.setProportion(gradeDTO.getProportion());
            gradeProportionVo.setProportionLabel(gradeDTO.getProportion() + "%");
            resultList.add(gradeProportionVo);
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 会员等级占比 导出
     */
    @PostMapping("grade-proportion-export")
    public void export(Date startTime, Date endTime, HttpServletResponse response) {
        R<List<GradeDTO>> gradeListData = gradeServiceApi.queryGradeList(SecurityUtils.getPkCountry());
        List<GradeDTO> gradeList = gradeListData.getData();
        List<Integer> gradeId = gradeList.stream().map(GradeDTO::getPkId).collect(Collectors.toList());
        // 查询会员总人数
        R<List<CuMemberExt>> memberDto = memberServiceApi.getMemberAll(gradeId, SecurityUtils.getPkCountry(), startTime, endTime);
        // 会员总数
        List<CuMemberExt> memberList = memberDto.getData();
        Map<Integer, List<CuMemberExt>> memberMap = memberList.stream().collect(Collectors.groupingBy(CuMemberExt::getPkSettleGrade));
        List<GradeProportionVo> resultList = new ArrayList<>();
        for (GradeDTO gradeDTO : gradeList) {
            GradeProportionVo gradeProportionVo = new GradeProportionVo();
            List<CuMemberExt> cuMemberExts = memberMap.get(gradeDTO.getPkId());
            int count = 0;
            if (cuMemberExts != null) {
                count = cuMemberExts.size();
            }
            gradeDTO.setMemberCount(count);
            // 总数
            int memberSum = memberList.size();

            if (memberSum == 0) {
                gradeDTO.setProportion(BigDecimal.ZERO);
            } else {
                BigDecimal proportion = new BigDecimal(count).divide(new BigDecimal(memberSum), 2, BigDecimal.ROUND_HALF_UP).setScale(2, RoundingMode.HALF_UP);
                gradeDTO.setProportion(proportion.multiply(new BigDecimal(100)));
            }

            gradeProportionVo.setGradeName(gradeDTO.getGradeName());
            gradeProportionVo.setMemberCount(gradeDTO.getMemberCount());
            gradeProportionVo.setProportion(gradeDTO.getProportion());
            gradeProportionVo.setProportionLabel(gradeDTO.getProportion() + "%");
            resultList.add(gradeProportionVo);
        }
        ExcelUtil<GradeProportionVo> util = new ExcelUtil<>(GradeProportionVo.class);
        util.exportExcel(response, resultList, "等级占比导出");
    }
}
