package shop.alien.util.common.safe.video;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class VideoModerationUtil {

    @Value("${ali.yundun.accessKeyID}")
    private String accessKeyId;

    @Value("${ali.yundun.secret}")
    private String accessKeySecret;

    @Value("${ali.yundun.videoEndpoint}")
    private String imgEndpoint;

    @Value("${ali.yundun.videoRegionId:cn-shanghai}")
    private String regionId;

    private Client client;

    @PostConstruct
    public void init() throws Exception {
        this.client = createClient();
    }

    /**
     * 创建请求客户端
     *
     * @return Client
     * @throws Exception 创建客户端异常
     */
    public Client createClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setEndpoint(imgEndpoint);
        //接入区域和地址请根据实际情况修改。
        config.setRegionId(regionId);
        //连接时超时时间，单位毫秒（ms）。
        config.setReadTimeout(6000);
        //读取时超时时间，单位毫秒（ms）。
        config.setConnectTimeout(3000);
        return new Client(config);
    }

    /**
     * 提交视频检测任务
     *
     * @param url  视频URL
     * @param dataId 数据ID
     * @return VideoModerationResponse
     * @throws Exception 调用异常
     */
    public VideoModerationResponse submitVideoModerationTask(String url, String dataId) throws Exception {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url", url);
        if (dataId != null) {
            serviceParameters.put("dataId", dataId);
        }

        VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
        // 检测类型：videoDetectionByVL
        videoModerationRequest.setService("videoDetectionByVL");
        videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResponse response = client.videoModeration(videoModerationRequest);
            log.info("提交视频审核任务结果: {}", JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("提交视频审核任务失败", e);
            throw new Exception("提交视频审核任务失败: " + e.getMessage());
        }
    }

    /**
     * 获取视频检测结果
     *
     * @param taskId 任务ID
     * @return VideoModerationResultResponse
     * @throws Exception 调用异常
     */
    public VideoModerationResultResponse getVideoModerationResult(String taskId) throws Exception {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("taskId", taskId);

        VideoModerationResultRequest request = new VideoModerationResultRequest();
        request.setService("videoDetection");
        request.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResultResponse response = client.videoModerationResult(request);
            log.info("获取视频审核结果: {}", JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("获取视频审核结果失败", e);
            throw new Exception("获取视频审核结果失败: " + e.getMessage());
        }
    }

    /**
     * 取消视频检测任务
     *
     * @param taskId 任务ID
     * @return VideoModerationCancelResponse
     * @throws Exception 调用异常
     */
    public VideoModerationCancelResponse cancelVideoModerationTask(String taskId) throws Exception {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("taskId", taskId);

        VideoModerationCancelRequest request = new VideoModerationCancelRequest();
        request.setService("liveStreamDetection");
        request.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationCancelResponse response = client.videoModerationCancel(request);
            log.info("取消视频审核任务结果: {}", JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("取消视频审核任务失败", e);
            throw new Exception("取消视频审核任务失败: " + e.getMessage());
        }
    }
}