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

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.service.tts.AiTtsService;
import cn.iocoder.byzs.module.ai.service.tts.AliyunTtsService;
import cn.iocoder.byzs.module.ai.service.tts.DouBaoTtsService;
import cn.iocoder.byzs.module.infra.api.file.FileApi;
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 DouBaoTtsService douBaoTtsService;

    @Resource
    private AliyunTtsService aliyunTtsService;

    @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, String command) {
        // 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);
        }

        byte[] mp3Data;
        // 3. 根据平台选择不同的TTS服务
        if ("DouBao".equals(aiTtsDO.getPlatform())) {
            // 使用豆包TTS服务
            try {
                mp3Data = douBaoTtsService.convertTextToSpeech(aiTtsDO, content, command);
            } catch (Exception e) {
                throw new RuntimeException("豆包文本转语音失败", e);
            }
        } else {
            // 使用阿里云TTS服务
            try {
                mp3Data = aliyunTtsService.convertTextToSpeech(aiTtsDO, content);
            } catch (Exception e) {
                throw new RuntimeException("阿里云文本转语音失败", e);
            }
        }

        // 4. 存储语音文件并上传到服务器
        String filePath = fileApi.createFile(mp3Data);
        return filePath;
    }
}