package com.tzld.piaoquan.api.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.model.bo.GroupData;
import com.tzld.piaoquan.api.model.bo.VideoDetail;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class TouLiuHttpClient {

    @Autowired
    private HttpPoolClient httpPoolClient;

    public String sendAdFlowAddRequest(String baseUrl,
                                       String videoId,
                                       String putScene,
                                       String channel,
                                       String remark,
                                       String putTypeOne,
                                       String putTypeTwo,
                                       String putTypeThree,
                                       String putCarrierId,
                                       String experimentId) {
        String url = baseUrl + "/ad/put/flow/add/tencent";
        UUID uuid = UUID.randomUUID();
        String experimentIdParam = (experimentId != null && !experimentId.isEmpty()) ? "&experimentId=" + experimentId : "";
        String experimentIdField = (experimentId != null && !experimentId.isEmpty()) ? "\"experimentId\":\"" + experimentId + "\"," : "";
        String jsonBody = "{" +
                "\"videoId\":\"" + videoId + "\"," +
                "\"putScene\":\"" + putScene + "\"," +
                "\"channel\":\"" + channel + "\"," +
                "\"remark\":\"" + remark + "\"," +
                "\"putTypeOne\":\"" + putTypeOne + "\"," +
                "\"putTypeTwo\":\"" + putTypeTwo + "\"," +
                "\"putTypeThree\":\"" + putTypeThree + "\"," +
                "\"putCarrierId\":\"" + putCarrierId + "\"," +
                experimentIdField +
                "\"path\":\"" + "pages/category" + "\"," +
                "\"requestParam\":{" +
                "\"jumpPage\":\"" + "pages/user-videos?fromGzh=1&rootShareId=" + uuid + "&id=" + videoId + "&shareId=" + uuid + "&rootSourceId=[rootSourceId]" + experimentIdParam + "\"" +
                "}" +
                "}";
        try {
            String response = httpPoolClient.post(url, jsonBody);
            // 在返回的url字段后拼接growthExtData参数（URL编码）
            if (experimentId != null && !experimentId.isEmpty() && response != null && !response.isEmpty()) {
                JSONObject responseJson = JSONObject.parseObject(response);
                JSONObject data = responseJson.getJSONObject("data");
                if (data != null && data.getString("url") != null) {
                    String pageUrl = data.getString("url");
                    String growthExtDataJson = "{\"experimentId\":\"" + experimentId + "\"}";
                    pageUrl = pageUrl + "%26growthExtData%3D" + URLEncoder.encode(growthExtDataJson, "UTF-8");
                    data.put("url", pageUrl);
                    responseJson.put("data", data);
                    return responseJson.toJSONString();
                }
            }
            return response;
        } catch (Exception e) {
            log.error("sendAdFlowAddRequest error", e);
        }
        return "";
    }


    public Map<Long, VideoDetail> getVideoDetailRequest(List<Long> videoIds) {
        Map<Long, VideoDetail> map = new HashMap<>();
        try {
            String url = "https://longvideoapi.piaoquantv.com/longvideoapi/openapi/video/batchSelectVideoInfo";
            JSONObject params = new JSONObject();
            params.put("videoIdList", videoIds);
            String post = httpPoolClient.post(url, JSONObject.toJSONString(params));
            JSONObject res = JSONObject.parseObject(post);
            JSONArray data = res.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                Long videoId = jsonObject.getLong("id");
                String shareImgPath = jsonObject.getString("shareImgPath");
                String title = jsonObject.getString("title");
                VideoDetail videoDetail = new VideoDetail();
                videoDetail.setId(videoId);
                videoDetail.setCover(shareImgPath);
                videoDetail.setTitle(title);
                map.put(videoId, videoDetail);
            }
        } catch (Exception e) {
            log.error("getVideoDetailRequest error", e);
        }
        return map;
    }

    public List<GroupData> sendPenGongBaseRequest(String ghId) {
        try {
            String url = "http://47.99.132.47:8813/VideoRank";
            JSONObject params = new JSONObject();
            params.put("ghId", ghId);
            String res = httpPoolClient.post(url, JSONObject.toJSONString(params));
            return JSON.parseArray(res, GroupData.class);
        } catch (Exception e) {
            log.error("getVideoDetailRequest error", e);
        }
        return null;
    }
}
