package com.backendsys.service.SDKService.SDKTencent;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.backendsys.entity.Ai.Aiivh.AiivhMakeBroadcastAudioTask.AiivhMakeBroadcastAudioTaskDTO;
import com.backendsys.entity.Ai.Aiivh.AiivhMakeBroadcastTask.AiivhMakeBroadcastTaskDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static com.backendsys.service.SDKService.SDKTencent.SDKTencentAiVirtualmanServiceImpl.convertObjectToMap;

@Service
public class SDKTencentAiVideoServiceImpl implements SDKTencentAiVideoService {

    @Value("${tencent.ivh.app-key}")
    private String appKey;

    @Value("${tencent.ivh.access-token}")
    private String accessToken;

    @Value("${tencent.ivh.empty-app-key}")
    private String emptyAppKey;

    @Value("${tencent.ivh.empty-access-token}")
    private String emptyAccessToken;

    @Autowired
    private SDKTencentService sdkTencentService;


    /**
     * [腾讯-数智人] 创建 定制音频
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> customPersonaudioMake(AiivhMakeBroadcastAudioTaskDTO aiivhMakeBroadcastAudioTaskDTO) {

        try {

            // 基于实体类，将 anchor_name 转换为 AnchorName (将下划线转为大驼峰)
            Map<String, Object> payload = new HashMap<>();
            convertObjectToMap(aiivhMakeBroadcastAudioTaskDTO, payload);
            Map<String, Object> resultMap = Collections.singletonMap("Payload", payload);
            String bodyData = JSONUtil.toJsonStr(resultMap);

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

            // -- Http Request --------------------------------------------
            Map<String, Object> signature = sdkTencentService.getSignature(appKey, accessToken); // 获得 Signature 签名

            String url = "https://gw.tvs.qq.com/v2/ivh/videomaker/broadcastservice/tts";
            URI uriWithParams = UriComponentsBuilder.fromUriString(url)
                    .queryParam("appkey", signature.get("appkey"))
                    .queryParam("signature", "{signature}")
                    .queryParam("timestamp", signature.get("timestamp"))
                    .build(signature.get("signature"));

            // Http 远程调用
            Map<String, Object> resp = WebClient.create()
                    .method(HttpMethod.POST)
                    .uri(uriWithParams)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .bodyValue(bodyData)
                    .retrieve().bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
                    })
                    .block();

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

//            // 判断 任务是否确认成功 (是，则更新数据库记录)
//            Integer respHeaderCode = (Integer) MapUtil.get(resp, "Header.Code");
//            if (respHeaderCode == 0) {
//
//            }

            return resp;

        } catch(IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }



    /**
     * [腾讯-数智人] 创建 定制视频
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> customPersonvideoMake(AiivhMakeBroadcastTaskDTO aiivhMakeBroadcastTaskDTO) {

        try {

            // 基于实体类，将 anchor_name 转换为 AnchorName (将下划线转为大驼峰)
            Map<String, Object> payload = new HashMap<>();
            convertObjectToMap(aiivhMakeBroadcastTaskDTO, payload);
            Map<String, Object> resultMap = Collections.singletonMap("Payload", payload);
            String bodyData = JSONUtil.toJsonStr(resultMap);

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

            // -- Http Request --------------------------------------------
            Map<String, Object> signature = sdkTencentService.getSignature(appKey, accessToken); // 获得 Signature 签名

            String url = "https://gw.tvs.qq.com/v2/ivh/videomaker/broadcastservice/videomakeadvanced";
            URI uriWithParams = UriComponentsBuilder.fromUriString(url)
                    .queryParam("appkey", signature.get("appkey"))
                    .queryParam("signature", "{signature}")
                    .queryParam("timestamp", signature.get("timestamp"))
                    .build(signature.get("signature"));

            // Http 远程调用
            Map<String, Object> resp = WebClient.create()
                    .method(HttpMethod.POST)
                    .uri(uriWithParams)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .bodyValue(bodyData)
                    .retrieve().bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
                    })
                    .block();

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

//            // 判断 任务是否确认成功 (是，则更新数据库记录)
//            Integer respHeaderCode = (Integer) MapUtil.get(resp, "Header.Code");
//            if (respHeaderCode == 0) {
//
//            }

            return resp;

        } catch(IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * [腾讯-数智人] 查询 视频定制视频制作进度
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> customPersonvideoGetprogress(String task_id) {
        // -- Http Request --------------------------------------------
        Map<String, Object> signature = sdkTencentService.getSignature(appKey, accessToken); // 获得 Signature 签名

        String url = "https://gw.tvs.qq.com/v2/ivh/videomaker/broadcastservice/getprogress";
        URI uriWithParams = UriComponentsBuilder.fromUriString(url)
                .queryParam("appkey", signature.get("appkey"))
                .queryParam("signature", "{signature}")
                .queryParam("timestamp", signature.get("timestamp"))
                .build(signature.get("signature"));

        String jsonStr = "{\"Payload\": {\"TaskId\": \"" + task_id + "\"}}";
        JSONObject bodyData = new JSONObject(jsonStr);

//        System.out.println("task_id: " + task_id);
//        System.out.println("bodyData: " + bodyData);

        // Http 远程调用
        Map<String, Object> resp = WebClient.create()
                .method(HttpMethod.POST)
                .uri(uriWithParams)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .bodyValue(bodyData.toString())
                .retrieve().bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
                })
                .block();

        //        // 临时数据 (模拟成功)
        //        Map<String, Object> tempPayload = new LinkedHashMap<>();
        //        tempPayload.put("StageInfo", "{\"TrainResult\":[\"url1\",\"url2\"],\"RejectReason\":\"\",\"TrainRecord\":[{\"StartTime\":\"2023-11-01 23:00:17\",\"Record\":[\"url1\",\"url2\"]}]}");
        //        tempPayload.put("Status", "MAKING");
        //        tempPayload.put("StatusV2", "WAIT_PROCESS");
        //        tempPayload.put("FailMessage", "");
        //        tempPayload.put("StageV2", "CONFIRM");
        //        resp.put("Payload", tempPayload);

//        System.out.println("customPersonvideoGetprogress:");
//        System.out.println(resp);

//        // 判断 任务是否查询成功 (是，则更新数据库记录)
//        Integer respHeaderCode = (Integer) MapUtil.get(resp, "Header.Code");
//        if (respHeaderCode == 0) {
//
//            // 任务失败
//            String respPayloadStatus = (String) MapUtil.get(resp, "Payload.Status");

//            /**
//             * 更新任务
//             */
//            AiPersonDTO aiPersonDTO = new AiPersonDTO();
//            // [查询] 自身 UserId
//            Long user_id = httpRequestAspect.getUserId();
//            aiPersonDTO.setUser_id(user_id);
//            aiPersonDTO.setTask_id(task_id);
//            aiPersonDTO.setTask_status(respPayloadStatus);
//            aiPersonDTO.setTask_status_info(respPayloadFailMessage);
//            aiPersonDTO.setStage_status(respPayloadStage);  // 返回值 { Payload } 跟文档不一样，文档是 { StageV2 }，实际上是返回 { Stage }
//
//            // 返回值 { StageInfo } 跟文档不一样，文档是：
//            // {\"TrainResult\":[\"url1\",\"url2\"],\"RejectReason\":\"\",\"TrainRecord\":[{\"StartTime\":\"2023-11-01 23:00:17\",\"Record\":[\"url1\",\"url2\"]}]}
//            // 实际上是：
//            // {"TrainResult":["https://videomaker-resources.ivh.qq.com/broadcast/Basic/video/78f7fb6c6fec4311921ede313f3c7cd5.mp4","https://videomaker-resources.ivh.qq.com/broadcast/Basic/video/259044134def40f69fdfdc1cd6c6c952.mp4"],"RejectReason":"","TrainRecord":[{"StartTime":"2024-03-21 18:06:59","Record":["https://videomaker-resources.ivh.qq.com/broadcast/Basic/video/78f7fb6c6fec4311921ede313f3c7cd5.mp4","https://videomaker-resources.ivh.qq.com/broadcast/Basic/video/259044134def40f69fdfdc1cd6c6c952.mp4"]}]}
//            if (!respPayloadStageInfo.isEmpty()) {
//                JSONObject StageInfoObject = JSONUtil.parseObj(respPayloadStageInfo);
//                String result = JSONUtil.toJsonStr(StageInfoObject);
//                aiPersonDTO.setResult(result);
//            }
//            // [Post] 根据 Payload 返回的状态来更新
//            aiPersonService.updateAiPerson(aiPersonDTO);

//        }

        return resp;
    }


}
