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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.sonic.common.event.Event;
import com.sonic.common.event.EventConsumer;
import com.sonic.common.event.EventHandler;
import com.sonic.cow.lib.client.ContentClient;
import com.sonic.cow.lib.client.VoiceClient;
import com.sonic.cow.lib.input.VoiceTtsInput;
import com.sonic.frog.domain.entity.AiUser;
import com.sonic.frog.domain.entity.AiUserExt;
import com.sonic.frog.domain.entity.TimbreDict;
import com.sonic.frog.domain.input.ClassificationListInput;
import com.sonic.frog.event.inner.EventType;
import com.sonic.frog.event.inner.payload.AiChangePayload;
import com.sonic.frog.service.AiUserExtService;
import com.sonic.frog.service.AiUserService;
import com.sonic.frog.service.HomeClassificationService;
import com.sonic.frog.service.TimbreDictService;
import com.sonic.shark.lib.client.S3Client;
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.util.Base64;
import java.util.List;

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

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private AiUserService aiUserService;
    @Autowired
    private HomeClassificationService homeClassificationService;
    @Autowired
    private AiUserExtService aiUserExtService;
    @Autowired
    private VoiceClient voiceClient;
    @Autowired
    private ContentClient contentClient;
    @Autowired
    private S3Client s3Client;
    @Autowired
    private TimbreDictService timbreDictService;


    @Override
    public void onEvent(Event event) {
        AiChangePayload payload = event.normalizedData(AiChangePayload.class);
        log.info("AIChangeHandler payload:{}", payload);
        if (payload.getAiId() == null) {
            return;
        }
        try {
            Long aiId = payload.getAiId();
            //获取ai的基础信息
            AiUser aiUser = aiUserService.getOne(Wrappers.<AiUser>lambdaQuery().eq(AiUser::getAiId, aiId));
            //更新首页缓存
            updateHomeCache(aiUser);
            //开场白更新需要生成开场白语音
            if (payload.getIsDialoguePrologueChange() != null && payload.getIsDialoguePrologueChange()) {
                generateDialoguePrologue(aiId);
            }
            //创建AI生成三条辅助聊天内容
            if (payload.getIsCreate() != null && payload.getIsCreate()) {
                generateSupportingContent(aiUser.getUserId(), aiId);
            }
        } catch (Exception e) {
            log.error("AIChangeHandler error:", e);
        }
    }

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

    /**
     * 更新首页缓存
     *
     * @param aiUser
     */
    private void updateHomeCache(AiUser aiUser) {
        //更新首页对应性格缓存
        String characterCode = aiUser.getCharacterCode();
        ClassificationListInput input = ClassificationListInput.builder()
                .characterCodeList(Lists.newArrayList(characterCode))
                .build();
        homeClassificationService.homeClassificationUpdateCache(input);

        //更新首页All缓存
        ClassificationListInput allInput = ClassificationListInput.builder()
                .build();
        homeClassificationService.homeClassificationUpdateCache(allInput);
    }

    /**
     * 生成开场白语音并上传到S3，保存到表里
     *
     * @param aiId
     */
    private void generateDialoguePrologue(Long aiId) {
        AiUserExt aiUserExt = aiUserExtService.getAiUserExtByAiId(aiId);
        //开场白
        String dialoguePrologue = aiUserExt.getDialoguePrologue();

        //语音类型，音高，语速
        TimbreDict timbreDict = timbreDictService.getTimbreDictByCode(aiUserExt.getDialogueTimbreCode());

        //调用Cow服务内部api生成语音 base64
        VoiceTtsInput voiceTtsInput = new VoiceTtsInput();
        voiceTtsInput.setUserId(-1L);
        voiceTtsInput.setAiId(aiId);
        voiceTtsInput.setText(dialoguePrologue);
        voiceTtsInput.setVoiceType(timbreDict != null ? timbreDict.getVoiceType() : null);
        voiceTtsInput.setSpeechRate(Integer.valueOf(aiUserExt.getDialogueSpeechRate()));
        voiceTtsInput.setPitchRate(Integer.valueOf(aiUserExt.getDialoguePitch()));
        String ttsBase64 = voiceClient.tts(voiceTtsInput);
        //调用Shark服务把语音上传到S3
        byte[] bytes = Base64.getDecoder().decode(ttsBase64);
        String mp3Url = s3Client.uploadAwsS3(bytes, "SOUND_PATH", "mp3");
        //保存生成的语音文件到数据库
        aiUserExtService.updateAiUserDialoguePrologueSound(mp3Url, aiId);
    }

    private void generateSupportingContent(Long userId, Long aiId) {
        //调用Cow服务内部api生成三条辅助聊天内容
        List<String> supContentList = contentClient.genSupContent(userId, aiId);
        //保存到数据库，JSON格式
        aiUserExtService.updateAiUserSupportingContent(supContentList, aiId);
    }
}
