package shop.alien.util.common.safe;

import com.alibaba.fastjson.JSON;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
@RefreshScope
public class ImageModerationUtil {

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

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

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

    /**
     * 创建请求客户端
     *
     * @return Client
     * @throws Exception 创建客户端异常
     */
    public Client createClient() throws Exception {
        Config config = new Config();
//        config.setAccessKeyId("LTAI5tReZWshffH78oQJPzZG");
//        config.setAccessKeySecret("Gi30OLYAWunaDbwsv5qqdZ3PzbDyGP");
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        // 设置http代理。
        //config.setHttpProxy("http://10.10.xx.xx:xxxx");
        // 设置https代理。
        //config.setHttpsProxy("https://10.10.xx.xx:xxxx");
        // 接入区域和地址请根据实际情况修改
        // 接入地址列表：https://help.aliyun.com/document_detail/467828.html?#section-uib-qkw-0c8
//        config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
        config.setEndpoint(ImgEndpoint);
        return new Client(config);
    }

    /**
     * 提供给service调用的方法
     *
     * @param imageUrl    图片地址
     * @param serviceEnum Service类型
     * @return 检测结果
     * @throws Exception 检测异常
     */
    public ImageModerationResponse invokeFunction(String imageUrl, String serviceEnum) throws Exception {
        //注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能。
        Client client = createClient();

        // 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtime = new RuntimeOptions();

        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", imageUrl);
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        ImageModerationRequest request = new ImageModerationRequest();
        // 图片检测service：内容安全控制台图片增强版规则配置的serviceCode，示例：baselineCheck
        // 支持service请参考：https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        request.setService(serviceEnum);
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        ImageModerationResponse response = null;
        try {
            response = client.imageModerationWithOptions(request, runtime);
        } catch (Exception e) {
            throw new Exception("调用服务失败" + e.getMessage());
        }
        return response;
    }

    /**
     * 批量图片检测
     *
     * @param imageUrl    图片地址
     * @param serviceEnum Service类型 服务名逗号拼接
     * @return 检测结果
     * @throws Exception 检测异常
     */
    public ImageBatchModerationResponse invokeBeachFunction(String imageUrl, String serviceEnum) throws Exception {
        Client client = createClient();
        RuntimeOptions runtime = new RuntimeOptions();
        Map<String, String> serviceParameters = new HashMap<>();
        serviceParameters.put("imageUrl", imageUrl);
        serviceParameters.put("dataId", UUID.randomUUID().toString());
        ImageBatchModerationRequest imageBatchModerationRequest = new ImageBatchModerationRequest();
        imageBatchModerationRequest.setService(serviceEnum);
        imageBatchModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
        ImageBatchModerationResponse response = null;
        try {
            response = client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
        } catch (Exception e) {
            throw new Exception("调用服务失败" + e.getMessage());
        }
        return response;
    }

    /**
     * 发布商品场景检测
     * 顺序调用内容治理检测、AIGC图片风险检测、图片万物识别
     *
     * @param imageUrl 图片地址
     * @return 检测结果VO
     * @throws Exception 检测异常
     */
    public ImageModerationResultVO productPublishCheck(String imageUrl,List<String> servicesList) throws Exception {
        ImageModerationResultVO resultVO = new ImageModerationResultVO();
        // 批量服务key
        StringBuilder serviceBatchEnum = new StringBuilder();
        StringBuilder serviceEnum = new StringBuilder();
        for (String service : servicesList) {
            if (isSpecialService(service)) {
                serviceBatchEnum.append(service).append(",");
            } else {
                serviceEnum.append(service).append(",");
            }
        }
        // 若存在特殊服务，则拼接字符串  并调取多service阿里图片审核服务
        if (serviceBatchEnum.length() > 0) {
            serviceBatchEnum.setLength(serviceBatchEnum.length() - 1);
            // 多service图片审核
            resultVO = getImageModerationResultVO(imageUrl, serviceBatchEnum);
        }
        // TODO 现阶段使用的服务都支持多service 图片审核，后续如果有不支持的服务则 融合 使用单service图片审核


        return resultVO;
    }

    private ImageModerationResultVO getImageModerationResultVO(String imageUrl, StringBuilder serviceEnum) throws Exception {
        // 多service图片审核
        ImageBatchModerationResponse response = invokeBeachFunction(imageUrl, serviceEnum.toString());
        ImageModerationResultVO resultVO = new ImageModerationResultVO();

        if (response != null && response.getStatusCode() == 200) {
            ImageBatchModerationResponseBody body = response.getBody();
            if (body != null && body.getCode() == 200) {
                ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyData data = body.getData();
                if (data != null) {
                    String riskLevel = data.getRiskLevel();
                    List<ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult> results = data.getResult();
                    StringBuilder labelsBuilder = new StringBuilder();
                    StringBuilder descriptionsBuilder = new StringBuilder();
                    // 处理结果 多个服务总敏感程度
                    if ("high".equals(riskLevel)) {
                        for (ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult result : results) {
                            // 触发多个，如果置信分高于80 则拼接描述
                            if (result.getConfidence() > 80) {
                                String label = result.getLabel();
                                String description = result.getDescription();
                                // 拼接标签
                                if (label != null && !label.isEmpty()) {
                                    labelsBuilder.append(label).append(",");
                                }
                                // 拼接描述
                                if (description != null && !description.isEmpty()) {
                                    descriptionsBuilder.append(description).append(",");
                                }
                            }
                        }
                    }
                    // 移除最后一个逗号
                    if (labelsBuilder.length() > 0) {
                        labelsBuilder.setLength(labelsBuilder.length() - 1);
                    }
                    if (descriptionsBuilder.length() > 0) {
                        descriptionsBuilder.setLength(descriptionsBuilder.length() - 1);
                    }
                    resultVO.setRiskLevel(riskLevel);
                    resultVO.setLabels(labelsBuilder.toString());
                    resultVO.setDescriptions(descriptionsBuilder.toString());
                }
            }
        }
        return resultVO;
    }

    /**
     * 聊一聊场景检测
     * 顺序调用图片万物识别、内容治理检测
     *
     * @param imageUrl 图片地址
     * @return 检测结果
     * @throws Exception 检测异常
     */
    public ImageModerationResultVO chatCheck(String imageUrl) throws Exception {
        // 批量图片检测
        ImageModerationResponse response = invokeFunction(imageUrl, "generalRecognition");
        ImageModerationResultVO resultVO = new ImageModerationResultVO();
        ImageModerationResponseBody body = response.body;
        ImageModerationResponseBody.ImageModerationResponseBodyDataExt dataExt = body.data.ext;
        // 调用DeepSeek接口生成商品文案
        String prompt = "根据以下标签生成一个吸引人的商品售卖文案(200字以内): " + dataExt;
        String generatedText = callDeepSeekAPI(prompt);
        resultVO.setGeneratedText(generatedText);
        return resultVO;
    }

    /**
     * 调用DeepSeek接口生成商品文案
     *
     * @param prompt 提示信息
     * @return 生成的文案
     * @throws IOException 调用异常
     */
    private String callDeepSeekAPI(String prompt) throws IOException {
        DeepseekClient client = new DeepseekClient("sk-dd8a6e10972145c9847883791ac9fb41");
        return client.generateText(prompt);
    }

    /**
     * 判断服务是否为特殊服务，若是可以调取阿里多service审核服务，返回多个场景的总审核结果
     *
     * @param service 服务名称
     * @return 是否为特殊服务
     */
    public static boolean isSpecialService(String service) {
        return ImageReviewServiceEnum.BASELINE_CHECK.getService().equals(service)
                || ImageReviewServiceEnum.BASELINE_CHECK_PRO.getService().equals(service)
                || ImageReviewServiceEnum.TONALITY_IMPROVE.getService().equals(service)
                || ImageReviewServiceEnum.AIGC_CHECK.getService().equals(service)
                || ImageReviewServiceEnum.PROFILE_PHOTO_CHECK.getService().equals(service)
                || ImageReviewServiceEnum.POST_IMAGE_CHECK.getService().equals(service)
                || ImageReviewServiceEnum.ADVERTISING_CHECK.getService().equals(service)
                || ImageReviewServiceEnum.LIVE_STREAM_CHECK.getService().equals(service);
    }
}
