package com.sonic.frog.event.inner.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sonic.common.event.Event;
import com.sonic.common.event.EventConsumer;
import com.sonic.common.event.EventHandler;
import com.sonic.frog.domain.entity.AiUser;
import com.sonic.frog.event.inner.EventType;
import com.sonic.frog.event.inner.payload.AiImInfoPayload;
import com.sonic.frog.service.AiUserService;
import com.sonic.pigeon.lib.client.ImUserClient;
import com.sonic.pigeon.lib.enums.ImUserTypeEnum;
import com.sonic.pigeon.lib.input.CreateImUserInput;
import com.sonic.pigeon.lib.input.EditImUserInput;
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.sql.Wrapper;

/**
 * @author code
 */
@Slf4j
@Component
public class AIImInfoHandler implements EventHandler, InitializingBean {

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private AiUserService aiUserService;
    @Autowired
    private ImUserClient imUserClient;

    @Override
    public void onEvent(Event event) {
        AiImInfoPayload payload = event.normalizedData(AiImInfoPayload.class);
        //获取IM的基础信息
        AiUser aiUser = aiUserService.getOne(Wrappers.<AiUser>lambdaQuery().eq(AiUser::getAiId, payload.getAiId()));
        //根据操作类型判断是创建还是修改
        if(AiImInfoPayload.OptType.ADD == payload.getOptType()){
            CreateImUserInput input = new CreateImUserInput();
            input.setUserId(aiUser.getAiId());
            input.setNickname(aiUser.getNickname());
            input.setHeadImage(aiUser.getHeadImg());
            input.setImUserType(ImUserTypeEnum.r);
            imUserClient.createImUser(input);
        }else if(AiImInfoPayload.OptType.UPDATE == payload.getOptType()){
            EditImUserInput input = new EditImUserInput();
            input.setImUserType(ImUserTypeEnum.r);
            input.setUserId(aiUser.getAiId());
            input.setNickname(aiUser.getNickname());
            input.setHeadImage(aiUser.getHeadImg());
            imUserClient.editImUser(input);
        }
    }

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