package com.backendsys.modules.ai.media.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.backendsys.exception.CustException;
import com.backendsys.modules.ai.media.dao.MediaTtvDao;
import com.backendsys.modules.ai.media.entity.JobStatusEnums;
import com.backendsys.modules.ai.media.entity.MediaTtv;
import com.backendsys.modules.ai.media.entity.MediaTtvConfig;
import com.backendsys.modules.ai.media.entity.MediaTtvSource;
import com.backendsys.modules.ai.media.service.MediaTtvService;
import com.backendsys.modules.common.config.security.utils.SecurityUtil;
import com.backendsys.modules.sdk.baidu.bce.entity.BaiduBceMediaJob;
import com.backendsys.modules.sdk.baidu.bce.entity.BaiduBceMediaJobResult;
import com.backendsys.modules.sdk.baidu.bce.service.BaiduBceMediaService;
import com.backendsys.modules.sdk.douyincloud.tos.service.DouyinTosService;
import com.backendsys.modules.sdk.tencentcloud.cos.service.TencentCosService;
import com.backendsys.modules.system.service.SysCommonService;
import com.backendsys.modules.upload.entity.SysFileResult;
import com.backendsys.modules.upload.service.SysFileService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class MediaTtvServiceImpl implements MediaTtvService {

    @Autowired
    private MediaTtvDao mediaTtvDao;

    @Autowired
    private SysCommonService sysCommonService;
    @Autowired
    private TencentCosService tencentCosService;
    @Autowired
    private DouyinTosService douyinTosService;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private BaiduBceMediaService baiduBceMediaService;

    /**
     * 生成图文语音视频
     */
    @Override
    public BaiduBceMediaJob generateMediaTtv(MediaTtv mediaTtv) {

        // 发起任务
        BaiduBceMediaJob response = baiduBceMediaService.generateMediaTtv(mediaTtv);
        String job_id = response.getJob_id();
        if (StrUtil.isNotEmpty(job_id)) {
            // 记录任务
            mediaTtv.setJob_id(job_id);
            mediaTtv.setRequest_params(response.getRequest_params());
            mediaTtv.setResponse_params(response.getResponse_params());
            mediaTtvDao.insert(mediaTtv);
        }
        return response;

    }


    /**
     * 查询图文语音视频
     */
    @Override
    public MediaTtv queryMediaTtv(MediaTtv mediaTtv) {

        // [Get] 查询是否存在生成记录
        MediaTtv detail = mediaTtvDao.selectOne(new LambdaQueryWrapper<MediaTtv>().eq(MediaTtv::getJob_id, mediaTtv.getJob_id()));
        if (detail == null) throw new CustException("任务记录不存在，请重新生成");

        // -- 静态赋值 -------------------------------
        JSONObject request_params_json = JSONUtil.parseObj(detail.getRequest_params());
        JSONObject response_params_json = JSONUtil.parseObj(detail.getResponse_params());
        detail.setRequest_params_json(request_params_json);
        detail.setResponse_params_json(response_params_json);

        // source
        List<MediaTtvSource> source = new ArrayList<>();
        JSONObject request_params_source = JSONUtil.parseObj(request_params_json.get("source"));
        JSONArray request_params_source_structs = JSONUtil.parseArray(request_params_source.get("structs"));
        for(Object obj : request_params_source_structs) {
            JSONObject jsonObject = JSONUtil.parseObj(obj);
            String type = Convert.toStr(jsonObject.get("type"));
            String content = "";
            if ("text".equals(type)) content = Convert.toStr(jsonObject.get("text"));
            if ("image".equals(type)) {
                JSONObject mediaSource = JSONUtil.parseObj(jsonObject.get("mediaSource"));
                content = Convert.toStr(mediaSource.get("url"));
            }
            MediaTtvSource sourceItem = new MediaTtvSource();
            sourceItem.setType(type);
            sourceItem.setContent(content);
            source.add(sourceItem);
        }
        detail.setSource(source);

        // config
        MediaTtvConfig config = new MediaTtvConfig();
        JSONObject request_params_config = JSONUtil.parseObj(request_params_json.get("config"));
        config.setTts_voice_type(Convert.toInt(request_params_config.get("ttsPer")));
        config.setResolution(Convert.toIntArray(request_params_config.get("resolution")));
        detail.setConfig(config);
        // ---------------------------------------

        // 任务状态 (0任务排队中，1任务完成，3任务执行中)
        Integer job_status = detail.getJob_status();
        if (job_status != 1) {

            // [百度AI] AI成片-查询结果
            BaiduBceMediaJobResult response = baiduBceMediaService.queryMediaTtv(mediaTtv.getJob_id());

            // 查询进度百分比
            detail.setJob_progress(response.getProgress());

            // 生成成功
            if (StrUtil.isNotEmpty(response.getVideo_origin_url())) {

                job_status = 1;

                // URL转存文件
                SysFileResult sysFileResult = sysFileService.urlToUploadFile(response.getVideo_origin_url(), SecurityUtil.getUserId());
                String object_key = sysFileResult.getKey();
                String video_url = sysFileResult.getDomain() + "/" + sysFileResult.getKey();

                // [DB] 更新表记录
                detail.setVideo_origin_url(response.getVideo_origin_url());
                detail.setVideo_url(video_url);
                detail.setObject_key(object_key);
                detail.setJob_status(job_status);
                mediaTtvDao.updateById(detail);
            }

        }

        detail.setJob_status_label(JobStatusEnums.jobStatusToLabel(job_status));
        return detail;

    }

}
