package com.tzld.piaoquan.api.component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class ManagerApiService {

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Value("${manager.api.host:https://testadmin.piaoquantv.com/manager}")
    private String managerApiHost;

    @Value("${video.vector.api.host:http://api-internal.piaoquantv.com/videoVector}")
    private String videoVectorApiHost;

    public JSONObject videoMultiTitleSave(Long videoId, String title) {
        String url = managerApiHost + "/video/multiTitleV2/saveNoAuth";
        JSONObject res = null;
        try {
            JSONObject param = new JSONObject();
            param.put("videoId", videoId);
            param.put("title", title);
            param.put("source", 1);
            String post = httpPoolClient.post(url, param.toJSONString());
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("ManagerApiService videoMultiTitleSave error, videoId={} title={}",
                    videoId, title, e);
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_TITLE_SAVE_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("ManagerApiService videoMultiTitleSave error, videoId={} title={} res={}",
                    videoId, title, res);
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_TITLE_SAVE_FAILED.getCode(),
                    ExceptionEnum.VIDEO_MULTI_TITLE_SAVE_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        return res.getJSONObject("content");
    }

    public JSONObject videoMultiCoverSave(Long videoId, String coverUrl) {
        String url = managerApiHost + "/video/multiCover/saveNoAuth";
        JSONObject res = null;
        try {
            JSONObject param = new JSONObject();
            param.put("videoId", videoId);
            param.put("coverUrl", coverUrl);
            param.put("source", 1);
            String post = httpPoolClient.post(url, param.toJSONString());
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("ManagerApiService videoMultiCoverSave error, videoId={} coverUrl={}",
                    videoId, coverUrl, e);
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_COVER_SAVE_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("ManagerApiService videoMultiCoverSave error, videoId={} coverUrl={} res={}",
                    videoId, coverUrl, res);
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_COVER_SAVE_FAILED.getCode(),
                    ExceptionEnum.VIDEO_MULTI_COVER_SAVE_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        return res.getJSONObject("content");
    }

    public JSONArray videoMultiCoverListV2(Long videoId) {
        String url = managerApiHost + "/video/multiCover/listV2";
        JSONObject res = null;
        int retry = 0;
        while (retry < 3) {
            try {
                JSONObject param = new JSONObject();
                param.put("videoId", videoId);
                param.put("range", "2h");
                String post = httpPoolClient.post(url, param.toJSONString());
                res = JSONObject.parseObject(post);
                break;
            } catch (Exception e) {
                log.error("ManagerApiService videoMultiCoverListV2 error, videoId={} range={}",
                        videoId, "2h", e);
                retry++;
            }
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_COVER_LIST_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("ManagerApiService videoMultiCoverListV2 error, videoId={} range={} res={}",
                    videoId, "2h", res);
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_COVER_LIST_FAILED.getCode(),
                    ExceptionEnum.VIDEO_MULTI_COVER_LIST_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        return res.getJSONArray("content");
    }

    public JSONArray videoMultiTitleListV2(Long videoId) {
        String url = managerApiHost + "/video/multiTitleV2/listV2";
        JSONObject res = null;
        int retry = 0;
        while (retry < 3) {
            try {
                JSONObject param = new JSONObject();
                param.put("videoId", videoId);
                param.put("range", "4h");
                String post = httpPoolClient.post(url, param.toJSONString());
                res = JSONObject.parseObject(post);
                break;
            } catch (Exception e) {
                log.error("ManagerApiService videoMultiCoverListV2 error, videoId={} range={}",
                        videoId, "4h", e);
                retry++;
            }
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_TITLE_LIST_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("ManagerApiService videoMultiTitleListV2 error, videoId={} range={} res={}",
                    videoId, "4h", res);
            throw new CommonException(ExceptionEnum.VIDEO_MULTI_TITLE_LIST_FAILED.getCode(),
                    ExceptionEnum.VIDEO_MULTI_TITLE_LIST_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        return res.getJSONArray("content");
    }


    /**
     * 按标题搜索视频（调用 manager 平台开放分页接口，无需鉴权）
     *
     * @param title    搜索关键词
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 接口返回的 content 对象，包含 totalSize 和 objs 列表
     */
    public JSONObject searchVideoByTitle(String title, int pageNum, int pageSize) {
        try {
            String encodedTitle = URLEncoder.encode(title, StandardCharsets.UTF_8.name());
            String url = managerApiHost + "/openapi/video/page?pageNum=" + pageNum + "&pageSize=" + pageSize
                    + "&title=" + encodedTitle
                    + "&sortField=4&sortType=desc&status=1&recommendStatus=-6&auditStaus=5&categoryId=55&muid=7";
            String response = httpPoolClient.get(url);
            if (response == null) {
                return null;
            }
            JSONObject res = JSONObject.parseObject(response);
            if (res != null && res.getInteger("code") == 0) {
                return res.getJSONObject("content");
            }
            log.error("ManagerApiService searchVideoByTitle failed, title={} pageNum={} pageSize={} res={}",
                    title, pageNum, pageSize, res);
        } catch (Exception e) {
            log.error("ManagerApiService searchVideoByTitle error, title={} pageNum={} pageSize={}",
                    title, pageNum, pageSize, e);
        }
        return null;
    }

    /**
     * 调用视频向量搜索接口，根据查询文本召回视频并计算综合评分
     *
     * @param queryText 查询文本
     * @param topN      返回数量
     * @return 接口返回的 data 对象（RecallVideoScoreVO）
     */
    public JSONObject recallVideoWithScore(String queryText, int topN) {
        String url = videoVectorApiHost + "/videoSearch/recallWithScore";
        try {
            JSONObject param = new JSONObject();
            param.put("queryText", queryText);
            param.put("configCode", "VIDEO_TITLE");
            param.put("topN", topN);
            param.put("simMin", 0.8);
            String post = httpPoolClient.post(url, param.toJSONString());
            JSONObject res = JSONObject.parseObject(post);
            if (res != null && "0".equals(res.getString("code"))) {
                return res.getJSONObject("data");
            }
            log.error("ManagerApiService recallVideoWithScore failed, queryText={} topN={} res={}",
                    queryText, topN, res);
        } catch (Exception e) {
            log.error("ManagerApiService recallVideoWithScore error, queryText={} topN={}",
                    queryText, topN, e);
        }
        return null;
    }

}
