package com.heyu.api.alibaba.handle.facebody;


import com.alibaba.fastjson.JSON;
import com.aliyun.facebody20191230.models.DetectVideoLivingFaceRequest;
import com.aliyun.facebody20191230.models.DetectVideoLivingFaceResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.heyu.api.data.annotation.CustomPath;
import com.heyu.api.data.constants.MimeTypeEnums;
import com.heyu.api.data.utils.SpringContextUtils;
import com.heyu.api.data.utils.StringUtils;
import com.heyu.api.alibaba.AlibabaBaseHandle;
import com.heyu.api.alibaba.request.facebody.ADetectVideoLivingFaceRequest;
import com.heyu.api.oss.OssFileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * https://next.api.aliyun.com/api/facebody/2019-12-30/DetectVideoLivingFace?tab=DOC&lang=JAVA
 *
 *
 * 视频活体检测
 */
@Component
@Slf4j
@CustomPath("videoLivingFace")
public class ADetectVideoLivingFaceHandle extends AlibabaBaseHandle<ADetectVideoLivingFaceRequest, DetectVideoLivingFaceResponse> {


    @Autowired
    private com.aliyun.facebody20191230.Client client;


    @Override
    public String check(ADetectVideoLivingFaceRequest request) {
        boolean flag = MimeTypeEnums.suportVideo(request.getVideoSuffix());
        if (!flag) {
            return "videoSuffix不正确，请上传" + JSON.toJSONString(MimeTypeEnums.videoSuffixList) + "其中一种";
        }


        OssFileUploadService ossFileUploadService = SpringContextUtils.getBean(OssFileUploadService.class);
        if (StringUtils.isBlank(request.getImageUrl()) && StringUtils.isBlank(request.getImageBase64())) {
            log.info("ADetectVideoLivingFaceHandle url and body not null");
            return "url 或 base64 不能同时为空";
        }


        if (StringUtils.isNotBlank(request.getImageBase64())) {
            try {
                String url = ossFileUploadService.uploadFileContentByBase64(request.getImageBase64(), request.getVideoSuffix());
                if (StringUtils.isBlank(url)) {
                    log.error("ADetectVideoLivingFaceHandle oss file upload is null");
                    return "你的base64内容有误";
                }
                request.setImageUrl(url);
            } catch (Exception e) {
                log.error("ADetectVideoLivingFaceHandle oss file upload error", e);
            }
        }
        return null;
    }

    @Override
    public DetectVideoLivingFaceResponse run(ADetectVideoLivingFaceRequest aDetectVideoLivingFaceRequest, RuntimeOptions runtime) throws Exception {
        DetectVideoLivingFaceRequest detectVideoLivingFaceRequest = new DetectVideoLivingFaceRequest();
        detectVideoLivingFaceRequest.setVideoUrl(aDetectVideoLivingFaceRequest.getImageUrl());
        // 复制代码运行请自行打印 API 的返回值
        return client.detectVideoLivingFaceWithOptions(detectVideoLivingFaceRequest, runtime);
    }
}
