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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.activity.base.param.*;
import com.hzs.activity.base.service.IAcApprovalLogService;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.vo.BaseConfigVo;
import com.hzs.activity.base.vo.ConsumeRuleConfigVo;
import com.hzs.activity.consume.service.IAcConsumeShieldConfigService;
import com.hzs.activity.consume.service.IAcMemberConsumeRuleService;
import com.hzs.activity.draw.service.IAcDrawGiftRuleConfigService;
import com.hzs.activity.draw.service.IAcDrawRewardNumService;
import com.hzs.activity.draw.service.IAcDrawRuleConfigService;
import com.hzs.activity.draw.vo.AcDrawGiftRuleConfigVo;
import com.hzs.activity.pick.service.IAcPickUpConfigService;
import com.hzs.activity.recommend.dto.AcRecommendUpgrade;
import com.hzs.activity.recommend.param.AcRecommendParam;
import com.hzs.activity.recommend.service.IAcRepurCouponsRuleConfigService;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
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.ComputeUtil;
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.consume.AcConsumeRuleConfig;
import com.hzs.common.domain.activity.consume.AcConsumeShieldConfig;
import com.hzs.common.domain.activity.consume.ext.AcConsumeRuleConfigExt;
import com.hzs.common.domain.activity.consume.ext.AcConsumeShieldConfigExt;
import com.hzs.common.domain.activity.consume.ext.AcMemberConsumeRuleExt;
import com.hzs.common.domain.activity.draw.AcDrawGiftRuleConfig;
import com.hzs.common.domain.activity.draw.AcDrawRuleConfig;
import com.hzs.common.domain.activity.wares.AcWaresRuleConfig;
import com.hzs.common.domain.activity.wares.ext.AcWaresRuleConfigExt;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.classify.BdSpecs;
import com.hzs.common.domain.sale.ext.BdWaresDetailExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.WaresSpecsExt;
import com.hzs.common.domain.sale.wares.BdWares;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.activity.consume.service.IAcConsumeRuleConfigService;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
import com.hzs.activity.wares.service.IAcWaresRuleConfigService;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.product.service.IBdSpecsService;
import com.hzs.sale.wares.service.IBdWaresService;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.sys.dto.BusinessLogDTO;
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.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动配置实现类
 */
@Slf4j
@Service
public class ActivityServiceImpl implements IActivityService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IAcDrawRuleConfigService drawRuleConfigService;
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    private IAcWaresRuleConfigService waresRuleConfigService;
    @Autowired
    private IAcGiftConfigService waresGiftConfigService;
    @Autowired
    private IAcGoalMemberConfigService goalMemberConfigService;
    @Autowired
    private IAcConsumeRuleConfigService consumeRuleConfigService;
    @Autowired
    private IAcConsumeShieldConfigService consumeShieldConfigService;
    @Autowired
    private IAcDrawGiftRuleConfigService drawGiftConfigService;
    @Autowired
    private IAcMemberConsumeRuleService iAcMemberConsumeRuleService;
    @Autowired
    private IAcDrawRewardNumService acDrawRewardNumService;
    @Autowired
    private IAcRepurCouponsRuleConfigService acRepurCouponsRuleConfigService;
    @Autowired
    private IAcPickUpConfigService pickUpConfigService;
    @Autowired
    private IAcApprovalLogService acApprovalLogService;
    @Autowired
    private IBdSpecsService specsService;
    @Autowired
    private IBdWaresService waresService;

    @DubboReference
    IGradeServiceApi gradeServiceApi;
    @DubboReference
    IAwardsServiceApi awardsServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;


    /**
     * 新增活动配置
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveActivity(ActivityParam activityParam) {
        // 增加基础配置
        AcBaseConfig baseConfig = saveBaseConfig(activityParam);
        // 商品买赠配置
        saveWaresRuleConfig(activityParam, baseConfig);
        //目标用户配置
        saveGoalMemberConfig(activityParam, baseConfig);

        return baseConfig.getPkId();
    }

    /**
     * 新增消费赠送规格
     *
     * @param activityParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveConsumptionGift(ActivityParam activityParam) {
        // 增加基础配置
        AcBaseConfig baseConfig = saveBaseConfig(activityParam);
        // 目标群体配置
        saveGoalMemberConfig(activityParam, baseConfig);
        // 消费赠送规格配置
        saveConsumeRuleConfigService(activityParam, baseConfig);
        // 消费赠送屏蔽配置表
        saveConsumeShieldConfig(activityParam, baseConfig);
        return baseConfig.getPkId();
    }

    /**
     * 抽奖提货配置
     *
     * @param activityParam
     * @param baseConfig
     */
    private void saveAcPickUpConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {
        AcPickUpConfig pickUpConfig = activityParam.getAcPickUpConfig();
        pickUpConfig.setPkBaseId(baseConfig.getPkId());
        pickUpConfig.setPickUpType(EPickUpType.QUANTITY.getValue());
        pickUpConfig.setPkCountry(baseConfig.getPkCountry());
        pickUpConfig.setPkCreator(baseConfig.getPkCreator());
        pickUpConfigService.save(pickUpConfig);
    }

    /**
     * 新增抽奖活动配置
     *
     * @param activityParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRaffleActivity(ActivityParam activityParam) {
        // 增加基础配置
        AcBaseConfig baseConfig = saveBaseConfig(activityParam);
        // 目标群体配置
        saveGoalMemberConfig(activityParam, baseConfig);
        // 抽奖活动赠品配置
        saveDrawGiftConfig(activityParam, baseConfig);
        // 抽奖赠送次数规则配置表
        saveDrawRuleConfig(activityParam, baseConfig);
        // 抽奖 提货配置
        saveAcPickUpConfig(activityParam, baseConfig);
    }

    /***
     * 抽奖赠送次数规则配置表
     * @param activityParam
     * @param baseConfig
     */
    public void saveDrawRuleConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {
        for (AcDrawRuleConfigParam acDrawRuleConfigParam : activityParam.getDrawRuleConfigParam()) {
            List<AcDrawRuleConfig> drawRuleConfigList = acDrawRuleConfigParam.getDrawRuleConfigList().stream().peek(acDrawRuleConfig -> {
                acDrawRuleConfig.setOrderType(acDrawRuleConfigParam.getOrderType());
                acDrawRuleConfig.setPkBaseId(baseConfig.getPkId());
                acDrawRuleConfig.setPkCreator(baseConfig.getPkCreator());
                acDrawRuleConfig.setCreationTime(DateUtils.currentDateTime());
                acDrawRuleConfig.setPkCountry(baseConfig.getPkCountry());
            }).collect(Collectors.toList());
            drawRuleConfigService.saveBatch(drawRuleConfigList);
        }
    }

    /**
     * 抽奖活动赠品配置
     *
     * @param activityParam
     */
    public void saveDrawGiftConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {
        for (AcDrawGiftRuleConfigVo drawGiftConfig : activityParam.getDrawGiftConfigList()) {
            drawGiftConfig.setPkBaseId(baseConfig.getPkId());
            drawGiftConfig.setPkCreator(baseConfig.getPkCreator());
            drawGiftConfig.setPkCountry(baseConfig.getPkCountry());
            AcDrawGiftRuleConfig dg = BeanUtil.copyProperties(drawGiftConfig, AcDrawGiftRuleConfig.class);
            drawGiftConfigService.save(dg);
            if (drawGiftConfig.getGiftConfigList() != null) {
                for (AcGiftConfig giftConfig : drawGiftConfig.getGiftConfigList()) {
                    giftConfig.setPkRuleId(dg.getPkId());
                    giftConfig.setActType(baseConfig.getActType());
                    giftConfig.setCreationTime(DateUtils.currentDateTime());
                    giftConfig.setPkCreator(baseConfig.getPkCreator());
                    giftConfig.setPkCountry(baseConfig.getPkCountry());
                    waresGiftConfigService.save(giftConfig);
                }
            }
        }
    }

    /**
     * 消费赠送屏蔽配置表
     *
     * @param activityParam
     * @param baseConfig
     */
    public void saveConsumeShieldConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {
        List<AcConsumeShieldConfig> consumeShieldConfigList = activityParam.getConsumeShieldConfigList().stream().peek(consumeShieldConfig -> {
            consumeShieldConfig.setPkBaseId(baseConfig.getPkId());
            consumeShieldConfig.setPkCreator(activityParam.getPkCreator());
            consumeShieldConfig.setPkCountry(activityParam.getPkCountry());
        }).collect(Collectors.toList());
        consumeShieldConfigService.saveBatch(consumeShieldConfigList);
    }

    /**
     * 消费赠送规格配置
     *
     * @param activityParam
     * @param baseConfig
     */
    public void saveConsumeRuleConfigService(ActivityParam activityParam, AcBaseConfig baseConfig) {
        List<ConsumeRuleConfigParam> consumeRuleConfigParam = activityParam.getConsumeRuleConfigParamList();

        for (ConsumeRuleConfigParam ruleConfigParam : consumeRuleConfigParam) {
            List<ConsumeRuleConfigVo> consumeRuleConfigList = ruleConfigParam.getConsumeRuleConfigList();
            for (ConsumeRuleConfigVo consumeRuleConfig : consumeRuleConfigList) {
                consumeRuleConfig.setPkBaseId(baseConfig.getPkId());
                consumeRuleConfig.setPkCreator(baseConfig.getPkCreator());
                consumeRuleConfig.setPkCountry(baseConfig.getPkCountry());
                consumeRuleConfig.setOrderType(ruleConfigParam.getOrderType());
                consumeRuleConfigService.save(consumeRuleConfig);
                /**
                 * 活动赠品配置
                 */
                List<AcGiftConfigExt> waresGiftConfigList = consumeRuleConfig.getWaresGiftConfigList();
                List<AcGiftConfig> giftConfigList = new ArrayList<>();
                for (AcGiftConfigExt acWaresGiftConfig : waresGiftConfigList) {
                    acWaresGiftConfig.setPkRuleId(consumeRuleConfig.getPkId());
                    acWaresGiftConfig.setActType(baseConfig.getActType());
                    acWaresGiftConfig.setPkCreator(baseConfig.getPkCreator());
                    acWaresGiftConfig.setPkCountry(baseConfig.getPkCountry());
                    AcGiftConfig acGiftConfig = BeanUtil.copyProperties(acWaresGiftConfig, AcGiftConfig.class);
                    giftConfigList.add(acGiftConfig);
                }
                waresGiftConfigService.saveBatch(giftConfigList);
            }
        }
    }

    /**
     * 目标群体配置
     *
     * @param activityParam
     * @param baseConfig
     */
    @Override
    public Boolean saveGoalMemberConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {
        List<AcGoalMemberConfig> goalMemberConfig = activityParam.getGoalMemberConfigList();
        for (AcGoalMemberConfig acGoalMemberConfig : goalMemberConfig) {
            acGoalMemberConfig.setPkBaseId(baseConfig.getPkId());
            acGoalMemberConfig.setPkCountry(activityParam.getPkCountry());
            acGoalMemberConfig.setPkCreator(activityParam.getPkCreator());
        }
        return goalMemberConfigService.saveBatch(goalMemberConfig);
    }

    /**
     * 新增商品产品买赠规则配置
     *
     * @param activityParam
     */
    @Override
    public void saveWaresRuleConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {

        for (WaresConfigParam waresConfigParam : activityParam.getWaresConfigParam()) {
            /**
             * 活动商品配置
             */
            List<WaresRuleConfigParam> waresRuleConfigParam = waresConfigParam.getWaresRuleConfigParam();
            for (WaresRuleConfigParam ruleConfigParam : waresRuleConfigParam) {
                AcWaresRuleConfig waresRuleConfig = BeanUtil.copyProperties(ruleConfigParam, AcWaresRuleConfig.class);
                waresRuleConfig.setPkBaseId(baseConfig.getPkId());
                waresRuleConfig.setOrderType(waresConfigParam.getOrderType());
                waresRuleConfig.setPkCreator(activityParam.getPkCreator());
                waresRuleConfig.setPkCountry(activityParam.getPkCountry());
                waresRuleConfigService.save(waresRuleConfig);
                /**
                 * 活动赠品配置
                 */
                List<AcGiftConfigExt> waresGiftConfigList = ruleConfigParam.getWaresGiftConfigList();
                List<AcGiftConfig> giftConfigList = new ArrayList<>();
                for (AcGiftConfigExt acWaresGiftConfig : waresGiftConfigList) {
                    acWaresGiftConfig.setPkRuleId(waresRuleConfig.getPkId());
                    acWaresGiftConfig.setActType(baseConfig.getActType());
                    acWaresGiftConfig.setPkCreator(activityParam.getPkCreator());
                    acWaresGiftConfig.setPkCountry(activityParam.getPkCountry());
                    AcGiftConfig giftConfig = BeanUtil.copyProperties(acWaresGiftConfig, AcGiftConfig.class);
                    giftConfigList.add(giftConfig);
                }
                waresGiftConfigService.saveBatch(giftConfigList);
            }

        }

    }

    /**
     * 新增活动基础配置
     *
     * @param activityParam
     */
    @Override
    public AcBaseConfig saveBaseConfig(ActivityParam activityParam) {
        AcBaseConfig baseConfig = BeanUtil.copyProperties(activityParam, AcBaseConfig.class);
        baseConfigService.save(baseConfig);
        return baseConfig;
    }

    /**
     * 活动日志基本信息拼装
     *
     * @param activityParam 活动基本信息
     * @param str           拼接字符
     * @param pkBaseId      活动主键
     * @param businessType  类型
     * @param freeSignFlag  是否需要签呈
     * @return
     */
    @Override
    public StringBuffer createBaseConfigLog(ActivityParam activityParam, StringBuffer str, Long pkBaseId, Integer businessType, Boolean freeSignFlag) {
        Integer pkCountry = activityParam.getPkCountry();
        Long userId = activityParam.getPkCreator();
        if (StringUtils.isNotBlank(activityParam.getActName())) {
            // 活动名称
            str.append("活动名称:").append(activityParam.getActName()).append("；\t\t");
        }
        if (StringUtils.isNotBlank(activityParam.getActExplain())) {
            // 活动说明
            str.append("活动说明:").append(activityParam.getActExplain()).append("；\t\t");
        }
        // 活动时间
        if (activityParam.getActStartDate() != null && activityParam.getActEndDate() != null) {
            str.append("活动开始时间:").append(DateUtil.format(activityParam.getActStartDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            str.append("活动结束时间:").append(DateUtil.format(activityParam.getActEndDate(), DateUtils.YYYY_MM_DD_HH_MM_SS)).append("；\t\t");
        }
        // 展示时间
        if (activityParam.getDisStartDate() != null && activityParam.getDisEndDate() != null) {
            str.append("展示开始时间:").append(DateUtil.format(activityParam.getDisStartDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));
            str.append("展示结束时间:").append(DateUtil.format(activityParam.getDisEndDate(), DateUtils.YYYY_MM_DD_HH_MM_SS)).append("；\t\t");
        }
        // 活动日志 目标用户群体拼接
        if (activityParam.getGoalMemberConfigList() != null && activityParam.getGoalMemberConfigList().size() > 0) {
            Map<Integer, List<AcGoalMemberConfig>> memberConfigList = activityParam.getGoalMemberConfigList().stream().collect(Collectors.groupingBy(AcGoalMemberConfig::getMemberType));

            for (Map.Entry<Integer, List<AcGoalMemberConfig>> item : memberConfigList.entrySet()) {
                if (item.getKey().equals(1)) {
                    // 等级
                    R<List<GradeDTO>> gradeDTO = gradeServiceApi.selectGradeAll(activityParam.getPkCountry());
                    List<GradeDTO> gradeList = gradeDTO.getData();
                    str.append("注册等级:");
                    for (AcGoalMemberConfig acGoalMemberConfig : item.getValue()) {
                        for (GradeDTO dto : gradeList) {
                            if (dto.getPkId().equals(acGoalMemberConfig.getPkLevel())) {
                                str.append(dto.getGradeName()).append(", ");
                            }
                        }

                    }
                    str.append("；\t\t");
                } else if (item.getKey().equals(2)) {
                    // 奖衔
                    R<List<BdAwards>> awardsDTO = awardsServiceApi.queryAwards(activityParam.getPkCountry());
                    List<BdAwards> awardsList = awardsDTO.getData();
                    str.append("真实奖衔:");
                    for (AcGoalMemberConfig acGoalMemberConfig : item.getValue()) {
                        for (BdAwards awards : awardsList) {
                            if (awards.getPkId().equals(acGoalMemberConfig.getPkLevel())) {
                                str.append(awards.getAwardsName()).append(", ");
                            }
                        }

                    }
                    str.append("；\t\t");
                } else if (item.getKey().equals(3)) {
                    // 权限中心
                    str.append("权限中心:");
                    for (AcGoalMemberConfig acGoalMemberConfig : item.getValue()) {
                        ERegistrationAuthority registrationAuthority = ERegistrationAuthority.getEnumByValue(acGoalMemberConfig.getPkLevel());
                        if (registrationAuthority != null) {
                            str.append(registrationAuthority.getLabel()).append(" ,");
                        }
                    }
                    str.append("；\t\t");
                }
            }
        }
        // 规则设置
        if (activityParam.getWaresConfigParam() != null && activityParam.getWaresConfigParam().size() > 0) {
            QueryWrapper<BdWares> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
            List<BdWares> waresList = waresService.list(queryWrapper);
            for (WaresConfigParam waresConfigParam : activityParam.getWaresConfigParam()) {
                if (waresConfigParam.getWaresRuleConfigParam() != null && waresConfigParam.getWaresRuleConfigParam().size() > 0) {
                    EOrderType enumByValue = EOrderType.getEnumByValue(waresConfigParam.getOrderType());
                    if (enumByValue != null) {
                        str.append(enumByValue.getLabel()).append(" :");
                        for (WaresRuleConfigParam waresRuleConfigParam : waresConfigParam.getWaresRuleConfigParam()) {
                            for (BdWares wares : waresList) {
                                if (waresRuleConfigParam.getPkWares().equals(wares.getPkId())) {
                                    str.append(" 商品名称:").append(wares.getWaresName());
                                    str.append("数量:").append(waresRuleConfigParam.getQuantity());
                                    if (waresRuleConfigParam.getWaresGiftConfigList() != null && waresRuleConfigParam.getWaresGiftConfigList().size() > 0) {
                                        for (AcGiftConfigExt acGiftConfigExt : waresRuleConfigParam.getWaresGiftConfigList()) {
                                            str.append("赠送产品:").append(acGiftConfigExt.getProductName());
                                            str.append("产品规格:").append(acGiftConfigExt.getSpecsName());
                                            str.append("赠送数量:").append(acGiftConfigExt.getQuantity());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // 屏蔽设置
        if (activityParam.getConsumeShieldConfigList() != null && activityParam.getConsumeShieldConfigList().size() > 0) {
            str.append("屏蔽配置： ");
            for (AcConsumeShieldConfigExt consumeShieldConfigExt : activityParam.getConsumeShieldConfigList()) {
                str.append("产品名称：").append(consumeShieldConfigExt.getProductName());
                str.append("产品规格：").append(consumeShieldConfigExt.getSpecsName());
                if (consumeShieldConfigExt.getCondition() != null) {
                    str.append("条件：").append(ECondition.getCondition(consumeShieldConfigExt.getCondition()).getLabel());
                }
                str.append("产品数量：").append(consumeShieldConfigExt.getQuantity());
            }
        }
        // 是否强弹 (种植公益配置) 是否强制弹框 0 是  1 否
        if (activityParam.getIsStrongAlert() != null) {
            if (activityParam.getIsStrongAlert().equals(EYesNo.YES.getIntValue())) {
                str.append("是否强制弹框：是");
            } else if (activityParam.getIsStrongAlert().equals(EYesNo.NO.getIntValue())) {
                str.append("是否强制弹框：否");
            }
        }
        // 抽奖赠送次数规则配置表
        if (activityParam.getDrawRuleConfigParam() != null && activityParam.getDrawRuleConfigParam().size() > 0) {
            for (AcDrawRuleConfigParam drawRuleConfigParam : activityParam.getDrawRuleConfigParam()) {
                if (drawRuleConfigParam.getDrawRuleConfigList() != null && drawRuleConfigParam.getDrawRuleConfigList().size() > 0) {
                    EOrderType enumByValue = EOrderType.getEnumByValue(drawRuleConfigParam.getOrderType());
                    str.append("订单类型：").append(enumByValue.getLabel());
                    for (AcDrawRuleConfig acDrawRuleConfig : drawRuleConfigParam.getDrawRuleConfigList()) {
                        str.append("订单金额：").append(acDrawRuleConfig.getOrderAmount());
                        str.append("订单业绩：").append(acDrawRuleConfig.getOrderAchieve());
                        str.append("赠送次数：").append(acDrawRuleConfig.getGiveNumber());
                    }
                }
            }
        }
        // 支付金额
        if (activityParam.getPayMoney() != null) {
            str.append("支付金额：").append(activityParam.getPayMoney());
        }
        // 奖品设置
        if (activityParam.getDrawGiftConfigList() != null && activityParam.getDrawGiftConfigList().size() > 0) {
            str.append("奖品设置：");
            for (AcDrawGiftRuleConfigVo drawGiftRuleConfigVo : activityParam.getDrawGiftConfigList()) {
                str.append("奖品名称：").append(drawGiftRuleConfigVo.getGiftName());
                str.append("奖品总数：").append(drawGiftRuleConfigVo.getGiftNumber());
                str.append("最小中奖数量：").append(drawGiftRuleConfigVo.getMinNumber());
                str.append("发放方式：").append(EActDrawGiftType.getActDrawGiftType(drawGiftRuleConfigVo.getGrantWay()));
                // 产品
                if (drawGiftRuleConfigVo.getGiftConfigList() != null && drawGiftRuleConfigVo.getGiftConfigList().size() > 0) {
                    for (AcGiftConfigExt giftConfigExt : drawGiftRuleConfigVo.getGiftConfigList()) {
                        str.append("产品名称：").append(giftConfigExt.getProductName());
                        str.append("产品规格：").append(giftConfigExt.getSpecsName());
                        str.append("数量：").append(giftConfigExt.getQuantity());
                    }
                }
            }
        }

        if (activityParam.getAcPickUpConfig() != null) {
            AcPickUpConfig acPickUpConfig = activityParam.getAcPickUpConfig();
            // 提货天数
            if (acPickUpConfig.getDeliveryDays() != null) {
                str.append("提货天数：").append(acPickUpConfig.getDeliveryDays());
            }
            // 包邮类型
            if (acPickUpConfig.getIsFreeMail() != null) {
                if (acPickUpConfig.getIsFreeMail().equals(EYesNo.YES.getIntValue())) {
                    str.append("包邮类型：包邮");
                } else if (acPickUpConfig.getIsFreeMail().equals(EYesNo.NO.getIntValue())) {
                    str.append("包邮类型：不包邮");
                }
            }
        }
        if (freeSignFlag == null) {
            freeSignFlag = false;
        }

        // 拼装发送mq
        BusinessLogDTO log = BusinessLogDTO.builder()
                .businessType(businessType)
                .businessId(pkBaseId)
                .businessCode(activityParam.getBusinessCode())
                .pkMember(null)
                .content(str.toString())
                .pkCreator(userId)
                .pkCountry(pkCountry)
                .freeSignFlag(freeSignFlag)
                .build();
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
        return str;
    }

    /**
     * 删除活动日志
     *
     * @param baseConfig
     * @param str
     * @param pkBaseId
     * @param businessType
     * @param freeSignFlag
     * @return
     */
    @Override
    public StringBuffer removeBaseConfigLog(AcBaseConfig baseConfig, StringBuffer str, Long pkBaseId, Integer businessType, Boolean freeSignFlag) {
        if (baseConfig != null) {
            Integer pkCountry = baseConfig.getPkCountry();
            Long userId = baseConfig.getPkCreator();
            str.append("删除活动：").append(baseConfig.getActName());
            // 拼装发送mq
            BusinessLogDTO log = BusinessLogDTO.builder()
                    .businessType(businessType)
                    .businessId(pkBaseId)
                    .businessCode(baseConfig.getBusinessCode())
                    .pkMember(null)
                    .content(str.toString())
                    .pkCreator(userId)
                    .pkCountry(pkCountry)
                    .freeSignFlag(freeSignFlag)
                    .build();
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
        }

        return str;
    }

    /**
     * 修改消费赠送规格
     *
     * @param activityParam
     */
    @Override
    public void updateConsumptionGift(ActivityParam activityParam) {
        Long pkId = activityParam.getPkId();
        // 查询基础信息
        AcBaseConfig baseConfig = BeanUtil.copyProperties(activityParam, AcBaseConfig.class);
        baseConfig.setPkId(activityParam.getPkId());
        baseConfigService.updateById(baseConfig);

        LambdaQueryWrapper<AcGoalMemberConfig> qt = new LambdaQueryWrapper<>();
        qt.eq(AcGoalMemberConfig::getPkBaseId, pkId);
        goalMemberConfigService.remove(qt);
        // 目标群体配置
        saveGoalMemberConfig(activityParam, baseConfig);

        // 消费赠送规格配置
        LambdaQueryWrapper<AcConsumeRuleConfig> qx = new LambdaQueryWrapper<>();
        qx.eq(AcConsumeRuleConfig::getPkBaseId, pkId);
        consumeRuleConfigService.remove(qx);
        saveConsumeRuleConfigService(activityParam, baseConfig);

        // 消费赠送屏蔽配置表
        LambdaQueryWrapper<AcConsumeShieldConfig> cr = new LambdaQueryWrapper<>();
        cr.eq(AcConsumeShieldConfig::getPkBaseId, pkId);
        consumeShieldConfigService.remove(cr);
        saveConsumeShieldConfig(activityParam, baseConfig);
    }

    /**
     * 保存活动审批日志信息
     *
     * @param recommendParam   直推赠送参数
     * @param approvalBusiness 审批业务
     * @return boolean
     */
    public AcApprovalLog saveApprovalLog(AcRecommendParam recommendParam, EApprovalBusiness approvalBusiness) {
        Integer controlType = recommendParam.getControlType();
        //查询变更前的数据
        String afterData = JSONUtil.toJsonStr(recommendParam);
        String beforeData = controlType.equals(EControlType.SAVE.getValue()) ? JSONUtil.toJsonStr(recommendParam) : null;
        //业务单号
        String businessCode = "";
        if (StringUtils.isEmpty(recommendParam.getActivityParam().getBusinessCode())) {
            businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        } else {
            businessCode = recommendParam.getActivityParam().getBusinessCode();
        }
        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
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleActivity(SaOrderExt saOrderExt) {
        if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
            if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
                // 抽奖
                acDrawRewardNumService.giveMemberDrawNum(saOrderExt);
            }
            // 直推升级
            acRepurCouponsRuleConfigService.invokeRecommendUpgrade(AcRecommendUpgrade.builder().saOrderExt(saOrderExt).orderOperateStatus(EOrderOperateStatus.NORMAL).build());
        } else if (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()) {
            // 抽奖
            acDrawRewardNumService.giveMemberDrawNum(saOrderExt);
            // 直推升级
            acRepurCouponsRuleConfigService.invokeRecommendUpgrade(AcRecommendUpgrade.builder().saOrderExt(saOrderExt).orderOperateStatus(EOrderOperateStatus.NORMAL).build());
        }
        return true;
    }

    @Override
    public AcBaseConfig updateRaffleActivity(ActivityParam activityParam) {
        // 增加基础配置
        AcBaseConfig baseConfig = BeanUtil.copyProperties(activityParam, AcBaseConfig.class);
        baseConfigService.updateById(baseConfig);
        // 目标群体配置
        saveGoalMemberConfig(activityParam, baseConfig);

        // 抽奖活动赠品配置
        saveDrawGiftConfig(activityParam, baseConfig);

        // 抽奖赠送次数规则配置表
        saveDrawRuleConfig(activityParam, baseConfig);

        updateAcPickUpConfig(activityParam, baseConfig);
        return baseConfig;
    }

    /**
     * 查询活动数据列表
     *
     * @param queryActivityParam
     * @return
     */
    @Override
    public List<BaseConfigVo> activityList(QueryActivityParam queryActivityParam) {
        LambdaQueryWrapper<AcBaseConfig> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(queryActivityParam.getActName())) {
            queryWrapper.eq(AcBaseConfig::getActName, queryActivityParam.getActName());
        }
        if (queryActivityParam.getActivityStatus() != null) {
            // 状态筛选
            if (queryActivityParam.getActivityStatus() == EActivityStatus.NOT_STARTED.getValue()) {
                // 未开始  当前时间小于开始时间
                queryWrapper.gt(AcBaseConfig::getActStartDate, DateUtils.currentDate());
            } else if (queryActivityParam.getActivityStatus() == EActivityStatus.IN_PROGRESS.getValue()) {
                // 进行中 大于开始 小于结束
                queryWrapper.lt(AcBaseConfig::getActStartDate, DateUtils.currentDate());
                queryWrapper.gt(AcBaseConfig::getActEndDate, DateUtils.currentDate());
            } else if (queryActivityParam.getActivityStatus() == EActivityStatus.EXPIRED.getValue()) {
                // 已失效 当前时间大于结束时间
                queryWrapper.le(AcBaseConfig::getActEndDate, DateUtils.currentDate());
            }
        }
        // 活动开始时间
        if (queryActivityParam.getStartActStartDate() != null && queryActivityParam.getEndActStartDate() != null) {
            queryWrapper.between(AcBaseConfig::getActStartDate, queryActivityParam.getStartActStartDate(), queryActivityParam.getEndActStartDate());
        }
        // 活动结束时间
        if (queryActivityParam.getStartActEndDate() != null && queryActivityParam.getEndActEndDate() != null) {
            queryWrapper.between(AcBaseConfig::getActEndDate, queryActivityParam.getStartActEndDate(), queryActivityParam.getEndActEndDate());
        }
        // 创建时间
        if (queryActivityParam.getStartCreationTime() != null && queryActivityParam.getEndCreationTime() != null) {
            queryWrapper.between(AcBaseConfig::getCreationTime, queryActivityParam.getStartCreationTime(), queryActivityParam.getEndCreationTime());
        }
        if (queryActivityParam.getActType() != null) {
            queryWrapper.eq(AcBaseConfig::getActType, queryActivityParam.getActType());
        }
        queryWrapper.eq(AcBaseConfig::getPkCountry, queryActivityParam.getPkCountry());
        queryWrapper.eq(AcBaseConfig::getSystemType, queryActivityParam.getSystemType());
        // 创建时间倒叙
        queryWrapper.orderByDesc(AcBaseConfig::getCreationTime);
        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.currentDateTime().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;
    }

    private void updateAcPickUpConfig(ActivityParam activityParam, AcBaseConfig baseConfig) {
        AcPickUpConfig pickUpConfig = activityParam.getAcPickUpConfig();
        if (pickUpConfig != null) {
            AcPickUpConfig pc = pickUpConfigService.getById(pickUpConfig.getPkId());
            if (pc != null) {
                BeanUtil.copyProperties(pickUpConfig, pc);
                pickUpConfigService.updateById(pc);
            } else {
                pickUpConfig.setPkBaseId(baseConfig.getPkId());
                pickUpConfig.setPickUpType(EPickUpType.QUANTITY.getValue());
                pickUpConfig.setPkCountry(baseConfig.getPkCountry());
                pickUpConfig.setPkCreator(baseConfig.getPkCreator());

                pickUpConfigService.save(pickUpConfig);
            }
        }

    }

    @Override
    public List<BdWaresDetailExt> generateActivityGiftWaresAchieve(Integer specialArea, Integer pkCountry, List<BdWaresDetailExt> bdWaresDetailExtList,
                                                                   String parentCode, CuMember cuMember) {
        // 兼容没有数据
        bdWaresDetailExtList = bdWaresDetailExtList.stream().filter(bdWaresDetailExt -> null != bdWaresDetailExt.getPkWares()).collect(Collectors.toList());

        // 商品赠送
        Date currentDate = DateUtils.currentDateTime();
        GiftConfigParam giftConfigParam = GiftConfigParam.builder()
                .actType(EActType.PRODUCT_GIFT.getValue())
                .orderType(specialArea)
                .startDate(currentDate)
                .endDate(currentDate)
                .orderAmount(BigDecimal.ZERO)
                .orderAchieve(BigDecimal.ZERO)
                .pkCountry(pkCountry)
                .build();
        List<GiftConfigParamDetail> configParamDetailList = new ArrayList<>(bdWaresDetailExtList.size());
        for (BdWaresDetailExt bdWaresDetailExt : bdWaresDetailExtList) {
            if (null != bdWaresDetailExt.getIsGift() && EYesNo.YES.getIntValue() == bdWaresDetailExt.getIsGift()) {
                // 赠品不处理活动
                continue;
            }
            GiftConfigParamDetail giftConfigParamDetail = GiftConfigParamDetail.builder()
                    .pkWares(bdWaresDetailExt.getPkWares())
                    .quantity(bdWaresDetailExt.getWaresQuantity())
                    .build();
            configParamDetailList.add(giftConfigParamDetail);
        }
        giftConfigParam.setConfigParamDetailList(configParamDetailList);
        List<BdWaresDetailExt> returnBdWaresDetailList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(giftConfigParam.getConfigParamDetailList())) {
            List<AcWaresRuleConfigExt> waresRuleConfigExtList = waresRuleConfigService.queryWaresGiftConfigByCondition(giftConfigParam);
            if (CollectionUtil.isNotEmpty(waresRuleConfigExtList)) {
                for (AcWaresRuleConfigExt waresRuleConfigExt : waresRuleConfigExtList) {
                    // 遍历购买的商品，判断是否在规则内
                    for (BdWaresDetailExt bdWaresDetail : bdWaresDetailExtList) {
                        // 指定商品买多少件
                        if (null != bdWaresDetail.getIsGift() && EYesNo.YES.getIntValue() == bdWaresDetail.getIsGift()) {
                            // 赠品不处理活动
                            continue;
                        }
                        if (bdWaresDetail.getPkWares().equals(waresRuleConfigExt.getPkWares())) {
                            // 目前这个位置需要优化，多活动多规则不支持，此处只匹配了同商品数量配置最小的
                            AcGiftConfigExt acGiftConfigExt = waresRuleConfigExt.getGiftConfigExtList().get(0);
                            // 实际需要赠送的商品数量（购买的商品数量 整除 活动配置的商品数量 = 实际赠送商品数量）
                            // 例：买3赠2的活动（购买的商品数量6 整除 活动配置商品数量3 = 实际赠品商品数量2份）
                            int waresQuantity = bdWaresDetail.getWaresQuantity() / waresRuleConfigExt.getQuantity();
                            if (waresQuantity > 0) {
                                // 如果购买的数量达不到配置的商品数量，则不需要进行赠品处理
                                BdWaresDetailExt bdWaresDetailExt = BdWaresDetailExt.builder()
                                        .isFreeMail(waresRuleConfigExt.getIsFreeMail())
                                        .pkAirPostage(waresRuleConfigExt.getPkAirPostage())
                                        .pkLandPostage(waresRuleConfigExt.getPkLandPostage())
                                        .pkOceanPostage(waresRuleConfigExt.getPkOceanPostage())
                                        .shippingChannel(waresRuleConfigExt.getShippingChannel())
                                        .pkSupplier(waresRuleConfigExt.getPkSupplier())
                                        .preSaleStatus(waresRuleConfigExt.getPreSaleStatus())
                                        .waresQuantity(1)
                                        .build();
                                String[] split = acGiftConfigExt.getSpecsNameId().split(",");
                                List<Integer> idList = new ArrayList<>();
                                for (String id : split) {
                                    idList.add(Integer.valueOf(id));
                                }
                                List<BdSpecs> specsList = specsService.queryBdSpecsByIdList(idList);
                                List<WaresSpecsExt> waresSpecsList = new ArrayList<>();
                                for (BdSpecs bdSpecs : specsList) {
                                    WaresSpecsExt waresSpecsExt = new WaresSpecsExt();
                                    waresSpecsExt.setPkSpecsType(bdSpecs.getPkSpecsType());
                                    waresSpecsExt.setPkSpecs(bdSpecs.getPkId());
                                    waresSpecsExt.setSpecsName(bdSpecs.getSpecsName());
                                    waresSpecsList.add(waresSpecsExt);
                                }
                                bdWaresDetailExt.setWaresSpecsList(waresSpecsList);
                                // 实际赠送商品数量 * 配置产品赠送数量 = 实际赠品数量
                                // 例：实际赠品商品数量2份 * 配置产品赠送数量2 = 实际赠品数量4
                                acGiftConfigExt.setQuantity(waresQuantity * acGiftConfigExt.getQuantity());
                                packageWaresDetail(bdWaresDetailExt, acGiftConfigExt);
                                returnBdWaresDetailList.add(bdWaresDetailExt);
                            }
                        }
                    }
                }
            }
        }

        // 消费赠送
        giftConfigParam.setActType(EActType.CONSUMPTION_GIFT.getValue());
        for (BdWaresDetailExt bdWaresDetailExt : bdWaresDetailExtList) {
            // 业绩、金额累积
            giftConfigParam.setOrderAmount(ComputeUtil.computeAdd(giftConfigParam.getOrderAmount(), ComputeUtil.computeMultiply(ComputeUtil.computeMultiply(bdWaresDetailExt.getPrice(), bdWaresDetailExt.getQuantity()), bdWaresDetailExt.getWaresQuantity())));
            giftConfigParam.setOrderAchieve(ComputeUtil.computeAdd(giftConfigParam.getOrderAchieve(), ComputeUtil.computeMultiply(ComputeUtil.computeMultiply(bdWaresDetailExt.getAchieve(), bdWaresDetailExt.getQuantity()), bdWaresDetailExt.getWaresQuantity())));
        }
        List<AcConsumeRuleConfigExt> consumeRuleConfigExtList = consumeRuleConfigService.queryConsumeGiftConfigByCondition(giftConfigParam);
        if (consumeRuleConfigExtList != null && consumeRuleConfigExtList.size() > 0) {
            for (AcConsumeRuleConfigExt consumeRuleConfigExt : consumeRuleConfigExtList) {
                // 配置ID
                Long pkConfigId = consumeRuleConfigExt.getGiftConfigExtList().get(0).getPkId();

                // 同一活动匹配多条规则，同规则下可能有多个赠品
                for (AcGiftConfigExt giftConfigExt : consumeRuleConfigExt.getGiftConfigExtList()) {
                    if (pkConfigId.equals(giftConfigExt.getPkId())) {
                        BdWaresDetailExt bdWaresDetailExt = BdWaresDetailExt.builder()
                                .isFreeMail(EYesNo.YES.getIntValue())
                                .waresQuantity(1)
                                .build();
                        packageWaresDetail(bdWaresDetailExt, giftConfigExt);
                        returnBdWaresDetailList.add(bdWaresDetailExt);
                    }
                }
            }
        }

        // 2024.11.26 新消费赠送活动需求，注册、升级专区处理新需求
        if (ESpecialArea.REGISTER_AREA.getValue() == specialArea
                || ESpecialArea.UPGRADE_AREA.getValue() == specialArea) {
            if (null != cuMember
                    && StringUtils.isNotEmpty(cuMember.getMemberName())
                    && StringUtils.isNotEmpty(cuMember.getPhone())) {
                // 根据订单业绩匹配对应等级
                BdGrade bdGrade = gradeServiceApi.getLastGrade(giftConfigParam.getOrderAchieve(), pkCountry).getData();
                if (null != bdGrade) {
                    // 查询会员该等级点位数量（因为当前订单的数据还没有更新入库，此处计算数量时，需要加 1 ）
                    Integer memberPoint = iMemberServiceApi.countGradeMemberPoint(cuMember.getMemberName(), cuMember.getPhone(), bdGrade.getPkId(), pkCountry).getData() + 1;

                    List<AcMemberConsumeRuleExt> ruleList = iAcMemberConsumeRuleService.listRuleAndProduct(currentDate, currentDate, bdGrade.getPkId(), memberPoint, pkCountry);
                    if (CollectionUtil.isNotEmpty(ruleList)) {
                        // 查询会员该等级的会员数量
                        // 与营运确认，匹配多条活动，只处理最新的一天
                        AcMemberConsumeRuleExt memberConsumeRuleExt = ruleList.get(0);
                        for (AcGiftConfigExt acGiftConfigExt : memberConsumeRuleExt.getGiftConfigExtList()) {
                            BdWaresDetailExt bdWaresDetailExt = BdWaresDetailExt.builder()
                                    .isFreeMail(EYesNo.YES.getIntValue())
                                    .waresQuantity(1)
                                    .build();
                            packageWaresDetail(bdWaresDetailExt, acGiftConfigExt);
                            returnBdWaresDetailList.add(bdWaresDetailExt);
                        }
                    }
                }
            }
        }

        return returnBdWaresDetailList;
    }

    /*
     * @description: 封装赠品明细
     * @author: sui q
     * @date: 2023/4/26 13:56
     * @param: null null
     **/
    private void packageWaresDetail(BdWaresDetailExt bdWaresDetailExt, AcGiftConfigExt acGiftConfigExt) {
        bdWaresDetailExt.setPkProduct(acGiftConfigExt.getPkProduct());
        bdWaresDetailExt.setProductCode(acGiftConfigExt.getProductCode());
        bdWaresDetailExt.setPkWares(0);
        bdWaresDetailExt.setPkId(0);
        bdWaresDetailExt.setPkWaresSpecsSku(0);
        bdWaresDetailExt.setPrice(BigDecimal.ZERO);
        bdWaresDetailExt.setAchieve(BigDecimal.ZERO);
        bdWaresDetailExt.setAssAchieve(BigDecimal.ZERO);
        bdWaresDetailExt.setQuantity(acGiftConfigExt.getQuantity());
        bdWaresDetailExt.setIsGift(EYesNo.YES.getIntValue());
        bdWaresDetailExt.setSpecsName(acGiftConfigExt.getSpecsName());
        bdWaresDetailExt.setSpecsNameId(acGiftConfigExt.getSpecsNameId());
    }


}
