package com.backendsys.service.Ai;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.backendsys.entity.Ai.AiGenerateVideoDTO;
import com.backendsys.exception.CustException;
import com.backendsys.mapper.Ai.AiGenerateVideoMapper;
import com.backendsys.mapper.Ai.AiGenerateVideoTimbreMapper;
import com.backendsys.service.SDKService.SDKBaidu.SDKBaiduAiGenerateVideoService;
import com.backendsys.utils.ConvertToUtil;
import com.backendsys.utils.ListUtil;
import com.backendsys.utils.MapUtil;
import com.backendsys.utils.response.PageInfoResult;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AiGenerateVideoServiceImpl implements AiGenerateVideoService {

    @Autowired
    private AiGenerateVideoMapper aiGenerateVideoMapper;
    @Autowired
    private AiGenerateVideoTimbreMapper aiGenerateVideoTimbreMapper;

    @Autowired
    private SDKBaiduAiGenerateVideoService sdkBaiduAiGenerateVideoService;

    /**
     * [百度-AI成片] 查询成片任务进度
     */
    public Map<String, Object> getGenerateVideoProgressAndUpdate(Long job_id, Long user_id) {

        Map<String, Object> resp = sdkBaiduAiGenerateVideoService.getGenerateVideoProgress(job_id);

        Integer error_code = (Integer) MapUtil.get(resp, "error_code");
        if (error_code == null || error_code == 0) {
            String statusCode = Convert.toStr(MapUtil.get(resp, "data.statusCode"));
            if (!statusCode.equals("3")) {
                //  更新进度
                AiGenerateVideoDTO aiGenerateVideoDTO = new AiGenerateVideoDTO();
                aiGenerateVideoDTO.setJob_id(job_id);
                aiGenerateVideoDTO.setUser_id(user_id);
//                aiGenerateVideoDTO.setJob_status((String) MapUtil.get(resp, "data.statusCode"));
//                aiGenerateVideoDTO.setResult_video_url((String) MapUtil.get(resp, "data.videoAddr"));
//                aiGenerateVideoDTO.setResult_fail_reason((String) MapUtil.get(resp, "data.failReason"));

                aiGenerateVideoDTO.setJob_status(Convert.toStr(MapUtil.get(resp, "data.statusCode")));
                aiGenerateVideoDTO.setResult_video_url(Convert.toStr(MapUtil.get(resp, "data.videoAddr")));
                aiGenerateVideoDTO.setResult_fail_reason(Convert.toStr(MapUtil.get(resp, "data.failReason")));

//                // 任务所使用的素材库，original为原文素材 (不安全接口)
//                List<String> mediaLibsList = (List<String>) MapUtil.get(resp, "data.mediaLibs");
//                if (mediaLibsList != null) {
//                    System.out.println(mediaLibsList);
//                    // aiGenerateVideoDTO.setResult_points((String) MapUtil.get(resp, "data.mediaLibs.points"));
//                }
//                System.out.println(aiGenerateVideoDTO);
                aiGenerateVideoMapper.updateAiGenerateVideo(aiGenerateVideoDTO);
            }
        }
        // {log_id=1789959190223908487, error_msg=图片可能存在低质、格式错误等问题, error_code=30701}
        if (error_code == 30701) {
            AiGenerateVideoDTO aiGenerateVideoDTO = new AiGenerateVideoDTO();
            aiGenerateVideoDTO.setJob_id(job_id);
            aiGenerateVideoDTO.setUser_id(user_id);
            aiGenerateVideoDTO.setJob_status("1");
            aiGenerateVideoDTO.setResult_fail_reason(Convert.toStr(resp.get("error_msg")));
            aiGenerateVideoMapper.updateAiGenerateVideo(aiGenerateVideoDTO);
        }

        return resp;
    }

    /**
     * 定制成片任务
     */
    public Map<String, Object> makeGenerateVideoAndInsert(AiGenerateVideoDTO aiGenerateVideoDTO) {

        // [远程] 发起定制
        Map<String, Object> resp = sdkBaiduAiGenerateVideoService.makeGenerateVideo(aiGenerateVideoDTO);

        System.out.println("makeGenerateVideoAndInsert resp:");
        System.out.println(resp);

        // 提交定制成功后，将数据插入表；失败则抛出错误

//        Integer error_code = (Integer) MapUtil.get(resp, "error_code");
        Integer error_code = Convert.toInt(MapUtil.get(resp, "error_code"));
        if (error_code == null || error_code == 0) {

            System.out.println("setJob_id: " + MapUtil.get(resp, "data.jobId"));

            aiGenerateVideoDTO.setJob_id(Convert.toLong(MapUtil.get(resp, "data.jobId")));
            // 数组 转 字符串
            String resolutionString = ConvertToUtil.convertToString(aiGenerateVideoDTO.getResolution());
            aiGenerateVideoDTO.setResolutionString(resolutionString);

            System.out.println("insertAiGenerateVideo aiGenerateVideoDTO");
            System.out.println(aiGenerateVideoDTO);
            aiGenerateVideoMapper.insertAiGenerateVideo(aiGenerateVideoDTO);
        } else {
            String error_message = Convert.toStr(MapUtil.get(resp, "error_msg"));
            throw new CustException("(" + error_code + ") " + error_message);
        }

        return resp;

    }

    /**
     * 查询全部配音列表
     */
    public List<Map<String, Object>> getGenerateVideoTimbre() {
        return aiGenerateVideoTimbreMapper.queryAiGenerateVideoTimbre();
    }

    /**
     * 查询 配音列表
     */
    public Map<String, Object> queryAiGenerateVideoList(Integer pageNum, Integer pageSize, AiGenerateVideoDTO aiGenerateVideoDTO) {
        // 分页查询
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
            PageHelper.getLocalPage().setPageSizeZero(true);
        }
        // 分页输出 (自定义)
        List<Map<String, Object>> list = aiGenerateVideoMapper.queryAiGenerateVideoList(aiGenerateVideoDTO);

        // 将 resolution 从 字符串 转为 数组类型
        ListUtil.convertToArray(list, "resolution");
        // 将 source 从 字符串 转为 JSON类型
        ListUtil.convertToJsonObjects(list, "source");

        PageInfoResult pageInfoResult = new PageInfoResult(list);
        return pageInfoResult.toMap();
    }

    /**
     * 查询 配音详情
     */
    public Map<String, Object> queryAiGenerateVideoDetail(AiGenerateVideoDTO aiGenerateVideoDTO) {
        Map<String, Object> response = aiGenerateVideoMapper.queryAiGenerateVideoDetail(aiGenerateVideoDTO);
        if (response == null) { return null; }

        // 将 resolution 从 字符串 转为 数组类型
        int[] resolution = StrUtil.splitToInt(Convert.toStr(response.get("resolution")), ",");
        response.put("resolution", resolution);
        // 将 source 从 字符串 转为 JSON类型
        JSONObject source = JSONUtil.parseObj(Convert.toStr(response.get("source")));
        response.put("source", source);

        // 查询进度，并更新
        getGenerateVideoProgressAndUpdate(aiGenerateVideoDTO.getJob_id(), aiGenerateVideoDTO.getUser_id());

        return response;
    }





}
