package com.slodon.b2b2c.mq;

import cn.hutool.core.date.DateUtil;
import com.slodon.b2b2c.core.constant.MemberIntegralLogConst;
import com.slodon.b2b2c.core.constant.StarterConfigConst;
import com.slodon.b2b2c.member.example.MemberIntegralLogExample;
import com.slodon.b2b2c.member.pojo.MemberIntegralLog;
import com.slodon.b2b2c.model.member.MemberIntegralLogModel;
import com.slodon.b2b2c.starter.mq.entity.MemberIntegralVO;
import com.slodon.b2b2c.starter.redisson.SlodonLock;
import com.slodon.b2b2c.starter.redisson.constant.LockKeyConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * mq执行会员积分记录操作
 */
@Slf4j
@Component
public class MqMemberIntegralConsumer {

    @Resource
    private MemberIntegralLogModel memberIntegralLogModel;
    @Resource
    private SlodonLock slodonLock;

    /**
     * 存储会员积分日志
     *
     * @param memberIntegralVO
     */
    @RabbitListener(queues = StarterConfigConst.MQ_QUEUE_NAME_MEMBER_INTEGRAL, containerFactory = StarterConfigConst.MQ_FACTORY_NAME_SINGLE_PASS_ERR)
    public void adminLogConsumer(MemberIntegralVO memberIntegralVO) {
        //对用户加锁，防止同一用户在不同客户端重复赠送积分
        String memberLockKey = LockKeyConst.MEMBER_LOGIN_PREFIX + memberIntegralVO.getMemberId();
        slodonLock.lock(memberLockKey);
        try {
            if (memberIntegralVO.getType() == MemberIntegralLogConst.TYPE_2) {
                //查询今天登录是否赠送积分
                MemberIntegralLogExample example = new MemberIntegralLogExample();
                example.setMemberId(memberIntegralVO.getMemberId());
                example.setType(MemberIntegralLogConst.TYPE_2);
                example.setCreateTimeAfter(DateUtil.beginOfDay(new Date()));
                example.setCreateTimeBefore(DateUtil.endOfDay(new Date()));
                List<MemberIntegralLog> list = memberIntegralLogModel.getMemberIntegralLogList(example, null);
                if (!CollectionUtils.isEmpty(list)) {
                    //已赠送直接返回
                    return;
                }
            }
            memberIntegralLogModel.memberSendIntegral(memberIntegralVO);
        } catch (Exception e) {
            log.error("保存会员积分日志失败：", e);
        }
    }

}
