package com.backendsys.service.Ai.Aiivh;

import com.backendsys.aspect.HttpRequestAspect;
import com.backendsys.entity.Ai.Aiivh.AiivhMakeBroadcastAudioTask.*;
import com.backendsys.exception.CustException;
import com.backendsys.mapper.Ai.Aiivh.AiivhAnchorMapper;
import com.backendsys.mapper.Ai.Aiivh.AiivhMakeBroadcastAudioTaskMapper;
import com.backendsys.service.SDKService.SDKTencent.SDKTencentAiVideoService;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class AiivhMakeBroadcastAudioTaskServiceImpl implements AiivhMakeBroadcastAudioTaskService {

    // 引用配置变量
    @Value("${HTTP_BASE_URI}")
    private String baseUrl;

    @Autowired
    private HttpRequestAspect httpRequestAspect;

    @Autowired
    private AiivhAnchorMapper aiivhAnchorMapper;
    @Autowired
    private SDKTencentAiVideoService sdkTencentAiVideoService;

    @Autowired
    private AiivhMakeBroadcastAudioTaskMapper aiivhMakeBroadcastAudioTaskMapper;


    @Override
    public Map<String, Object> queryAiivhMakeBroadcastAudioTask(Integer pageNum, Integer pageSize, AiivhMakeBroadcastAudioTaskDTO aiivhMakeBroadcastAudioTaskDTO) {
        // 分页查询
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
            PageHelper.getLocalPage().setPageSizeZero(true);
        }
        // 分页输出 (自定义)
        List<Map<String, Object>> list = aiivhMakeBroadcastAudioTaskMapper.queryAiivhMakeBroadcastAudioTask(aiivhMakeBroadcastAudioTaskDTO);

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

    @Override
    public Map<String, Object> queryAiivhMakeBroadcastAudioTaskDetail(AiivhMakeBroadcastAudioTaskDTO aiivhMakeBroadcastAudioTaskDTO) throws IOException {

        Map<String, Object> detail = aiivhMakeBroadcastAudioTaskMapper.queryAiivhMakeBroadcastAudioTaskDetail(aiivhMakeBroadcastAudioTaskDTO);
        if (detail == null) {
            throw new CustException("(task_id) 找不到任务");
        }
        if (!aiivhMakeBroadcastAudioTaskDTO.getUser_id().equals((Long) detail.get("user_id"))) {
            throw new CustException("(task_id) 任务没有访问权限");
        }

        System.out.println("detail:");
        System.out.println(detail);

        // -- 如果是任务 CONFIRM 状态，则刷新状态
        String task_status = (String) detail.get("task_status");
        if (task_status.equals("MAKING") || task_status.equals("COMMIT")) {

            // 访问详情的同时，刷新一次进度
            String task_id = aiivhMakeBroadcastAudioTaskDTO.getTask_id();
            Map<String, Object> resp = sdkTencentAiVideoService.customPersonvideoGetprogress(task_id);
            System.out.println("customPersonvideoGetprogress:");
            System.out.println(resp);

            Integer respHeaderCode = (Integer) MapUtil.get(resp, "Header.Code");
            if (respHeaderCode == 0) {
                AiivhMakeBroadcastAudioTaskDTO vo = new AiivhMakeBroadcastAudioTaskDTO();
                vo.setTask_id(task_id);
                vo.setRequest_id((String) MapUtil.get(resp, "Header.RequestID"));
                vo.setTask_status((String) MapUtil.get(resp, "Payload.Status"));
                vo.setTask_reason((String) MapUtil.get(resp, "Payload.FailMessage"));
                vo.setResult_media_url((String) MapUtil.get(resp, "Payload.MediaUrl"));
                vo.setResult_media_duration((Long) MapUtil.get(resp, "Payload.Duration"));
                vo.setResult_subitles_url((String) MapUtil.get(resp, "Payload.SubtitlesUrl"));
                aiivhMakeBroadcastAudioTaskMapper.updateAiivhMakeBroadcastAudio(vo);
            }
        }

//        // 测试数据
//        AiivhMakeBroadcastAudioTaskDTO vo = new AiivhMakeBroadcastAudioTaskDTO();
//        vo.setTask_id(aiivhMakeBroadcastAudioTaskDTO.getTask_id());
//        vo.setRequest_id("aaaa");
//        vo.setTask_status("SUCCESS");
//        vo.setTask_reason("成功");
//
//        String media_url = "http://cos.daoguyujiamcn.com/materials/baidu/ai-generate-video/audio/0%EF%BC%9A%E5%B0%8F%E7%BE%8E-%E5%A5%B3.mp3";
//        vo.setResult_media_url(media_url);
//        vo.setResult_media_duration(7000L);
//        aiivhMakeBroadcastAudioTaskMapper.updateAiivhMakeBroadcastAudio(vo);

        return detail;
    }


    /**
     * 文档中心 > 腾讯云智能数智人 > API 接入 > 视频生成服务 API 文档-v4.9.7 > 视频制作接口-进阶版
     * https://cloud.tencent.com/document/product/1240/81269#ec658a0e-cd14-48c2-af38-9ca07936a513
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertAiivhMakeBroadcastAudioTask(AiivhMakeBroadcastAudioTaskDTO aiivhMakeBroadcastAudioTaskDTO) throws IOException {

        // [查询] 自身 UserId
        Long user_id = httpRequestAspect.getUserId();
        aiivhMakeBroadcastAudioTaskDTO.setUser_id(user_id);

        System.out.println("aiivhMakeBroadcastAudioTaskDTO:");
        System.out.println(aiivhMakeBroadcastAudioTaskDTO);
        System.out.println("----------------------------------------");

        // 文档中心 > 腾讯云智能数智人 > 服务端 API 接入 > 视频生成服务 API 文档-v4.9.7 > 视频制作接口-进阶版
        // https://cloud.tencent.com/document/product/1240/81269

        Map<String, Object> resp = sdkTencentAiVideoService.customPersonaudioMake(aiivhMakeBroadcastAudioTaskDTO);
        Integer respHeaderCode = (Integer) MapUtil.get(resp, "Header.Code");
        if (respHeaderCode != null && respHeaderCode != 0) {
            String respHeaderMessage = (String) MapUtil.get(resp, "Header.Message");
            throw new CustException("(" + respHeaderCode + ") " + respHeaderMessage);
        }
        String task_id = (String) MapUtil.get(resp, "Payload.TaskId");
        String request_id = (String) MapUtil.get(resp, "Payload.RequestID");
        aiivhMakeBroadcastAudioTaskDTO.setTask_id(task_id);
        aiivhMakeBroadcastAudioTaskDTO.setRequest_id(request_id);

//        // 测试数据
//        String task_id = "888888";
//        aiivhMakeBroadcastAudioTaskDTO.setTask_id(task_id);
//        aiivhMakeBroadcastAudioTaskDTO.setRequest_id("99999");


        long insert = aiivhMakeBroadcastAudioTaskMapper.insertAiivhMakeBroadcastAudio(aiivhMakeBroadcastAudioTaskDTO);
        if (insert == 1) {
            return Map.of("task_id", task_id);
        }

        return null;
    }

    /**
     * 当用户增加回调url时，将把视频制作结果以固定格式发送post请求到该url地址，固定格式见 附录二： 回调请求体格式。
     * 需注意：
     * 1. 限制CallbackUrl长度小于1000
     * 2. 只发送一次请求，无论是哪种问题导致的请求失败，都不会再进行发送。
     * https://cloud.tencent.com/document/product/1240/81269
     * https://cloud.tencent.com/document/product/1240/81279
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateAiivhMakeBroadcastAudioTask(AiivhMakeBroadcastAudioTaskDTO aiivhMakeBroadcastAudioTaskDTO) {
        long update = aiivhMakeBroadcastAudioTaskMapper.updateAiivhMakeBroadcastAudio(aiivhMakeBroadcastAudioTaskDTO);
        if (update == 1) {
            return Map.of("task_id", aiivhMakeBroadcastAudioTaskDTO.getTask_id());
        }
        return null;
    }


    /**
     * 删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deleteAiivhMakeBroadcastAudioTask(AiivhMakeBroadcastAudioTaskDTO aiivhMakeBroadcastAudioTaskDTO) {
        aiivhMakeBroadcastAudioTaskMapper.deleteAiivhMakeBroadcastAudio(aiivhMakeBroadcastAudioTaskDTO);
        return Map.of("task_id", aiivhMakeBroadcastAudioTaskDTO.getTask_id());
    }
}
