package cn.newfeifan.mall.module.distri.mq.consumer.sharePath;

import cn.newfeifan.mall.module.distri.controller.app.sharepath.vo.SharePathSaveReqVO;
import cn.newfeifan.mall.module.distri.service.sharelink.ShareLinkService;
import cn.newfeifan.mall.module.distri.service.sharepath.SharePathService;
import cn.newfeifan.mall.module.member.message.share.SharePathCreateMessage;
import cn.newfeifan.mall.module.member.message.user.MemberUserCreateMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.member.enums.ErrorCodeConstants.RELOAD_REGISTER;

/**
 * 用户注册时，发送优惠劵的消费者，基 {@link MemberUserCreateMessage} 消息
 *
 * @author owen
 */
@Component
@Slf4j
public class AddSharePathConsumer {

    @Resource
    private SharePathService sharePathService;
    @Resource
    private ShareLinkService shareLinkService;

    @EventListener
//    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(SharePathCreateMessage message) {
        log.info("[onMessage][消息内容({})]", message);

        Long ancestor;
        if (message.getLinkId() != null) {
            ancestor = shareLinkService.getCreateUserIdById(message.getLinkId());
        } else {
            throw exception(RELOAD_REGISTER);
        }

        SharePathSaveReqVO saveReqVO = SharePathSaveReqVO.builder()
                .ancestor(ancestor)
                .descendant(message.getDescendant()).build();
        sharePathService.createSharePathByUserId(saveReqVO);
    }

}
