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

import com.alibaba.fastjson.JSONObject;
import com.sonic.common.event.Event;
import com.sonic.common.event.EventConsumer;
import com.sonic.common.event.EventHandler;
import com.sonic.common.utils.RedisLock;
import com.sonic.cow.event.outer.EventType;
import com.sonic.cow.event.outer.payload.AiChatPayload;
import com.sonic.cow.service.ChatHandlerService;
import com.sonic.cow.utils.RedisKeyUtils;
import com.sonic.pigeon.lib.bo.AttachBo;
import com.sonic.pigeon.lib.enums.MessageTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author chenjun
 */
@Slf4j
@Component
public class AiChatV2Handler implements EventHandler, InitializingBean {

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private ChatHandlerService chatHandlerService;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;

    @Override
    public void onEvent(Event event) {
        //执行AI聊天的逻辑
        AiChatPayload payload = event.normalizedData(AiChatPayload.class);
        //非自定义图片消息的话直接给拒绝掉
        AttachBo attachBo = StringUtils.isEmpty(payload.getAttach()) ? null : JSONObject.parseObject(payload.getAttach(), AttachBo.class);
        if(MessageTypeEnum.CUSTOM == payload.getMessageType() && (attachBo == null || !"IMAGE".equalsIgnoreCase(attachBo.getType()))) {
            return;
        }
        //加锁处理，防止并发访问
        RedisLock redisLock = new RedisLock(redisKeyUtils.aiChatLockKey(payload.getFromUserId(), payload.getToUserId()), redisWrapper);
        redisLock.tryAcquireRun(60 * 1000, 60 * 1000, () -> {
            chatHandlerService.handle(payload, attachBo);
            return true;
        });
    }


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