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

import com.aliyun.facebody20191230.models.DetectLivingFaceRequest;
import com.aliyun.facebody20191230.models.DetectLivingFaceResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.heyu.api.data.annotation.CustomPath;
import com.heyu.api.data.utils.StringUtils;
import com.heyu.api.alibaba.AlibabaBaseHandle;
import com.heyu.api.alibaba.request.ACommonTextRequest;
import com.heyu.api.alibaba.request.facebody.ADetectLivingFaceRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * https://next.api.aliyun.com/api/facebody/2019-12-30/DetectLivingFace
 * 人脸活体检测
 */
@Component
@Slf4j
@CustomPath("detectLivingFace")
public class ADetectLivingFaceHandle extends AlibabaBaseHandle<ADetectLivingFaceRequest, DetectLivingFaceResponse> {

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

    @Override
    public String check(ADetectLivingFaceRequest aDetectLivingFaceRequest) {
        if (CollectionUtils.isEmpty(aDetectLivingFaceRequest.getTasks())) {
            return "请传入tasks数据";
        }

        if (aDetectLivingFaceRequest.getTasks().size() > 10) {
            return "一次性输入人脸数据不能大于10条";
        }

        for (ACommonTextRequest task : aDetectLivingFaceRequest.getTasks()) {
            if (StringUtils.isBlank(task.getImageUrl()) &&
                    StringUtils.isBlank(task.getImageBase64())) {
                return "url和base64不能同时为空";
            }
        }
        return "";
    }



    @Override
    public DetectLivingFaceResponse run(ADetectLivingFaceRequest aDetectLivingFaceRequest, RuntimeOptions runtime) throws Exception {
        DetectLivingFaceRequest detectLivingFaceRequest = new DetectLivingFaceRequest();
        List<DetectLivingFaceRequest.DetectLivingFaceRequestTasks> tasks = new ArrayList<>();

        for (ACommonTextRequest task : aDetectLivingFaceRequest.getTasks()) {
            DetectLivingFaceRequest.DetectLivingFaceRequestTasks tasks1 = new DetectLivingFaceRequest.DetectLivingFaceRequestTasks();
            tasks1.setImageURL(task.getImageUrl());
            tasks1.setImageData(task.getImageBase64());
            tasks.add(tasks1);
        }
        detectLivingFaceRequest.setTasks(tasks);

        // 复制代码运行请自行打印 API 的返回值
        return client.detectLivingFaceWithOptions(detectLivingFaceRequest, runtime);
    }
}
