package com.fzm.mall.server.front.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.fzm.mall.server.front.constant.MALLGlobalConfig;
import com.fzm.mall.server.front.mq.model.MemberUp;
import com.fzm.mall.server.front.order.model.Pay;
import com.fzm.mall.server.front.order.model.vo.DeliveryVO;
import com.fzm.mall.server.front.user.model.Member;
import com.fzm.mall.server.front.user.model.User;
import com.fzm.mall.server.front.user.service.IMemberService;
import com.fzm.mall.server.front.user.service.ISysMemberService;
import com.fzm.mall.server.front.user.service.IUserService;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MemberUpCousumer {

    @Autowired
    private ISysMemberService sysMemberService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IUserService userService;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = MALLGlobalConfig.projectMq+".memberup.queue"), exchange = @Exchange(value = MALLGlobalConfig.projectMq+"-memberup-exchange"), key = MALLGlobalConfig.projectMq+".memberup.key")})
    public void receiver(String message) {
        System.out.println("MemberUpCousumer:" + message);
        if(StringUtil.isNullOrEmpty(message)){
            return;
        }
        try {
            MemberUp memberUp = JSON.parseObject(message,MemberUp.class);
            //获取累计消费
            Member byUid = memberService.getByUid(memberUp.getUid());
            User user = userService.getByUid(memberUp.getUid());
            Integer  count = userService.getInviteCount(user.getInviteCode());
            if(byUid == null){
                byUid = new Member();
                byUid.setUid(memberUp.getUid());
                byUid.setMemberExperience(memberUp.getAmount());
            }else{
                byUid.setMemberExperience(byUid.getMemberExperience().add(memberUp.getAmount()));
            }
            int level = sysMemberService.check(byUid.getMemberExperience(),count);
            byUid.setMemberLevel(level);
            memberService.saveOrUpdate(byUid);
        }catch (Exception e){
            return;
        }
    }

}
