package com.pjilisense.flxai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pjilisense.flxai.base.service.impl.CrudServiceImpl;
import com.pjilisense.flxai.dao.MyDigitalHumanDao;
import com.pjilisense.flxai.dto.MyDigitalHumanDTO;
import com.pjilisense.flxai.dto.VoiceRefFilesDTO;
import com.pjilisense.flxai.entity.MyDigitalHumanEntity;
import com.pjilisense.flxai.service.MyDigitalHumanService;
import cn.hutool.core.util.StrUtil;
import com.pjilisense.flxai.service.VoiceRefFilesService;
import com.pjilisense.flxai.utils.FileUtil;
import com.pjilisense.flxai.utils.TtsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * ${comments}
 *
 * @author liushujing liushujing@philisense.com
 * @since 1.0.0 2025-02-26
 */
@Service
public class MyDigitalHumanServiceImpl extends CrudServiceImpl<MyDigitalHumanDao, MyDigitalHumanEntity, MyDigitalHumanDTO> implements MyDigitalHumanService {

    @Autowired
    VoiceRefFilesService voiceRefFilesService;

    @Autowired
    TtsUtils ttsUtils;

    @Autowired
    FileUtil fileUtil;

    @Override
    public QueryWrapper<MyDigitalHumanEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<MyDigitalHumanEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public MyDigitalHumanDTO genVideo(MyDigitalHumanDTO dto) {

        //TODO:gen generate code here
        //1.generate voice by text and select voiceid
        String voiceId = dto.getVoiceid();
        VoiceRefFilesDTO voiceRefFilesDTO = voiceRefFilesService.get(voiceId);
        String dir = voiceRefFilesDTO.getVoiceServerDir();
        String text = dto.getText();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String monthpath = sdf.format(new Date()).substring(0,6);
        String relPath = "/genvoice/"+monthpath+"/"+ UUID.randomUUID().toString().replace("-","")+".wav";
        String destFile = fileUtil.getFilepath(relPath);
        boolean ttsres = ttsUtils.sendText(text,dir,destFile);
        if(ttsres==true){
            dto.setVoicedir(relPath);
        } else {
            throw new RuntimeException("生成音频失败！");
        }
        //2.生成视频

        if(dto.getId()!=null&&dto.getId().length()>0){
            update(dto);
        } else {
            save(dto);
        }
        return dto;
    }
}