package com.hzs.third.mqcall.listener;

import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EGrade;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.core.enums.EUpgradeType;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 会员消费升级监听器
 */
@Slf4j
@Component
public class ConsumeUpgradeListener {

    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    ISaOrderServiceApi iSaOrderServiceApi;

    /**
     * 会员消费升级监听处理
     *
     * @param message
     * @param channel
     * @throws Exception
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMqConstants.CONSUME_UPGRADE_EXCHANGE, type = "topic"),
            value = @Queue(value = RabbitMqConstants.CONSUME_UPGRADE_QUEUE, durable = "true", autoDelete = "false"),
            key = RabbitMqConstants.CONSUME_UPGRADE_KEY))
    @RabbitHandler
    public void onMessage(Message<SaOrderExt> message, Channel channel) throws Exception {
        // 手动应答
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);

        // 根据传入的ID获取订单内容
        SaOrderExt saOrderExt = message.getPayload();

        log.info("会员异步升级信息：{}", saOrderExt);

        // 处理会员消费升级（个人购买满20美金并且直推60PV报单，可升级到铜卡）
        if ((EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType() && saOrderExt.getOrderAchieve().compareTo(BigDecimal.ZERO) > 0)
                || (EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType() && saOrderExt.getOrderAmount().compareTo(BigDecimal.ZERO) > 0)
        ) {
            // 报单并且业绩大于0 或 消费并且金额大于0，则进行处理
            log.info("会员异步升级信息: 开始处理");

            // 校验会员等级，如果为铜卡以上，直接跳过
            // 购买人
            Long pkMember = saOrderExt.getPkCreator();
            // 查询会员信息
            CuMember cuMember = iMemberServiceApi.queryMember(pkMember).getData();
            // 查询所有等级
            List<GradeDTO> gradeDTOList = iGradeServiceApi.queryGradeConfigByCondition(saOrderExt.getPkCountry()).getData();
            // 获取会员旧应等级
            GradeDTO gradeDTO = null;
            for (int i = 0; i < gradeDTOList.size(); i++) {
                GradeDTO dto = gradeDTOList.get(i);
                if (dto.getPkId().equals(cuMember.getPkSettleGrade())) {
                    gradeDTO = dto;
                    if (i != 0) {
                        // 会员赋值新等级
                        cuMember.setPkSettleGrade(gradeDTOList.get(i - 1).getPkId());
                    }
                    break;
                }
            }

            if (null != gradeDTO && EGrade.START_UP.getValue() == gradeDTO.getGradeValue()) {
                // 购买人是会员级，需要处理消费升级d

                // 查询会员购买金额以及直推PV
                SaOrderExt sumOrder = iSaOrderServiceApi.queryUpgradeAmountAndAchieve(pkMember).getData();
                log.info("会员异步升级订单数据: {}", sumOrder);

                // 判断订单购买人，为当前订单购买人的订单金额是否达到20美金
                // 判断订单报单人，为当前订单购买人的订单PV是否达到60PV
                if (sumOrder.getOrderAmount().compareTo(new BigDecimal("20")) >= 0
                        && sumOrder.getOrderAchieve().compareTo(new BigDecimal("60")) >= 0) {
                    log.info("会员异步升级满足条件，进行升级");

                    R<Boolean> updateR = iMemberServiceApi.updateMemberLevel(cuMember, gradeDTO.getPkId(), EUpgradeType.ACTIVITY_UPGRADE, "消费活动升级");
                    if (updateR.isSuccess()) {
                        log.info("会员异步升级成功");
                        return;
                    }
                    log.warn("会员异步升级失败");
                }
            }
        }
    }

}
