package com.backendsys.service.SDKService.SDKTencent;

import cn.hutool.json.JSONUtil;
import com.backendsys.utils.ListUtil;
import com.backendsys.utils.MapUtil;
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.*;

@Service
public class SDKTencentAiTimbreServiceImpl implements SDKTencentAiTimbreService {

    @Autowired
    private SDKTencentService sdkTencentService;

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

    /**
     * 腾讯-数智人-个人资产管理-分页查询音色列表
     * https://cloud.tencent.com/document/product/1240/99703
     */

    /**
     * [内部服务][腾讯-数智人] 获取公共/定制音色 (使用公司账号)
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> initTimbre(Integer pageIndex, Integer pageSize) {

        Map<String, Object> payload = new HashMap<>();
        payload.put("PageIndex", pageIndex);
        payload.put("PageSize", pageSize);
        Map<String, Object> resultMap = Collections.singletonMap("Payload", payload);
        String bodyData = JSONUtil.toJsonStr(resultMap);

        // -- Http Request --------------------------------------------
        /**
         * 这里使用我自己的空白密钥，因为只有未创建自定义形象的账号，才能返回全部形象
         *
         * 我真的无语！
         * - [分页查询小样本] 是返回 公共 或 自定义
         * - [分页查询单色] 是返回 公共 + 自定义 (自定义放在最后面返回)
         */
        // emptyAppKey, emptyAccessToken
        Map<String, Object> signature = sdkTencentService.getSignature(appKey, accessToken); // 获得 Signature 签名

        String url = "https://gw.tvs.qq.com/v2/ivh/crmserver/customerassetservice/describetimbre";
        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.toString())
                .retrieve().bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
                })
                .block();

        return resp;
    }


    /**
     * [内部服务] 获得全部形象音色 (循环调用接口，至到获得全部数据)
     * - 用于遍历并匹配用户ID与音色标识
     * List<Map<String, Object>> virtualmans = getAllVirtualman(pageIndex, pageSize);
     */
    public List<Map<String, Object>> getTimbreOfDepth(Integer pageIndex, Integer pageSize) {

        // 初始化变量
        List<Map<String, Object>> timbre_assets = new ArrayList<>();

        // 第一次调用 initTimbre 方法，并将当前页的数据追加到 timbre_assets 列表中
        Map<String, Object> resp = initTimbre(pageIndex, pageSize);
        Integer total = (Integer) MapUtil.get(resp, "Payload.Total");
        timbre_assets.addAll((List<Map<String, Object>>) MapUtil.get(resp, "Payload.TimbreAssets"));

        // 循环获取所有页的数据
        while (total != null && total > 0 && pageIndex * pageSize <= total) {
            // 准备下一次查询，页码加1
            pageIndex++;
            System.out.println("pageIndex: " + pageIndex);

            // 再次调用 initTimbre 方法获取下一页的数据，并将当前页的数据追加到 timbre_assets 列表中
            resp = initTimbre(pageIndex, pageSize);
            total = (Integer) MapUtil.get(resp, "Payload.Total");
            timbre_assets.addAll((List<Map<String, Object>>) MapUtil.get(resp, "Payload.TimbreAssets"));
        }
        return timbre_assets;
    }


    /**
     * [腾讯-数智人] 获得音色详细信息 (通过音色名称)
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getTimbreObject(String timbre_name) {

        // 循环获得数据列表，直到 total 小于 pageSize
        List<Map<String, Object>> timbre_assets = getTimbreOfDepth(1, 100);

        // 遍历 virtualmans 列表，并将 key 由大驼峰改为下划线命名
        timbre_assets = ListUtil.convertToUnderscoreCase(timbre_assets);

        // 遍历 匹配 anchor_name
        Map<String, Object> result = new LinkedHashMap<>();
        for (Map<String, Object> timbre_asset : timbre_assets) {
            String asset_timbre_name = (String) timbre_asset.get("timbre_name");
            // System.out.println("virtualman_anchor_name: " + asset_timbre_name + ", anchor_name: " + timbre_name);
            // System.out.println(timbre_asset);
            if (asset_timbre_name.equals(timbre_name)) {
                result = timbre_asset;
            }
        }
        return result;
    }




}
