package com.gxwebsoft.common.core.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.gxwebsoft.common.core.enums.GreenWebType;
import com.gxwebsoft.common.system.vo.faceId.HeadPortraitResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;


@Component
public class GreenWebUtils {
    private static Client contentGreenClient = null;

    static final String accessKeyId = "LTAI5t8UTh8CTXEi2dYxobhj";
    static final String accessKeySecret = "fNdJOT4KAjrVrzHNAcSJuUCy9ZljD9";

    static final String[] badAudioLabel = {"violence", "political_content", "sexual_content", "sexual_sounds", "contraband", "profanity", "religion", "cyberbullying", "negative_content", "specified_speaking", "specified_lyrics"};
//    static final String[] badVideoLabel = {"pornographic_adultContent","pornographic_adultToys","pornographic_artwork","pornographic_adultContent_tii","sexual_suggestiveContent","sexual_breastNudity","sexual_cleavage","sexual_femaleUnderwear","sexual_maleTopless","sexual_femaleShoulder","sexual_cartoon","sexual_pregnancy","sexual_underage","political_politicalFigure_1","political_politicalFigure_2","political_politicalFigure_3","political_politicalFigure_name_tii",""};

    private static class ContentGreenClientHolder {
        private static final Client INSTANCE = createContentGreenClient();
    }

    private static Client createContentGreenClient() {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setRegionId("cn-shenzhen");
        config.setEndpoint("green-cip.cn-shenzhen.aliyuncs.com");
        config.setReadTimeout(6000);
        config.setConnectTimeout(3000);
        try {
            return new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static Client getContentGreenClient() {

        if (contentGreenClient == null) {
            contentGreenClient = ContentGreenClientHolder.INSTANCE;
        }
        return contentGreenClient;
    }

    /**
     * 文本审核
     *
     * @param text
     * @param type
     * @return
     */
    public static boolean testText(String text, GreenWebType type) {
        if (!StringUtils.hasText(text)) {
            return false;
        }

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", text);

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

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        textModerationRequest.setService(type.name());
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());

//        try {
        TextModerationResponse response = null;
        try {
            response = getContentGreenClient().textModerationWithOptions(textModerationRequest, runtime);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (response.statusCode != 200) {
            return false;
        }

        TextModerationResponseBody result = response.getBody();
        Integer code = result.getCode();
        if (code != null && code == 200) {
            TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
            return !StringUtils.hasText(data.getReason());

        } else {
            return false;
        }
    }

    /**
     * 图片审核
     *
     * @param imgUrl
     * @param type
     * @return
     */

    public static boolean testImage(String imgUrl, GreenWebType type) {

        if(!imgUrl.contains("?x-oss-process=image/resize")) {
            imgUrl += "?x-oss-process=image/resize,w_750/quality,Q_90";
        }

        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", imgUrl);
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        ImageModerationRequest request = new ImageModerationRequest();
        // 图片检测service: baselineCheck通用基线检测。
        request.setService(type.name());
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;
        ImageModerationResponse response = null;
        try {
            response = getContentGreenClient().imageModerationWithOptions(request, runtime);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        ImageModerationResponseBody body = response.getBody();

        String[] unSafeLabelArr = {"pornographic_adultContent_tii","pornographic_adultContent","sexual_suggestiveContent",""};
        if (body.getCode() == 200) {
            ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
            System.out.println("dataId=" + data.getDataId());
            List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
            for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {

                if (!"nonLabel".equals(result.getLabel())) {
                    System.out.println(String.format("Label: %s,Confidence: %f",result.getLabel(),result.getConfidence()));
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * 视频审核（异步）
     *
     * @param videoUrl
     * @param type
     * @return
     */
    public static String testVideo(String videoUrl, GreenWebType type) {

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url", videoUrl);

        VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
        // 检测类型：videoDetection
        videoModerationRequest.setService(type.name());
        videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());


        try {
            VideoModerationResponse response = getContentGreenClient().videoModeration(videoModerationRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                    return data.taskId;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 获取视频审核结果
     *
     * @param taskId
     * @param type
     * @return
     */
    public static boolean getTestVideoResult(String taskId, GreenWebType type) {


        JSONObject serviceParameters = new JSONObject();
        // 提交任务时返回的taskId。
        serviceParameters.put("taskId", taskId);
        VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
        videoModerationResultRequest.setService(type.name());
        videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
        try {
            VideoModerationResultResponse response = getContentGreenClient().videoModerationResult(videoModerationResultRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResultResponseBody result = response.getBody();
                System.out.println("requestId=" + result.getRequestId());
                System.out.println("code=" + result.getCode());
                System.out.println("msg=" + result.getMessage());
                if (200 == result.getCode()) {
                    VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
                    VideoModerationResultResponseBody.VideoModerationResultResponseBodyDataAudioResult audioResult = data.getAudioResult();
                    VideoModerationResultResponseBody.VideoModerationResultResponseBodyDataFrameResult frameResult = data.getFrameResult();
                    boolean hasBadAudio = audioResult.sliceDetails.stream().filter(w -> {
                        String labels = w.getLabels();
                        String[] labelArr = labels.split(",");
                        return Arrays.stream(labelArr).filter(l -> {
                            return Arrays.stream(badAudioLabel).filter(b -> b.equals(l)).findFirst().isPresent();
                        }).findFirst().isPresent();
                    }).findFirst().isPresent();
                    if (hasBadAudio) {
                        return false;
                    }
                    boolean hasBadVideo = frameResult.getFrames().stream().filter(w -> {
                        return w.getResults().stream().filter(r -> {
                            return r.getResult().stream().filter(r2 -> {
                                return !"nonLabel".equals(r2.label);
                            }).findFirst().isPresent();
                        }).findFirst().isPresent();
                    }).findFirst().isPresent();
                    if (hasBadVideo) {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     * 鉴别头像是否是真人头像（非卡通）     2. 鉴别图片是否有性感，色情信息     3. 鉴别头像是否有广告，敏感信息，以及二维码等 4. 鉴别头像性别。
     *
     * @param imageBase64
     * @param imageType
     * @param genter
     * @return
     */
    public static boolean testAvatar(String imageBase64, String imageType, Integer genter) {
        String host = "https://edishead.market.alicloudapi.com";
        String path = "/faceId/headPortrait/getResult";
        String method = "POST";
        String appcode = "566b5786c5874464909d8c0b7f64cdc7";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("image", imageBase64);
        bodys.put("imageType", imageType);
        HttpResponse response = null;
        try {
            response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity);
            HeadPortraitResult result = JSONObject.parseObject(string, new TypeReference<HeadPortraitResult>() {
            });
            if (!"0000".equals(result.getCode())) {
                return false;
            }
            if (!"normal".equals(result.getPorn()) || !"normal".equals(result.getAd())) {
                return false;
            }
            if (result.getFaceCount() != 1 || result.getCartoonImg()) {
                return false;
            }

            if (!genter.equals(result.getGenterList()[0])) {
                return false;
            }


        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        System.out.println(response.toString());
        return true;
    }
}
