package cn.iocoder.byzs.module.ai.service.tts;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.byzs.framework.common.pojo.PageResult;
import cn.iocoder.byzs.framework.common.util.object.BeanUtils;
import cn.iocoder.byzs.module.ai.controller.admin.tts.vo.AiTtsPageReqVO;
import cn.iocoder.byzs.module.ai.controller.admin.tts.vo.AiTtsSaveReqVO;
import cn.iocoder.byzs.module.ai.dal.dataobject.model.AiChatRoleDO;
import cn.iocoder.byzs.module.ai.dal.dataobject.tts.AiTtsDO;
import cn.iocoder.byzs.module.ai.dal.mysql.model.AiChatRoleMapper;
import cn.iocoder.byzs.module.ai.dal.mysql.tts.AiTtsMapper;
import cn.iocoder.byzs.module.ai.util.tts.StreamTtsService;
import cn.iocoder.byzs.module.infra.api.file.FileApi;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.byzs.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.byzs.module.ai.enums.ErrorCodeConstants.TTS_NOT_EXISTS;

/**
 * AI TTS文转音 Service 实现类
 *
 * @author lyb
 */
@Service
@Validated
public class AiTtsServiceImpl implements AiTtsService {

    @Resource
    private AiTtsMapper ttsMapper;

    @Resource
    private AiChatRoleMapper chatRoleMapper;

    @Resource
    private org.springframework.beans.factory.ObjectProvider<StreamTtsService> streamTtsServiceProvider;

    @Resource
    private FileApi fileApi;

    @Override
    public Long createTts(AiTtsSaveReqVO createReqVO) {
        // 插入
        AiTtsDO tts = BeanUtils.toBean(createReqVO, AiTtsDO.class);
        ttsMapper.insert(tts);
        // 返回
        return tts.getId();
    }

    @Override
    public void updateTts(AiTtsSaveReqVO updateReqVO) {
        // 校验存在
        validateTtsExists(updateReqVO.getId());
        // 更新
        AiTtsDO updateObj = BeanUtils.toBean(updateReqVO, AiTtsDO.class);
        ttsMapper.updateById(updateObj);
    }

    @Override
    public void deleteTts(Long id) {
        // 校验存在
        validateTtsExists(id);
        // 删除
        ttsMapper.deleteById(id);
    }

    @Override
        public void deleteTtsListByIds(List<Long> ids) {
        // 校验存在
        validateTtsExists(ids);
        // 删除
        ttsMapper.deleteByIds(ids);
        }

    private void validateTtsExists(List<Long> ids) {
        List<AiTtsDO> list = ttsMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(TTS_NOT_EXISTS);
        }
    }

    private void validateTtsExists(Long id) {
        if (ttsMapper.selectById(id) == null) {
            throw exception(TTS_NOT_EXISTS);
        }
    }

    @Override
    public AiTtsDO getTts(Long id) {
        return ttsMapper.selectById(id);
    }

    @Override
    public PageResult<AiTtsDO> getTtsPage(AiTtsPageReqVO pageReqVO) {
        return ttsMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AiTtsDO> getTtsSimpleListByStatus(Integer status) {
        return ttsMapper.getTtsSimpleListByStatus(status);
    }

    @Override
    public String convertTextToSpeech(Long roleId, String content) {
        // 1. 根据角色id查询角色信息
        AiChatRoleDO chatRole = chatRoleMapper.selectById(roleId);
        if (chatRole == null) {
            throw exception(TTS_NOT_EXISTS);
        }

        // 2. 根据角色的ttsId查询TTS配置
        Long ttsId = chatRole.getTtsId();
        if (ttsId == null) {
            throw exception(TTS_NOT_EXISTS);
        }
        AiTtsDO aiTtsDO = ttsMapper.selectById(ttsId);
        if (aiTtsDO == null) {
            throw exception(TTS_NOT_EXISTS);
        }

        // 3. 使用StreamTtsService将文本转语音
        StreamTtsService streamTtsService = streamTtsServiceProvider.getObject();
        try {
            // 创建音频数据缓冲区
            java.io.ByteArrayOutputStream audioOutputStream = new java.io.ByteArrayOutputStream();
            // 设置音频数据回调
            streamTtsService.setAudioDataCallback(audioData -> {
                try {
                    audioOutputStream.write(audioData);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("写入音频数据失败", e);
                }
            });

            // 开始TTS语音合成
            streamTtsService.startTts(aiTtsDO, OutputFormatEnum.MP3);
            // 发送文本
            streamTtsService.sendText(content);
            // 停止TTS
            streamTtsService.stopTts();

            // 4. 存储语音文件并上传到服务器
            byte[] mp3Data = audioOutputStream.toByteArray();
            String filePath = fileApi.createFile(mp3Data);
            return filePath;
        } catch (Exception e) {
            throw new RuntimeException("文本转语音失败", e);
        } finally {
            // 确保资源被释放
            if (streamTtsService != null) {
                streamTtsService.stopTts();
            }
        }
    }

}