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.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.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.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;

@Service
public class MediaTtvServiceImpl implements MediaTtvService {

    @Autowired
    private MediaTtvDao mediaTtvDao;

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

    @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("任务记录不存在，请重新生成");

        // -- 静态赋值 -------------------------------
        String request_params_str = detail.getRequest_params();
        JSONObject request_params = JSONUtil.parseObj(request_params_str);

        // source
        List<MediaTtvSource> source = new ArrayList<>();
        JSONObject request_params_source = JSONUtil.parseObj(request_params.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.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());

            // -- 静态赋值 ------------------------
            // progress: 查询进度
            // System.out.println("(queryMediaTtv) user_id: " + detail.getUser_id() + ", job_id: " + mediaTtv.getJob_id() + ", progress: " + response.getProgress());
            detail.setJob_progress(response.getProgress());
            // ----------------------------------

            if (StrUtil.isNotEmpty(response.getVideo_origin_url())) {
                String video_url = "";
                String object_key = "";

                // -- [转存] 将查询结果转存 --------------------------------------
                Integer UPLOAD_TARGET = Convert.toInt(sysCommonService.getCommonByTag("UPLOAD_TARGET"));
                // target: 上传目标 (-1:本地, 1:腾讯云, 2:阿里云, 3.抖音云)
                if (UPLOAD_TARGET == 1) {
                    SysFileResult sysFileResult = tencentCosService.uploadFileFromUrlToCOS(response.getVideo_origin_url());
                    object_key = sysFileResult.getKey();
                    video_url = sysFileResult.getDomain() + "/" + sysFileResult.getKey();
                }
                // 3: 抖音云
                if (UPLOAD_TARGET == 3) {

                }
                // ------------------------------------------------------------

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

        }
        return detail;

    }

}
