package com.sonic.bear.event.outer.handler;

import com.sonic.bear.event.outer.EventType;
import com.sonic.bear.event.outer.payload.UserCratedPayload;
import com.sonic.bear.lib.output.BaseUserInfoOutput;
import com.sonic.bear.service.CommonMessageService;
import com.sonic.bear.service.UserSearchService;
import com.sonic.common.event.Event;
import com.sonic.common.event.EventConsumer;
import com.sonic.common.event.EventHandler;
import com.sonic.lion.lib.client.PayClient;
import com.sonic.lion.lib.input.PlatformGiftInput;
import com.sonic.pigeon.lib.client.ImUserClient;
import com.sonic.pigeon.lib.enums.ImUserTypeEnum;
import com.sonic.pigeon.lib.input.CreateImUserInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author coder
 */
@Slf4j
@Component
public class UserCreatedThenHandler implements EventHandler, InitializingBean {

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private ImUserClient imUserClient;
    @Autowired
    private PayClient payClient;
    @Autowired
    private CommonMessageService commonMessageService;
    @Autowired
    private UserSearchService userSearchService;

    @Override
    public void onEvent(Event event) {
        UserCratedPayload payload = event.normalizedData(UserCratedPayload.class);
        log.info("UserCreatedThenHandler payload:{}", payload);
        if (payload.getUserId() == null) {
            return;
        }
        Long userId = payload.getUserId();
        //获取用户信息
        BaseUserInfoOutput baseUserInfo = userSearchService.baseUserInfo(userId);
        //设置创建IM账号的入参对象
        CreateImUserInput createImUserInput = new CreateImUserInput();
        createImUserInput.setUserId(baseUserInfo.getUserId());
        createImUserInput.setNickname(baseUserInfo.getNickname());
        createImUserInput.setHeadImage(baseUserInfo.getHeadImage());
        createImUserInput.setImUserType(ImUserTypeEnum.u);
        //RPC 调用IM创建账号
        imUserClient.createImUser(createImUserInput);
        //RPC 初始化账号钱包
        payClient.createAccountBuff(userId);
        //用户注册发送欢迎系统通知
        commonMessageService.userRegisterSendMessage(userId);
        //赠送5个BUFF
        PlatformGiftInput platformGiftInput = new PlatformGiftInput();
        platformGiftInput.setPlatform("1");
        platformGiftInput.setUid(userId);
        platformGiftInput.setName(PlatformGiftInput.Type.NEW_USER_GIFT.getBizType().getDesc());
        platformGiftInput.setCreateTime(LocalDateTime.now());
        platformGiftInput.setAmount(500L);
        platformGiftInput.setType(PlatformGiftInput.Type.NEW_USER_GIFT);
        payClient.platformGift(platformGiftInput);
    }

    @Override
    public void afterPropertiesSet() {
        eventConsumer.registerHandler(EventType.USER_CREATED.getEventCode(), this);
    }
}
