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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.service.*;
import com.hzs.activity.base.vo.AcGiftConfigVO;
import com.hzs.activity.base.vo.BaseConfigVo;
import com.hzs.activity.people.vo.AcBaseConfigVO;
import com.hzs.activity.pick.service.IAcPickService;
import com.hzs.activity.recommend.dto.AcRecommendUpgrade;
import com.hzs.activity.recommend.mapper.AcRepurCouponsRuleConfigMapper;
import com.hzs.activity.recommend.param.AcRecommendParam;
import com.hzs.activity.recommend.service.*;
import com.hzs.activity.recommend.vo.*;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.RabbitMqConstants;
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.*;
import com.hzs.common.domain.activity.base.ext.AcGiftConfigExt;
import com.hzs.common.domain.activity.recommend.*;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.product.IProductServiceApi;
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.BusinessLogDTO;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 直推配置 服务实现类
 */
@Slf4j
@Service
public class AcRepurCouponsRuleConfigServiceImpl extends ServiceImpl<AcRepurCouponsRuleConfigMapper, AcRepurCouponsRuleConfig> implements IAcRepurCouponsRuleConfigService {

    @Autowired
    IActivityService iActivityService;
    @Autowired
    IAcRecomUpgradeRuleConfigService recomUpgradeRuleConfigService;
    @Autowired
    IAcGiftConfigService giftConfigService;
    @Autowired
    IAcBaseConfigService baseConfigService;
    @Autowired
    IAcApprovalLogService acApprovalLogService;
    @Autowired
    IAcRecomUpgradeRecordService acRecomUpgradeRecordService;
    @Autowired
    IAcPickService acPickService;
    @Autowired
    IAcGoalMemberConfigService acGoalMemberConfigService;
    @Autowired
    IAcRepurSharOrderTypeService acRepurSharOrderTypeService;
    @Autowired
    IAcRepurSharRuleConfigService acRepurSharRuleConfigService;
    @Autowired
    IAcBaseAuthorityService iAcBaseAuthorityService;

    @DubboReference
    IApprovalServiceApi approvalServiceApi;
    @DubboReference
    IMemberServiceApi memberServiceApi;
    @DubboReference
    IProductServiceApi productServiceApi;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean onLinePetition(AcRecommendParam recommendParam) {
        EApprovalBusiness approvalBusiness = EApprovalBusiness.DIRECT_PUSH_GIFT;
        //根据产品ID查询产品名称
        List<AcRecommendUpgradeVO> recommendUpgradeList = recommendParam.getRecommendUpgradeList();
        if (CollUtil.isNotEmpty(recommendUpgradeList)) {
            for (AcRecommendUpgradeVO recommendUpgradeVO : recommendUpgradeList) {
                List<AcGiftConfigVO> giftConfigList = recommendUpgradeVO.getGiftConfigList();
                if (CollUtil.isNotEmpty(giftConfigList)) {
                    for (AcGiftConfigVO giftConfigVO : giftConfigList) {
                        Integer pkProduct = giftConfigVO.getPkProduct();
                        if (null != pkProduct) {
                            giftConfigVO.setProductName(productServiceApi.getProduct(pkProduct).getData().getProductName());
                        }
                    }
                }
            }
        }
        //业务单号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        //提交审批
        Boolean result = submitApproval(recommendParam, approvalBusiness, businessCode);
        packageRecommendOperationLog(recommendParam, approvalBusiness, businessCode);
        return result;
    }


    /**
     * 直推赠送操作日志
     *
     * @param param            入参
     * @param approvalBusiness 业务类型
     * @param businessCode     业务代码
     */
    private void packageRecommendOperationLog(AcRecommendParam param, EApprovalBusiness approvalBusiness, String businessCode) {
        //活动的基本信息
        ActivityParam activityParam = param.getActivityParam();
        //推荐升级
        List<AcRecommendUpgradeVO> recommendUpgradeList = param.getRecommendUpgradeList();
        //直推复购券
        List<AcRepurchaseCouponsShowVO> repurchaseCouponsShowList = param.getRepurchaseCouponsShowList();
        //复购均分
        AcRecommendSharVO acRecommendSharVO = param.getAcRecommendSharVO();
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EControlType.values());
        Integer controlType = param.getControlType();
        controlType = null == controlType ? EControlType.SAVE.getValue() : controlType;
        StringBuilder sb = new StringBuilder();
        sb.append("活动名称：").append(activityParam.getActName())
                .append(" 活动说明：").append(activityParam.getActExplain())
                .append(" 活动时间：").append(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, activityParam.getActStartDate())).append(" 至 ")
                .append(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, activityParam.getActEndDate()))
                .append(" 业务类型：");
        if (CollUtil.isNotEmpty(recommendUpgradeList)) {
            sb.append(EApprovalBusiness.DIRECT_PUSH_UPGRADE.getLabel()).append(" ");
        }
        if (CollUtil.isNotEmpty(repurchaseCouponsShowList)) {
            sb.append(EApprovalBusiness.REPURCHASE_COUPON.getLabel()).append(" ");
        }
        if (null != acRecommendSharVO && CollUtil.isNotEmpty(acRecommendSharVO.getOrderTypeList())) {
            sb.append(EApprovalBusiness.REPURCHASE_SHAR.getLabel());
        }
        sb.append(" 操作类型：").append(transactionMap.get(EnumsPrefixConstants.CONTROL_TYPE + controlType));
        BusinessLogDTO businessLog = BusinessLogDTO.builder()
                .businessType(approvalBusiness.getValue())
                .businessCode(businessCode)
                .content(sb.toString()).pkCreator(param.getPkMember())
                .pkCountry(param.getPkCountry())
                .freeSignFlag(false).build();
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, Collections.singleton(businessLog));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    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())) {
                return saveRecommendData(recommendParam);
            } else if (controlType.equals(EControlType.MODIFY.getValue())) {
                deleteRecommendData(recommendParam);
                return saveRecommendData(recommendParam);
            } else {
                deleteRecommendData(recommendParam);
            }
        }
        //更新审批状态
        acApprovalLogService.updateApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry(),
                loginUser.getUserId(), EApproveRechargeStatus.AGREE, businessResult.getApproveRemark());
        return null;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    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;
    }

    /**
     * 保存直推赠送数据
     *
     * @param recommendParam 入参
     * @return String
     */
    private String saveRecommendData(AcRecommendParam recommendParam) {
        //保存活动基本信息
        String message = saveBaseConfig(recommendParam);
        //保存复购券配置信息
        saveRepurchaseCouponsInfo(recommendParam);
        //保存直推升级配置信息
        saveRecommendUpgradeRuleInfo(recommendParam);
        //保存复购均分
        saveRepurchaseSharInfo(recommendParam);
        // 保存活动权限
        this.saveAuthority(recommendParam);
        return message;
    }

    /**
     * 删除直推赠送数据
     *
     * @param recommendParam 入参
     * @return String
     */
    public String deleteRecommendData(AcRecommendParam recommendParam) {
        Long pkBaseId = recommendParam.getActivityParam().getPkId();
        Long pkModifyId = recommendParam.getPkMember();
        //删除活动基本信息
        baseConfigService.deleteBaseConfigById(pkBaseId, pkModifyId);
        // 删除活动权限配置
        iAcBaseAuthorityService.update(Wrappers.<AcBaseAuthority>lambdaUpdate()
                .eq(AcBaseAuthority::getPkBaseId, pkBaseId)
                .eq(AcBaseAuthority::getDelFlag, EDelFlag.UN_DELETE.getValue())
                .set(AcBaseAuthority::getDelFlag, EDelFlag.DELETE.getValue())
        );
        acGoalMemberConfigService.deleteGoalMemberConfig(pkBaseId, pkModifyId);
        //删除复购券配置信息
        List<AcRepurchaseCouponsShowVO> repurchaseCouponsShowList = recommendParam.getRepurchaseCouponsShowList();
        if (CollUtil.isNotEmpty(repurchaseCouponsShowList)) {
            deleteCouponsRuleConfigByBaseId(pkBaseId, pkModifyId);
        }
        //删除直推升级配置信息
        List<AcRecommendUpgradeVO> recommendUpgradeList = recommendParam.getRecommendUpgradeList();
        if (CollUtil.isNotEmpty(recommendUpgradeList)) {
            recomUpgradeRuleConfigService.deleteUpgradeRuleConfigByBaseId(pkBaseId, pkModifyId);
        }
        //删除复购均分
        AcRecommendSharVO acRecommendSharVO = recommendParam.getAcRecommendSharVO();
        if (null != acRecommendSharVO && CollUtil.isNotEmpty(acRecommendSharVO.getOrderTypeList())) {
            AcRepurSharRuleConfig repurSharRuleConfig = acRepurSharRuleConfigService.selectAcRepurSharRuleConfigByBaseId(pkBaseId);
            if (null == repurSharRuleConfig) {
                return "复购均分规则配置不存在！";
            }
            acRepurSharRuleConfigService.deleteSharRuleConfigByActivityId(pkBaseId, pkModifyId);
            acRepurSharOrderTypeService.deleteSharOrderTypeByRuleId(repurSharRuleConfig.getPkId(), pkModifyId);
        }
        return null;
    }


    /**
     * 保存活动基本信息
     *
     * @param recommendParam 入参
     * @return
     */
    private String saveBaseConfig(AcRecommendParam recommendParam) {
        ActivityParam activityParam = recommendParam.getActivityParam();
        if (null == activityParam) {
            return "没有活动的基本信息！";
        }
        List<AcRecommendUpgradeVO> recommendUpgradeList = recommendParam.getRecommendUpgradeList();
        if (CollUtil.isNotEmpty(recommendUpgradeList)) {
            activityParam.setAtcModule(EActModule.DIRECT_PUSH_UPGRADE.getValue());
        }
        activityParam.setActType(EActType.DIRECT_PUSH_GIFT.getValue());
        //保存基础配置
        activityParam.setPkCreator(recommendParam.getPkMember());
        activityParam.setPkCountry(recommendParam.getPkCountry());
        AcBaseConfig acBaseConfig = iActivityService.saveBaseConfig(activityParam);
        recommendParam.setPkBaseId(acBaseConfig.getPkId());
        iActivityService.saveGoalMemberConfig(activityParam, acBaseConfig);

        return null;
    }


    /**
     * 保存复购券配置信息
     *
     * @param recommendParam 入参
     * @return Boolean
     */
    private Boolean saveRepurchaseCouponsInfo(AcRecommendParam recommendParam) {
        List<AcRepurCouponsRuleConfig> repurCouponsRuleConfigList = new ArrayList<>();
        List<AcRepurchaseCouponsShowVO> repurchaseCouponsShowList = recommendParam.getRepurchaseCouponsShowList();
        if (CollUtil.isNotEmpty(repurchaseCouponsShowList)) {
            for (AcRepurchaseCouponsShowVO repurchaseCouponsShowVO : repurchaseCouponsShowList) {
                repurCouponsRuleConfigList.addAll(getRepurchaseCouponsRuleConfig(recommendParam, repurchaseCouponsShowVO));
            }

        }
        return saveBatch(repurCouponsRuleConfigList);
    }


    /**
     * 保存复购均分配置信息
     *
     * @param recommendParam 入参
     * @return Boolean
     */
    private Boolean saveRepurchaseSharInfo(AcRecommendParam recommendParam) {
        AcRecommendSharVO acRecommendSharVO = recommendParam.getAcRecommendSharVO();
        Long pkBaseId = recommendParam.getPkBaseId();
        if (null != acRecommendSharVO) {
            List<Integer> orderTypeList = acRecommendSharVO.getOrderTypeList();
            if (CollUtil.isNotEmpty(orderTypeList)) {
                AcRepurSharRuleConfig repurSharRuleConfig = AcRepurSharRuleConfig.builder().pkBaseId(pkBaseId)
                        .orderAmount(acRecommendSharVO.getOrderAmount()).orderAchieve(acRecommendSharVO.getOrderAchieve())
                        .ratioValue(acRecommendSharVO.getRatioValue()).build();
                repurSharRuleConfig.setPkCreator(recommendParam.getPkMember());
                repurSharRuleConfig.setPkCountry(recommendParam.getPkCountry());
                //复购券均分-规则配置信息
                acRepurSharRuleConfigService.save(repurSharRuleConfig);

                AcRepurSharOrderType repurSharOrderType;
                List<AcRepurSharOrderType> sharOrderTypes = new ArrayList<>();
                for (Integer orderType : orderTypeList) {
                    repurSharOrderType = AcRepurSharOrderType.builder().pkRuleId(repurSharRuleConfig.getPkId())
                            .orderType(orderType).build();
                    repurSharOrderType.setPkCreator(recommendParam.getPkMember());
                    repurSharOrderType.setPkCountry(recommendParam.getPkCountry());
                    sharOrderTypes.add(repurSharOrderType);
                }
                //复购券均分-订单类型
                acRepurSharOrderTypeService.saveBatch(sharOrderTypes);
            }
        }
        return true;
    }

    /**
     * 保存活动权限
     *
     * @param recommendParam
     */
    private void saveAuthority(AcRecommendParam recommendParam) {
        List<AcBaseAuthority> authorityList = recommendParam.getAuthorityList();
        if (CollectionUtil.isNotEmpty(authorityList)) {
            for (AcBaseAuthority acBaseAuthority : authorityList) {
                acBaseAuthority.setPkBaseId(recommendParam.getPkBaseId());
            }
            iAcBaseAuthorityService.saveBatch(authorityList);
        }
    }

    /**
     * 每个专区复购券规则配置
     *
     * @param recommendParam          直推赠送
     * @param repurchaseCouponsShowVO 专区复购券规则
     * @return List<AcRepurCouponsRuleConfig>
     */
    private List<AcRepurCouponsRuleConfig> getRepurchaseCouponsRuleConfig(AcRecommendParam recommendParam, AcRepurchaseCouponsShowVO repurchaseCouponsShowVO) {
        AcRepurCouponsRuleConfig repurCouponsRuleConfig;
        List<AcRepurCouponsRuleConfig> repurCouponsRuleConfigList = new ArrayList<>();
        //专区
        Integer orderType = repurchaseCouponsShowVO.getOrderType();
        List<AcRepurchaseCouponsVO> repurchaseCouponsList = repurchaseCouponsShowVO.getRepurchaseCouponsList();
        if (CollUtil.isNotEmpty(repurchaseCouponsList)) {
            //循环每个专区
            for (AcRepurchaseCouponsVO repurchaseCouponsVO : repurchaseCouponsList) {
                repurCouponsRuleConfig = AcRepurCouponsRuleConfig.builder().pkBaseId(recommendParam.getPkBaseId())
                        .orderType(orderType).orderAmount(repurchaseCouponsVO.getOrderAmount())
                        .orderAchieve(repurchaseCouponsVO.getOrderAchieve()).ratioType(repurchaseCouponsVO.getRatioType())
                        .ratioValue(repurchaseCouponsVO.getRatioValue()).build();
                repurCouponsRuleConfig.setPkCreator(recommendParam.getPkMember());
                repurCouponsRuleConfig.setPkCountry(recommendParam.getPkCountry());
                repurCouponsRuleConfigList.add(repurCouponsRuleConfig);
            }
        }
        return repurCouponsRuleConfigList;
    }


    /**
     * 保存直推升级配置信息
     *
     * @param recommendParam 直推信息
     * @return Boolean
     */
    private Boolean saveRecommendUpgradeRuleInfo(AcRecommendParam recommendParam) {
        AcRecomUpgradeRuleConfig recomUpgradeRuleConfig;
        //直推升级规则配置
        List<AcRecommendUpgradeVO> recommendUpgradeList = recommendParam.getRecommendUpgradeList();
        if (CollUtil.isNotEmpty(recommendUpgradeList)) {
            for (AcRecommendUpgradeVO recommendUpgradeVO : recommendUpgradeList) {
                recommendUpgradeVO.setPkCreator(recommendParam.getPkMember());
                recommendUpgradeVO.setPkCountry(recommendParam.getPkCountry());
                recomUpgradeRuleConfig = BeanUtil.copyProperties(recommendUpgradeVO, AcRecomUpgradeRuleConfig.class);
                recomUpgradeRuleConfig.setPkBaseId(recommendParam.getPkBaseId());
                recomUpgradeRuleConfigService.save(recomUpgradeRuleConfig);
                List<AcGiftConfig> giftConfigs = saveRecommendUpgradeGift(recommendUpgradeVO, recomUpgradeRuleConfig.getPkId());
                giftConfigService.saveBatch(giftConfigs);
            }
        }
        return true;
    }


    /**
     * 提交审批
     *
     * @param recommendParam 直推赠送参数
     */
    public Boolean submitApproval(AcRecommendParam recommendParam, EApprovalBusiness approvalBusiness, String businessCode) {
        //保存审批日志
        AcApprovalLog approvalLog = saveApprovalLog(recommendParam, approvalBusiness, businessCode);
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(approvalBusiness)
                .businessCode(approvalLog.getBusinessCode())
                .signType(ESignType.getEnumByValue(recommendParam.getSignType())).userIdList(recommendParam.getUserIdList())
                .sendIdList(recommendParam.getSendIdList()).remark(recommendParam.getRemark()).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, String businessCode) {
        String detailJson = null;
        Integer controlType = recommendParam.getControlType();
        //查询变更前的数据
        Long pkBaseId = recommendParam.getActivityParam().getPkId();
        if (null != pkBaseId) {
            String detail = JSONUtil.toJsonStr(showDetailInfo(pkBaseId, recommendParam.getPkCountry()));
            detailJson = null != detail ? JSONUtil.toJsonStr(detail) : null;
        }
        String afterData = JSONUtil.toJsonStr(recommendParam);
        String beforeData = controlType.equals(EControlType.MODIFY.getValue()) ? detailJson : null;
        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;
    }

    /**
     * 直推升级赠品
     *
     * @param recommendUpgradeVO 直推升级赠品VO
     * @param pkRuleId           规则ID
     * @return List<AcGiftConfig>
     */
    public List<AcGiftConfig> saveRecommendUpgradeGift(AcRecommendUpgradeVO recommendUpgradeVO, Long pkRuleId) {
        AcGiftConfig giftConfig;
        List<AcGiftConfig> giftConfigList = new ArrayList<>();
        List<AcGiftConfigVO> giftConfigVOList = recommendUpgradeVO.getGiftConfigList();
        if (CollUtil.isNotEmpty(giftConfigVOList)) {
            for (AcGiftConfigVO giftConfigVO : giftConfigVOList) {
                if (null == giftConfigVO.getPkProduct()) {
                    continue;
                }
                giftConfig = BeanUtil.copyProperties(giftConfigVO, AcGiftConfig.class);
                giftConfig.setPkCreator(recommendUpgradeVO.getPkCreator());
                giftConfig.setPkCountry(recommendUpgradeVO.getPkCountry());
                giftConfig.setPkRuleId(pkRuleId);
                giftConfig.setActType(EActType.DIRECT_PUSH_GIFT.getValue());
                giftConfigList.add(giftConfig);
            }
        }
        return giftConfigList;
    }

    @Override
    public AcRecommendVO showDetailInfo(Long activityId, Integer pkCountry) {
        AcRecommendVO recommendVO = new AcRecommendVO();
        recommendVO.setPkBaseId(activityId);
        AcBaseConfig baseConfig = baseConfigService.getById(activityId);
        //查询目标用户群体
        List<AcGoalMemberConfig> acGoalMemberConfigs = acGoalMemberConfigService.selectMemberConfig(activityId);
        BaseConfigVo baseConfigVo = BeanUtil.copyProperties(baseConfig, BaseConfigVo.class);
        baseConfigVo.setGoalMemberConfigList(acGoalMemberConfigs);

        recommendVO.setPkBaseId(baseConfig.getPkId());
        recommendVO.setActivityParam(baseConfigVo);

        // 查询活动权限
        recommendVO.setAuthorityList(iAcBaseAuthorityService.listAuthority(activityId));
        //查询复购券规则
        List<AcRepurCouponsRuleConfig> repurCouponsRuleConfigList = selectRuleConfigByActivityId(activityId);
        recommendVO.setRepurchaseCouponsShowList(conversionAcRepurchaseCouponsShowVO(repurCouponsRuleConfigList));
        //查询直推升级规则
        List<AcRecomUpgradeRuleConfig> recomUpgradeRuleConfigList = recomUpgradeRuleConfigService.selectByActivityId(activityId);
        recommendVO.setRecommendUpgradeList(conversionRecommendUpgradeVO(recomUpgradeRuleConfigList, pkCountry));
        //复购券均分
        AcRepurSharRuleConfig repurSharRuleConfig = acRepurSharRuleConfigService.selectAcRepurSharRuleConfigByBaseId(activityId);
        if (null != repurSharRuleConfig) {
            List<AcRepurSharOrderType> repurSharOrderTypes = acRepurSharOrderTypeService.selectSharOrderByRuleId(repurSharRuleConfig.getPkId());
            //订单类型
            List<Integer> orderTypeList = repurSharOrderTypes.stream().map(AcRepurSharOrderType::getOrderType).collect(Collectors.toList());

            AcRecommendSharVO recommendSharVO = BeanUtil.copyProperties(repurSharRuleConfig, AcRecommendSharVO.class);
            recommendSharVO.setOrderTypeList(orderTypeList);
            recommendVO.setAcRecommendSharVO(recommendSharVO);
        }

        return recommendVO;
    }

    /**
     * 转化推荐升级
     *
     * @param recomUpgradeRuleConfigList 推荐升级
     * @param pkCountry                  国家ID
     * @return List<AcRecommendUpgradeVO>
     */
    private List<AcRecommendUpgradeVO> conversionRecommendUpgradeVO(List<AcRecomUpgradeRuleConfig> recomUpgradeRuleConfigList, Integer pkCountry) {
        List<AcRecommendUpgradeVO> recommendUpgradeVOList = new ArrayList<>();
        if (CollUtil.isNotEmpty(recomUpgradeRuleConfigList)) {
            AcRecommendUpgradeVO acRecommendUpgradeVO;
            List<Long> ruleId = recomUpgradeRuleConfigList.stream().map(AcRecomUpgradeRuleConfig::getPkId).collect(Collectors.toList());
            Map<Long, List<AcGiftConfigExt>> listMap = giftConfigService.queryListByRuleIdList(ruleId, pkCountry);
            for (AcRecomUpgradeRuleConfig recomUpgradeRuleConfig : recomUpgradeRuleConfigList) {
                acRecommendUpgradeVO = BeanUtil.copyProperties(recomUpgradeRuleConfig, AcRecommendUpgradeVO.class);
                //赠品
                List<AcGiftConfigVO> giftConfigList = BeanUtil.copyToList(listMap.get(recomUpgradeRuleConfig.getPkId()), AcGiftConfigVO.class);
                acRecommendUpgradeVO.setGiftConfigList(giftConfigList);
                recommendUpgradeVOList.add(acRecommendUpgradeVO);
            }
        }
        return recommendUpgradeVOList;
    }

    /**
     * 转化直推复购券VO
     *
     * @param repurCouponsRuleConfigList 直推复购券
     * @return List<AcRepurchaseCouponsShowVO>
     */
    private List<AcRepurchaseCouponsShowVO> conversionAcRepurchaseCouponsShowVO(List<AcRepurCouponsRuleConfig> repurCouponsRuleConfigList) {
        List<AcRepurchaseCouponsShowVO> showVOList = new ArrayList<>();
        AcRepurchaseCouponsShowVO repurchaseCouponsShowVO;
        if (CollUtil.isNotEmpty(repurCouponsRuleConfigList)) {
            AcRepurchaseCouponsVO acRepurchaseCouponsVO;
            List<AcRepurchaseCouponsVO> repurchaseCouponsVOList;
            //转换每个专区的配置
            Map<Integer, List<AcRepurCouponsRuleConfig>> map = repurCouponsRuleConfigList.stream().collect(Collectors.groupingBy(AcRepurCouponsRuleConfig::getOrderType));
            //封装AcRepurchaseCouponsShowVO
            for (Map.Entry<Integer, List<AcRepurCouponsRuleConfig>> entry : map.entrySet()) {
                repurchaseCouponsShowVO = new AcRepurchaseCouponsShowVO();
                repurchaseCouponsVOList = new ArrayList<>();
                //循环每个分区
                repurchaseCouponsShowVO.setOrderType(entry.getKey());
                for (AcRepurCouponsRuleConfig repurCouponsRuleConfig : entry.getValue()) {
                    acRepurchaseCouponsVO = BeanUtil.copyProperties(repurCouponsRuleConfig, AcRepurchaseCouponsVO.class);
                    repurchaseCouponsVOList.add(acRepurchaseCouponsVO);
                }
                repurchaseCouponsShowVO.setRepurchaseCouponsList(repurchaseCouponsVOList);
                showVOList.add(repurchaseCouponsShowVO);
            }
        }
        return showVOList;
    }

    public List<AcRepurCouponsRuleConfig> selectRuleConfigByActivityId(Long activityId) {
        LambdaQueryWrapper<AcRepurCouponsRuleConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AcRepurCouponsRuleConfig::getPkBaseId, activityId);
        return baseMapper.selectList(queryWrapper);
    }


    @Override
    public Boolean deleteRecommendConfig(Long activityId) {
        return null;
    }

    @Override
    public Boolean updateRecommendConfig(AcRecommendVO recommendVO) {
        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean invokeRecommendUpgrade(AcRecommendUpgrade acRepurchaseCouponsDTO) {
        boolean result = true;
        SaOrderExt saOrderExt = acRepurchaseCouponsDTO.getSaOrderExt();
        AcBaseConfigVO baseConfigVO = AcBaseConfigVO.builder().actType(EActType.DIRECT_PUSH_GIFT.getValue())
                .pkCountry(saOrderExt.getPkCountry())
                .atcModule(EActModule.DIRECT_PUSH_UPGRADE.getValue()).build();
        //查询活动
        List<AcBaseConfig> acBaseConfigs = baseConfigService.selectBaseConfigByType(baseConfigVO);
        if (CollUtil.isNotEmpty(acBaseConfigs)) {
            EOrderOperateStatus orderOperateStatus = acRepurchaseCouponsDTO.getOrderOperateStatus();
            for (AcBaseConfig baseConfig : acBaseConfigs) {
                if (orderOperateStatus.equals(EOrderOperateStatus.NORMAL)) {
                    result = handleBusiness(acRepurchaseCouponsDTO, baseConfig);
                } else {
                    result = cancelOrder(acRepurchaseCouponsDTO, baseConfig);
                }
            }
        }
        return result;
    }

    /**
     * 校验活动权限（true：进行处理，false：不进行处理）
     *
     * @param baseConfig 活动配置
     * @param pkMember   会员ID
     * @return
     */
    private boolean checkAuthority(AcBaseConfig baseConfig, Long pkMember) {
        List<AcBaseAuthority> authList = iAcBaseAuthorityService.list(Wrappers.<AcBaseAuthority>lambdaQuery()
                .eq(AcBaseAuthority::getPkBaseId, baseConfig.getPkId())
                .orderByDesc(AcBaseAuthority::getAuthorityType)
        );
        if (CollectionUtil.isNotEmpty(authList)) {
            Map<Integer, List<String>> authMap = new HashMap<>();
            for (AcBaseAuthority authority : authList) {
                authMap.computeIfAbsent(authority.getAuthorityType(), k -> new ArrayList<>());
                authMap.get(authority.getAuthorityType()).add(authority.getMemberCode());
            }

            for (Integer key : authMap.keySet()) {
                List<String> memberCodeList = authMap.get(key);
                switch (EWaresPermissionType.getEnumByValue(key)) {
                    case AUTH_ORITY_TYPE:
                        // 全部
                        return true;
                    case PLACE_STOP:
                        // 安置禁止
                        if (iAcBaseAuthorityService.checkPlaceParent(pkMember, memberCodeList) > 0) {
                            return false;
                        } else {
                            return true;
                        }
                    case BLOOD_STOP:
                        // 血缘禁止
                        if (iAcBaseAuthorityService.checkParent(pkMember, memberCodeList) > 0) {
                            return false;
                        } else {
                            return true;
                        }
                    case PLACE_ALLWO:
                        // 安置可见
                        if (iAcBaseAuthorityService.checkPlaceParent(pkMember, memberCodeList) > 0) {
                            return true;
                        } else {
                            return false;
                        }
                    case BLOOD_ALLOW:
                        // 血缘可见
                        if (iAcBaseAuthorityService.checkParent(pkMember, memberCodeList) > 0) {
                            return true;
                        } else {
                            return false;
                        }
                    default:
                }
            }
        }
        return true;
    }

    @Override
    public List<AcRepurCouponsRuleConfig> queryAcRepurchaseCouponsRule(Date settleDate) {
        return baseMapper.queryAcRepurchaseCouponsRule(settleDate);
    }

    /**
     * 处理业务(正常报单)
     *
     * @param acRecommendUpgrade 升级参数
     * @param baseConfig         基本配置
     */
    private Boolean handleBusiness(AcRecommendUpgrade acRecommendUpgrade, AcBaseConfig baseConfig) {
        SaOrderExt saOrderExt = acRecommendUpgrade.getSaOrderExt();
        //活动ID
        Long pkBaseId = baseConfig.getPkId();
        //推荐人
        Long pkMember = saOrderExt.getPkReference();
        //推荐人等级ID
        Integer pkSettleGrade = memberServiceApi.queryMember(pkMember).getData().getPkSettleGrade();
        //被推荐人等级ID
        Integer pkRecommendGrade = memberServiceApi.queryMember(saOrderExt.getPkMember()).getData().getPkSettleGrade();
        //国家
        Integer pkCountry = saOrderExt.getPkCountry();
        AcRecommendUpgradeVO recommendUpgradeVO = AcRecommendUpgradeVO.builder().pkCountry(pkCountry)
                .pkBaseId(pkBaseId).memberType(1).pkSettleGrade(pkSettleGrade)
                .pkRecommendGrade(pkRecommendGrade).build();
        //查询规则
        List<AcRecomUpgradeRuleConfig> recomUpgradeRuleConfigList = recomUpgradeRuleConfigService.selectRuleConfig(recommendUpgradeVO);
        if (CollUtil.isNotEmpty(recomUpgradeRuleConfigList)) {
            AcRecomUpgradeRuleConfig recomUpgradeRuleConfig = recomUpgradeRuleConfigList.get(0);
            //正常报单
            Long pkRuleId = recomUpgradeRuleConfig.getPkId();
            //插入业务表
            AcRecomUpgradeRecord recomUpgradeRecord = AcRecomUpgradeRecord.builder().pkBaseId(pkBaseId)
                    .pkRuleId(pkRuleId).pkMember(pkMember)
                    .pkSettleGrade(pkSettleGrade).pkRecommendGrade(pkRecommendGrade)
                    .pkOrderId(saOrderExt.getPkId()).build();
            recomUpgradeRecord.setPkCountry(pkCountry);
            recomUpgradeRecord.setPkCreator(pkMember);
            acRecomUpgradeRecordService.save(recomUpgradeRecord);

            // 查询活动权限
            if (!this.checkAuthority(baseConfig, saOrderExt.getPkReference())) {
                return true;
            }
            log.info("直推升级权限校验，pkBaseId: {}，orderCode: {}", pkBaseId, saOrderExt.getOrderCode());

            //满足规则时 直推升级
            AcRecomUpgradeRecordExt upgradeRecord = new AcRecomUpgradeRecordExt();
            upgradeRecord.setPkMember(pkMember);
            upgradeRecord.setPkBaseId(pkBaseId);
            upgradeRecord.setPkRuleId(pkRuleId);
            upgradeRecord.setPkSettleGrade(recomUpgradeRuleConfig.getPkSettleGrade());
            upgradeRecord.setPkRecommendGrade(recomUpgradeRuleConfig.getPkRecommendGrade());
            upgradeRecord.setStartDate(baseConfig.getActStartDate());
            upgradeRecord.setEndDate(baseConfig.getActEndDate());
            upgradeRecord.setPkCountry(pkCountry);
            upgradeRecord.setUpgradeStatus(0);
            //查询推荐人数ID(没有升级过记录)
            List<Long> recommendNumber = acRecomUpgradeRecordService.selectRecommendNumber(upgradeRecord);
            //配置中的人数
            Integer configNumber = recomUpgradeRuleConfig.getRecommendNumber();
            if (CollUtil.isNotEmpty(recommendNumber) && configNumber.equals(recommendNumber.size())) {
                //更新为已升级过的推荐状态
                acRecomUpgradeRecordService.updateUpgradeStatusById(recommendNumber, pkMember, EYesNo.NO.getIntValue());
                //升级等级
                Integer pkUpgradeGrade = recomUpgradeRuleConfig.getPkUpgradeGrade();
                CuMember data = memberServiceApi.getMember(pkMember).getData();
                //用户信息
                CuMember cuMember = CuMember.builder().pkId(pkMember).pkSettleGrade(pkUpgradeGrade).memberCode(data.getMemberCode())
                        .pkSettleCountry(data.getPkSettleCountry()).build();
                cuMember.setPkModified(pkMember);
                cuMember.setModifiedTime(new Date());
                SaOrder saOrder = SaOrder.builder().payTime(new Date()).build();
                //查询是否配置赠品
                List<AcGiftConfigExt> acGiftConfigList = giftConfigService.queryListByRuleIdList(pkRuleId, pkCountry);
                //调用提货接口
                if (CollUtil.isNotEmpty(acGiftConfigList)) {
                    AcGiftConfigExt acGiftConfigExt = acGiftConfigList.get(0);
                    acPickService.addPickByActivity(pkMember, EActType.DIRECT_PUSH_GIFT.getValue(),
                            baseConfig.getPkId(), pkRuleId, acGiftConfigExt.getQuantity(), baseConfig.getActCover(), null,
                            null, pkMember, pkCountry, baseConfig.getPkId(), null, null);
                }
                //调用升级接口
                return memberServiceApi.updateMemberLevel(cuMember, saOrder, pkSettleGrade).getData();
            }
        }
        return true;

    }


    /**
     * 撤单
     */
    private Boolean cancelOrder(AcRecommendUpgrade acRecommendUpgrade, AcBaseConfig baseConfig) {
        SaOrderExt saOrderExt = acRecommendUpgrade.getSaOrderExt();
        Long pkOrderId = saOrderExt.getPkId();
        //修改人
        Long pkModified = saOrderExt.getPkReference();
        AcRecomUpgradeRecordExt upgradeRecordOrder = new AcRecomUpgradeRecordExt();
        upgradeRecordOrder.setPkOrderId(pkOrderId);
        upgradeRecordOrder.setStartDate(baseConfig.getActStartDate());
        upgradeRecordOrder.setEndDate(baseConfig.getActEndDate());
        //根据orderId查询
        AcRecomUpgradeRecord recomUpgradeRecord = acRecomUpgradeRecordService.selectUpgradeRecordByOrderId(upgradeRecordOrder);
        if (null != recomUpgradeRecord) {
            Long pkRuleId = recomUpgradeRecord.getPkRuleId();
            //查询规则
            AcRecomUpgradeRuleConfig upgradeRuleConfig = recomUpgradeRuleConfigService.getById(pkRuleId);
            //结算等级
            Integer pkSettleGrade = upgradeRuleConfig.getPkSettleGrade();
            //找茬等级
            Integer pkRecommendGrade = upgradeRuleConfig.getPkRecommendGrade();
            if (pkSettleGrade.equals(recomUpgradeRecord.getPkSettleGrade()) && pkRecommendGrade.equals(recomUpgradeRecord.getPkRecommendGrade())) {
                //撤单更新状态
                acRecomUpgradeRecordService.cancelOrder(pkOrderId, pkModified);
                AcRecomUpgradeRecordExt upgradeRecord = BeanUtil.copyProperties(recomUpgradeRecord, AcRecomUpgradeRecordExt.class);
                upgradeRecord.setPkSettleGrade(pkSettleGrade);
                upgradeRecord.setPkRecommendGrade(pkRecommendGrade);
                upgradeRecord.setStartDate(baseConfig.getActStartDate());
                upgradeRecord.setEndDate(baseConfig.getActEndDate());
                upgradeRecord.setUpgradeStatus(1);
                //推荐人数
                List<Long> recommendNumber = acRecomUpgradeRecordService.selectRecommendNumber(upgradeRecord);
                //配置的推荐人数
                Integer recommendConfigNumber = upgradeRuleConfig.getRecommendNumber();
                if (CollUtil.isNotEmpty(recommendNumber) && recommendNumber.size() < recommendConfigNumber) {
                    Long pkMember = recomUpgradeRecord.getPkMember();
                    //调用降级处理
                    Integer pkUpgradeGrade = upgradeRuleConfig.getPkUpgradeGrade();
                    CuMember data = memberServiceApi.getMember(pkMember).getData();
                    //用户信息
                    CuMember cuMember = CuMember.builder().pkId(pkMember).pkSettleGrade(pkSettleGrade).memberCode(data.getMemberCode())
                            .pkSettleCountry(data.getPkSettleCountry()).build();
                    cuMember.setPkModified(pkMember);
                    cuMember.setModifiedTime(new Date());
                    SaOrder saOrder = SaOrder.builder().payTime(new Date()).build();
                    //修改升级状态
                    acRecomUpgradeRecordService.updateUpgradeStatusById(recommendNumber, pkModified, EYesNo.YES.getIntValue());
                    //查询是否配置赠品
                    List<AcGiftConfigExt> acGiftConfigList = giftConfigService.queryListByRuleIdList(pkRuleId, saOrderExt.getPkCountry());
                    //调用提货接口
                    if (CollUtil.isNotEmpty(acGiftConfigList)) {
                        AcGiftConfigExt acGiftConfigExt = acGiftConfigList.get(0);
                        acPickService.updatePickUsableByMemberAndActivityType(pkMember, EActType.DIRECT_PUSH_GIFT.getValue(), baseConfig.getPkId(), pkRuleId
                                , acGiftConfigExt.getQuantity(), pkModified);
                    }
                    //调用降级处理
                    memberServiceApi.updateMemberLevel(cuMember, saOrder, pkUpgradeGrade);
                }
            }
        }
        return true;
    }

    @Override
    public Boolean deleteCouponsRuleConfigByBaseId(Long pkBaseId, Long pkModifyId) {
        LambdaUpdateWrapper<AcRepurCouponsRuleConfig> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(AcRepurCouponsRuleConfig::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(AcRepurCouponsRuleConfig::getPkModified, pkModifyId);
        updateWrapper.set(AcRepurCouponsRuleConfig::getModifiedTime, new Date());
        updateWrapper.eq(AcRepurCouponsRuleConfig::getPkBaseId, pkBaseId);
        return update(updateWrapper);
    }


}
