package com.ruoyi.ai.service.impl;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.ai.domain.ByteBodyReq;
import com.ruoyi.ai.domain.ByteBodyRes;
import com.ruoyi.ai.service.IByteService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.OkHttpUtils;
import okhttp3.HttpUrl;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ByteService implements IByteService {

//    private final OkHttpClient okHttpClient = OkHttpUtils.createOkHttpClient();

    // Jackson用于JSON序列化/反序列化
    private final ObjectMapper objectMapper = new ObjectMapper()
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

    // API地址（可配置在配置文件中）
    @Value("${byteapi.url}")
    private String API_URL;

    @Value("${byteapi.apiKey}")
    private String apiKey;

    // 火山引擎配置
    @Value("${volcengine.ark.baseUrl:https://ark.cn-beijing.volces.com}")
    private String volcBaseUrl;

    @Value("${volcengine.ark.apiKey}")
    private String volcApiKey;

    @Override
    public ByteBodyRes promptToImg(ByteBodyReq req) throws Exception {
        return this.imgToImg(req);
    }

    @Override
    public ByteBodyRes imgToImg(ByteBodyReq req) throws Exception {

        // 1. 验证请求参数（可选，根据业务需求）
        if (StringUtils.isBlank(req.getPrompt())) {
            throw new Exception("imgToImg error：prompt is null");
        }

        // 2. 构建请求体JSON（基于ByteBodyReq的字段）
        // 注意：ByteBodyReq需包含与API参数对应的字段（model、prompt等）
        String jsonBody = objectMapper.writeValueAsString(req);
        // 3. 构建请求
        Request request = new Request.Builder()
                .url(API_URL + "/images/generations")
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
//                    .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.1.1", 8080)))
                .post(RequestBody.create(
                        MediaType.parse("application/json"),
                        jsonBody
                ))
                .build();
        // 4. 发送同步请求（因方法需要返回值，使用execute而非enqueue）
        Response response = OkHttpUtils.newCall(request).execute();
        // 5. 处理响应
        if (!response.isSuccessful()) {
            // 非200状态：返回错误信息（假设ByteBodyRes有error字段）
            String errorMsg = response.body() != null ? response.body().string() : "imgToImg error";
            throw new Exception("imgToImg error：" + errorMsg);
        }
        // 6. 解析成功响应为ByteBodyRes
        if (response.body() == null) {
            throw new Exception("imgToImg response null");
        }
        String responseBody = response.body().string();
        return objectMapper.readValue(responseBody, ByteBodyRes.class);
    }

    @Override
    public ByteBodyRes imgToVideo(ByteBodyReq req) throws Exception {
        return imgToVideo(req, volcApiKey);
    }

    @Override
    public ByteBodyRes imgToVideo(ByteBodyReq req, String arkApiKey) throws Exception {
        if (req == null) {
            throw new Exception("imgToVideo error：req is null");
        }
        if (StringUtils.isBlank(arkApiKey)) {
            throw new Exception("imgToVideo error：apiKey is null");
        }

        String jsonBody = objectMapper.writeValueAsString(req);

        Request request = new Request.Builder()
                .url(volcBaseUrl + "/api/v3/contents/generations/tasks")
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + arkApiKey)
                .post(RequestBody.create(
                        MediaType.parse("application/json; charset=utf-8"),
                        jsonBody
                ))
                .build();

        Response response = OkHttpUtils.newCall(request).execute();

        if (!response.isSuccessful()) {
            String errorMsg = response.body() != null ? response.body().string() : "imgToVideo error";
            throw new Exception("imgToVideo error：" + errorMsg);
        }

        if (response.body() == null) {
            throw new Exception("imgToVideo response null");
        }

        String responseBody = response.body().string();
        return objectMapper.readValue(responseBody, ByteBodyRes.class);
    }

    @Override
    public ByteBodyRes uploadVideo(String id) throws Exception {
        return uploadVideo(id, volcApiKey);
    }

    @Override
    public ByteBodyRes uploadVideo(String id, String arkApiKey) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new Exception("uploadVideo error：id is null");
        }
        if (StringUtils.isBlank(arkApiKey)) {
            throw new Exception("uploadVideo error：apiKey is null");
        }

        Request request = new Request.Builder()
                .url(volcBaseUrl + "/api/v3/contents/generations/tasks/" + id)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + arkApiKey)
                .get()
                .build();

        Response response = OkHttpUtils.newCall(request).execute();

        if (!response.isSuccessful()) {
            String errorMsg = response.body() != null ? response.body().string() : "uploadVideo error";
            throw new Exception("uploadVideo error：" + errorMsg);
        }

        if (response.body() == null) {
            throw new Exception("uploadVideo response null");
        }

        String responseBody = response.body().string();
        return objectMapper.readValue(responseBody, ByteBodyRes.class);
    }

    @Override
    public AjaxResult cancelVideoTask(String id) throws Exception {
        return cancelVideoTask(id, volcApiKey);
    }

    @Override
    public AjaxResult cancelVideoTask(String id, String arkApiKey) throws Exception {
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error("任务ID不能为空");
        }
        if (StringUtils.isBlank(arkApiKey)) {
            return AjaxResult.error("API Key 无效");
        }

        try {
            Request request = new Request.Builder()
                    .url(volcBaseUrl + "/api/v3/contents/generations/tasks/" + id)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + arkApiKey)
                    .delete()
                    .build();

            Response response = OkHttpUtils.newCall(request).execute();

            if (!response.isSuccessful()) {
                String errorMsg = response.body() != null ? response.body().string() : "cancel failed";
                return AjaxResult.error("取消任务失败：" + errorMsg);
            }

            return AjaxResult.success("任务已取消，余额已退回");
        } catch (Exception e) {
            return AjaxResult.error("取消任务异常：" + e.getMessage());
        }
    }

    @Override
    public String listVideoGenerationTasks(int pageNum, int pageSize, String arkApiKey) throws Exception {
        if (StringUtils.isBlank(arkApiKey)) {
            throw new Exception("listVideoGenerationTasks error：apiKey is null");
        }
        int pn = pageNum > 0 ? pageNum : 1;
        int ps = pageSize > 0 ? Math.min(pageSize, 500) : 10;

        HttpUrl parsed = HttpUrl.parse(volcBaseUrl + "/api/v3/contents/generations/tasks");
        if (parsed == null) {
            throw new Exception("listVideoGenerationTasks error：invalid base url");
        }
        HttpUrl url = parsed.newBuilder()
                .addQueryParameter("page_num", String.valueOf(pn))
                .addQueryParameter("page_size", String.valueOf(ps))
                .build();

        Request request = new Request.Builder()
                .url(url)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + arkApiKey)
                .get()
                .build();

        Response response = OkHttpUtils.newCall(request).execute();
        if (response.body() == null) {
            throw new Exception("listVideoGenerationTasks response null");
        }
        String body = response.body().string();
        if (!response.isSuccessful()) {
            throw new Exception("listVideoGenerationTasks error：" + body);
        }
        return body;
    }
}
