package com.hzs.activity.recoilGive.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.param.QueryActivityParam;
import com.hzs.activity.base.service.IAcApprovalLogService;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.activity.base.vo.BaseConfigVo;
import com.hzs.activity.recoilGive.mapper.AcRecoilGiveConfigMapper;
import com.hzs.activity.recoilGive.service.IAcRecoilGiveConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.recommend.param.AcRecommendParam;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.activity.base.AcApprovalLog;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.domain.activity.base.AcGoalMemberConfig;
import com.hzs.common.core.enums.EAccount;
import com.hzs.common.domain.activity.recoilGive.AcRecoilGiveConfig;
import com.hzs.common.domain.member.account.CuMemberTradeRecoil;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.member.account.ICuMemberTradeRecoilServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.system.config.BdAccount;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAccountServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * 复消币赠送活动配置 服务实现类
 *
 * @author hzs
 * @since 2024-07-18
 */
@Slf4j
@Service
public class AcRecoilGiveConfigServiceImpl extends ServiceImpl<AcRecoilGiveConfigMapper, AcRecoilGiveConfig> implements IAcRecoilGiveConfigService {
    @Autowired
    private IAcApprovalLogService acApprovalLogService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IAcRecoilGiveConfigService recoilGiveConfigService;
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    private IAcGoalMemberConfigService goalMemberConfigService;

    @DubboReference
    private IApprovalServiceApi approvalServiceApi;
    @DubboReference
    private IMemberServiceApi iMemberServiceApi;
    @DubboReference
    private ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    private IAccountServiceApi iAccountServiceApi;
    @DubboReference
    private ICuMemberTradeRecoilServiceApi iCuMemberTradeRecoilServiceApi;
    @DubboReference
    private IGradeServiceApi iGradeServiceApi;

    /**
     * 新增复消币活动配置
     *
     * @param activityParam
     */
    @Override
    public Long saveRecoilGiveConfig(ActivityParam activityParam) {
        // 增加基础配置
        AcBaseConfig baseConfig = activityService.saveBaseConfig(activityParam);
        // 目标群体配置
        activityService.saveGoalMemberConfig(activityParam, baseConfig);
        // 复消币活动配置
        recoilGiveConfigService.createRecoilGiveConfig(activityParam, baseConfig);
        return baseConfig.getPkId();
    }

    /**
     * 复消币活动配置新增
     *
     * @param activityParam
     * @param baseConfig
     */
    @Override
    public void createRecoilGiveConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {
        if (activityParam.getRecoilGiveConfigList().size() > 0) {
            List<AcRecoilGiveConfig> recoilGiveConfigList = activityParam.getRecoilGiveConfigList().stream().map(recoilGiveConfigVO -> {
                AcRecoilGiveConfig acRecoilGiveConfig = BeanUtil.copyProperties(recoilGiveConfigVO, AcRecoilGiveConfig.class);
                acRecoilGiveConfig.setPkBaseConfig(baseConfig.getPkId());
                acRecoilGiveConfig.setPkCreator(activityParam.getPkCreator());
                acRecoilGiveConfig.setPkCountry(baseConfig.getPkCountry());
                acRecoilGiveConfig.setCreationTime(DateUtils.currentDateTime());

                return acRecoilGiveConfig;
            }).collect(Collectors.toList());
            recoilGiveConfigService.saveBatch(recoilGiveConfigList);
        }

    }

    /**
     * 复消币赠送 签呈审批
     *
     * @param recommendParam
     */
    @Override
    public void onLinePetition(AcRecommendParam recommendParam) {
        EApprovalBusiness approvalBusiness = null;
        if (recommendParam.getControlType() == EControlType.SAVE.getValue()) {
            approvalBusiness = EApprovalBusiness.RECOIL_GIVE_ADD;
        } else if (recommendParam.getControlType() == EControlType.MODIFY.getValue()) {
            approvalBusiness = EApprovalBusiness.RECOIL_GIVE_UPDATE;
        } else if (recommendParam.getControlType() == EControlType.DELETE.getValue()) {
            approvalBusiness = EApprovalBusiness.RECOIL_GIVE_REMOVE;
        }

        submitApproval(recommendParam, approvalBusiness);
    }

    /**
     * 复消币赠送签呈 审批通过
     *
     * @param businessResult
     */
    @Override
    public String ApprovalAgree(ApprovalBusinessResultDTO businessResult) {
        EApprovalBusiness eApprovalBusiness = businessResult.getEApprovalBusiness();
        String businessCode = businessResult.getBusinessCode();
        LoginUser loginUser = businessResult.getLoginUser();
        AcApprovalLog approvalLog = acApprovalLogService.queryApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry());
        if (null == approvalLog) {
            return "审批数据不存在！";
        }
        Integer controlType = approvalLog.getControlType();
        String data = approvalLog.getAfterData();
        if (StringUtils.isNotEmpty(data)) {
            AcRecommendParam recommendParam = JSONUtil.toBean(data, AcRecommendParam.class);
            if (controlType.equals(EControlType.SAVE.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                activityParam.setPkCountry(recommendParam.getPkCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.RECOIL_GIVE.getValue());
                Long pkBaseId = recoilGiveConfigService.saveRecoilGiveConfig(activityParam);
                //日志
                //    IActivityService.createBaseConfigLog(activityParam, new StringBuffer(), pkBaseId, EApprovalBusiness.CONSUME_GIFT_ADD.getValue(), true);
                return null;
            } else if (controlType.equals(EControlType.MODIFY.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                activityParam.setPkCountry(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.RECOIL_GIVE.getValue());
                recoilGiveConfigService.updateRecoilGiveConfig(activityParam);
                //    IActivityService.createBaseConfigLog(activityParam, new StringBuffer(), activityParam.getPkBaseId(), EApprovalBusiness.CONSUME_GIFT_UPDATE.getValue(), true);
                return null;
            } else if (controlType.equals(EControlType.DELETE.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                Long pkBaseId = activityParam.getPkBaseId();
      //          AcBaseConfig baseConfig = baseConfigService.getById(activityParam.getPkId());
       //
                baseConfigService.removeById(activityParam.getPkId());
                recoilGiveConfigService.removeRecoilGiveConfig(activityParam.getPkId());
                //    IActivityService.removeBaseConfigLog(baseConfig, new StringBuffer(), activityParam.getPkBaseId(), EApprovalBusiness.CONSUME_GIFT_REMOVE.getValue(), true);
            }
        }
        return null;
    }

    /**
     * 复消币活动配置修改
     *
     * @param activityParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long updateRecoilGiveConfig(ActivityParam activityParam) {
        Long pkId = activityParam.getPkId();
        // 查询基础信息
        AcBaseConfig baseConfig = BeanUtil.copyProperties(activityParam, AcBaseConfig.class);
        baseConfig.setPkId(activityParam.getPkId());
        baseConfigService.updateById(baseConfig);

        QueryWrapper<AcGoalMemberConfig> qt = new QueryWrapper<>();
        qt.eq("PK_BASE_ID", pkId);
        goalMemberConfigService.remove(qt);
        // 目标群体配置
        activityService.saveGoalMemberConfig(activityParam, baseConfig);

        // 删除复消币赠送活动基础配置
        recoilGiveConfigService.removeRecoilGiveConfig(baseConfig.getPkId());
        // 复消币活动配置
        recoilGiveConfigService.createRecoilGiveConfig(activityParam, baseConfig);
        return pkId;
    }

    /**
     * 删除复消币活动配置
     *
     * @param pkBaseId
     */
    @Override
    public void removeRecoilGiveConfig(Long pkBaseId) {
        QueryWrapper<AcRecoilGiveConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_BASE_CONFIG", pkBaseId);
        recoilGiveConfigService.remove(queryWrapper);
    }

    /**
     * 复消币赠送活动驳回
     *
     * @param businessResult
     */
    @Override
    public String ApprovalReject(ApprovalBusinessResultDTO businessResult) {
        EApprovalBusiness eApprovalBusiness = businessResult.getEApprovalBusiness();
        String businessCode = businessResult.getBusinessCode();
        LoginUser loginUser = businessResult.getLoginUser();
        AcApprovalLog approvalLog = acApprovalLogService.queryApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry());
        if (null == approvalLog) {
            return "审批数据不存在！";
        }
        //更新审批状态
        acApprovalLogService.updateApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry(),
                loginUser.getUserId(), EApproveRechargeStatus.REJECT, businessResult.getApproveRemark());
        return null;
    }

    @Override
    public List<BaseConfigVo> queryList(QueryActivityParam queryActivityParam) {
        QueryWrapper<AcBaseConfig> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(queryActivityParam.getActName())) {
            queryWrapper.eq("ACT_NAME", queryActivityParam.getActName());
        }
        if (queryActivityParam.getActivityStatus() != null) {
            // 状态筛选
            if (queryActivityParam.getActivityStatus() == EActivityStatus.NOT_STARTED.getValue()) {
                // 未开始  当前时间小于开始时间
                queryWrapper.lt("ACT_START_DATE", DateUtils.currentDate());
                queryWrapper.gt("ACT_START_DATE", DateUtils.currentDate());
            } else if (queryActivityParam.getActivityStatus() == EActivityStatus.IN_PROGRESS.getValue()) {
                // 进行中 大于开始 小于结束
                queryWrapper.le("ACT_START_DATE", DateUtils.currentDate());
                queryWrapper.ge("ACT_END_DATE", DateUtils.currentDate());
            } else if (queryActivityParam.getActivityStatus() == EActivityStatus.EXPIRED.getValue()) {
                // 已失效 当前时间大于结束时间
                queryWrapper.lt("ACT_START_DATE", DateUtils.currentDate());
                queryWrapper.lt("ACT_END_DATE", DateUtils.currentDate());
            }
        }
        // 活动开始时间
        if (queryActivityParam.getStartActStartDate() != null && queryActivityParam.getEndActStartDate() != null) {
            queryWrapper.between("ACT_START_DATE", queryActivityParam.getStartActStartDate(), queryActivityParam.getEndActStartDate());
        }
        // 活动结束时间
        if (queryActivityParam.getStartActEndDate() != null && queryActivityParam.getEndActEndDate() != null) {
            queryWrapper.between("ACT_END_DATE", queryActivityParam.getStartActEndDate(), queryActivityParam.getEndActEndDate());
        }
        // 创建时间
        if (queryActivityParam.getStartCreationTime() != null && queryActivityParam.getEndCreationTime() != null) {
            queryWrapper.between("CREATION_TIME", queryActivityParam.getStartCreationTime(), queryActivityParam.getEndCreationTime());
        }
        queryWrapper.eq("ACT_TYPE", queryActivityParam.getActType());
        queryWrapper.eq("PK_COUNTRY", queryActivityParam.getPkCountry());
        // 创建时间倒叙
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BaseConfigVo> resultList = new ArrayList<>();
        List<AcBaseConfig> list = baseConfigService.list(queryWrapper);
        for (AcBaseConfig acBaseConfig : list) {
            BaseConfigVo baseConfigVo = BeanUtil.copyProperties(acBaseConfig, BaseConfigVo.class);
            // 判断活动状态
            // 开始时间
            long startTime = acBaseConfig.getActStartDate().getTime();
            // 结束时间
            long endTime = acBaseConfig.getActEndDate().getTime();
            // 当前时间
            long currentTime = DateUtils.currentDate().getTime();
            if ((currentTime > startTime && currentTime < endTime) || currentTime == startTime || currentTime == endTime) {
                // 当前时间大于开始 小于结束
                baseConfigVo.setStatus(EActivityStatus.IN_PROGRESS.getLabel());
            } else if (currentTime < startTime) {
                // 当前时间小于开始时间
                baseConfigVo.setStatus(EActivityStatus.NOT_STARTED.getLabel());
            } else if (currentTime > endTime) {
                // 当前时间大于结束时间
                baseConfigVo.setStatus(EActivityStatus.EXPIRED.getLabel());
            }
            resultList.add(baseConfigVo);
        }
        return resultList;
    }

    /**
     * 提交审批
     *
     * @param recommendParam 抽奖参数
     */
    public Boolean submitApproval(AcRecommendParam recommendParam, EApprovalBusiness approvalBusiness) {
        //保存审批日志
        AcApprovalLog approvalLog = saveApprovalLog(recommendParam, approvalBusiness);
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(approvalBusiness)
                .businessCode(approvalLog.getBusinessCode())
                .businessData(JSONObject.toJSONString(recommendParam.getActivityParam()))
                .signType(ESignType.getEnumByValue(recommendParam.getSignType())).userIdList(recommendParam.getUserIdList())
                .sendIdList(recommendParam.getSendIdList()).remark(recommendParam.getRemark()).fileList(recommendParam.getFileList())
                .build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, recommendParam.getLoginUser());
        if (!submit.isSuccess()) {
            throw new RuntimeException("旅游活动参数提交审批失败！");
        }
        return submit.isSuccess();
    }

    /**
     * 保存活动审批日志信息
     *
     * @param recommendParam   复消币赠送参数
     * @param approvalBusiness 审批业务
     * @return boolean
     */
    public AcApprovalLog saveApprovalLog(AcRecommendParam recommendParam, EApprovalBusiness approvalBusiness) {
        Integer controlType = recommendParam.getControlType();
        //查询变更前的数据
/*        String afterData = !controlType.equals(EControlType.SAVE.getValue()) ?
                JSONUtil.toJsonStr(showDetailInfo(recommendParam.getPkBaseId(), recommendParam.getPkCountry())) :
                JSONUtil.toJsonStr(recommendParam);*/
        String afterData = JSONUtil.toJsonStr(recommendParam);
        String beforeData = controlType.equals(EControlType.SAVE.getValue()) ? JSONUtil.toJsonStr(recommendParam) : null;
        //业务单号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        AcApprovalLog approvalLog = AcApprovalLog.builder().approvalType(approvalBusiness.getValue())
                .beforeData(beforeData).businessCode(businessCode).controlType(controlType)
                .approvalStatus(EApproveRechargeStatus.WAIT.getValue()).afterData(afterData)
                .build();
        approvalLog.setPkCreator(recommendParam.getPkMember());
        approvalLog.setPkCountry(recommendParam.getPkCountry());

        acApprovalLogService.save(approvalLog);
        return approvalLog;
    }

    @Override
    public String recoilGiveHandle(SaOrderExt saOrderExt) {
        // 查询 新会员、推荐人 信息
        List<CuMemberExt> cuMemberList = iMemberServiceApi.queryMemberList(Arrays.asList(saOrderExt.getPkMember(), saOrderExt.getPkReference())).getData();
        // 会员Map
        Map<Long, CuMemberExt> cuMemberMap = cuMemberList.stream().collect(Collectors.toMap(CuMember::getPkId, dto -> dto));
        // 新会员
        CuMemberExt newMember = cuMemberMap.get(saOrderExt.getPkMember());
        // 国家ID列表
        Set<Integer> countryIdList = cuMemberList.stream().map(CuMemberExt::getPkSettleCountry).collect(Collectors.toSet());

        // 新会员国家等级数据
        List<GradeDTO> gradeList = iGradeServiceApi.queryGradeConfigByCondition(newMember.getPkSettleCountry()).getData();
        // 旧等级值
        Integer oldPkGrade = null;
        // 新等级值
        Integer newPkGrade = null;
        if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 注册订单
            for (GradeDTO gradeDTO : gradeList) {
                if (saOrderExt.getOrderAchieve().compareTo(gradeDTO.getStartValue()) >= 0) {
                    // 注册订单PV 大于等于 该等级PV，则是会员购买的该等级
                    newPkGrade = gradeDTO.getPkId();
                    break;
                }
            }
        } else {
            // 升级订单
            if (newMember.getPkSettleGrade().equals(saOrderExt.getOrderPkGrade())) {
                // 会员当前等级和升级前等级一致，则不需要处理
                return null;
            } else {
                oldPkGrade = saOrderExt.getOrderPkGrade();
                newPkGrade = newMember.getPkSettleGrade();
            }
        }

        // 查询新会员国家配置
        List<AcRecoilGiveConfig> acRecoilGiveConfigList = baseMapper.listRecoilGiveConfigByCountry(newMember.getPkSettleCountry());
        if (CollectionUtil.isNotEmpty(acRecoilGiveConfigList)) {
            log.info("订单消费币赠送活动存在，进行处理");

            // 旧等级匹配活动规则
            AcRecoilGiveConfig oldAcRecoilGiveConfig = null;
            // 匹配活动规则
            AcRecoilGiveConfig newAcRecoilGiveConfig = null;
            // 推荐人 或 新会员 匹配到活动配置
            for (AcRecoilGiveConfig tmpAcRecoilGiveConfig : acRecoilGiveConfigList) {
                if (tmpAcRecoilGiveConfig.getPkGrade().equals(newPkGrade)) {
                    // 当前等级的配置
                    newAcRecoilGiveConfig = tmpAcRecoilGiveConfig;
                }
                if (tmpAcRecoilGiveConfig.getPkGrade().equals(oldPkGrade)) {
                    // 旧等级的配置
                    oldAcRecoilGiveConfig = tmpAcRecoilGiveConfig;
                }
            }
            if (null == newAcRecoilGiveConfig) {
                // 该国家该等级没有配置对应活动
                return null;
            }

            // 给 推荐人 金额
            BigDecimal parentAmount = newAcRecoilGiveConfig.getParentCalValue();
            // 给 新会员 金额
            BigDecimal newAmount = newAcRecoilGiveConfig.getBuyCalValue();
            if (null != oldAcRecoilGiveConfig) {
                // 如果旧等级配置存在，则计算差等级与旧等级差值
                parentAmount = parentAmount.subtract(oldAcRecoilGiveConfig.getParentCalValue());
                newAmount = newAmount.subtract(oldAcRecoilGiveConfig.getBuyCalValue());
            }

            // 查询国家汇率
            List<CurrencyDTO> currencyList = iCurrencyServiceApi.getCurrencyByPkCountryList(countryIdList).getData();
            Map<Integer, CurrencyDTO> currencyMap = currencyList.stream().collect(Collectors.toMap(CurrencyDTO::getPkCountry, dto -> dto));
            // 查询国家复消账户
            List<BdAccount> accountList = iAccountServiceApi.queryAccountByType(EAccount.RECOIL.getValue(), countryIdList).getData();
            Map<Integer, BdAccount> accountMap = accountList.stream().collect(Collectors.toMap(BdAccount::getPkCountry, dto -> dto));

            // 计算PV下限，推荐人、新会员只有本身等级PV达到30才能拿奖励
            BigDecimal startValue = new BigDecimal("30");
            // 复消账户发送明细列表
            List<CuMemberTradeRecoil> saveList = new ArrayList<>();

            // 推荐人
            CuMemberExt parentMember = cuMemberMap.get(saOrderExt.getPkReference());
            if (null != parentAmount && parentMember.getStartValue().compareTo(startValue) >= 0) {
                // 存在推荐人活动配置，需要进行处理
                // 推荐人汇率
                BigDecimal parentMemberRate = currencyMap.get(parentMember.getPkSettleCountry()).getInExchangeRate();
                parentAmount = parentAmount.multiply(parentMemberRate).setScale(2, BigDecimal.ROUND_HALF_UP);

                CuMemberTradeRecoil cuMemberTradeRecoil = CuMemberTradeRecoil.builder()
                        .pkMember(parentMember.getPkId())
                        .pkGrade(newPkGrade)
                        .tradeCode(CommonUtil.createSerialNumber())
                        .pkAccount(accountMap.get(parentMember.getPkSettleCountry()).getPkId())
                        .tradeType(ETradeType.RECOIL_INCOME_GRANT.getValue())
                        .tradeClassify(ETradeClassify.INCOME.getValue())
                        .pkRate(currencyMap.get(parentMember.getPkSettleCountry()).getPkId())
                        .tradeAmount(parentAmount)
                        .sourcePkMember(newMember.getPkId())
                        .sourceCode(saOrderExt.getOrderCode())
                        .build();
                cuMemberTradeRecoil.setPkCountry(parentMember.getPkSettleCountry());
                cuMemberTradeRecoil.setPkCreator(newMember.getPkId());
                saveList.add(cuMemberTradeRecoil);
            }

            if (null != newAmount && newMember.getStartValue().compareTo(startValue) >= 0) {
                // 存在购买人活动配置，需要进行处理
                // 购买人汇率
                BigDecimal buyMemberRate = currencyMap.get(newMember.getPkSettleCountry()).getInExchangeRate();
                newAmount = newAmount.multiply(buyMemberRate).setScale(2, BigDecimal.ROUND_HALF_UP);

                CuMemberTradeRecoil cuMemberTradeRecoil = CuMemberTradeRecoil.builder()
                        .pkMember(newMember.getPkId())
                        .pkGrade(newPkGrade)
                        .tradeCode(CommonUtil.createSerialNumber())
                        .pkAccount(accountMap.get(newMember.getPkSettleCountry()).getPkId())
                        .tradeType(ETradeType.RECOIL_INCOME_GRANT.getValue())
                        .tradeClassify(ETradeClassify.INCOME.getValue())
                        .pkRate(currencyMap.get(newMember.getPkSettleCountry()).getPkId())
                        .tradeAmount(newAmount)
                        .sourcePkMember(newMember.getPkId())
                        .sourceCode(saOrderExt.getOrderCode())
                        .build();
                cuMemberTradeRecoil.setPkCountry(newMember.getPkSettleCountry());
                cuMemberTradeRecoil.setPkCreator(newMember.getPkId());
                saveList.add(cuMemberTradeRecoil);
            }

            if (CollectionUtil.isNotEmpty(saveList)) {
                R<?> resultR = iCuMemberTradeRecoilServiceApi.insertBatch(saveList);
                if (!resultR.isSuccess()) {
                    return "订单消费币赠送活动保存复消明细失败";
                }
            }
        }
        return null;
    }

    @Override
    public String recoilGiveCancelHandle(SaOrderExt saOrderExt) {
        // 查询会员信息
        CuMember cuMember = iMemberServiceApi.queryMember(saOrderExt.getPkMember()).getData();
        if (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 升级订单撤单，需要校验是否需要删除数据
            if (cuMember.getPkSettleGrade().equals(saOrderExt.getOrderPkGrade())) {
                // 会员撤单前后等级一样，不需要处理
                return null;
            }
            if (iCuMemberTradeRecoilServiceApi.deleteUpdateBatch(saOrderExt.getPkMember(), cuMember.getPkSettleGrade()).isSuccess()) {
                return null;
            }
        } else {
            if (iCuMemberTradeRecoilServiceApi.deleteBatch(saOrderExt.getPkMember(), saOrderExt.getOrderCode()).isSuccess()) {
                return null;
            }
        }
        return "订单消费币赠送活动撤消明细处理失败";
    }

}
