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


import com.aliyun.imageseg20191230.models.RefineMaskRequest;
import com.aliyun.imageseg20191230.models.RefineMaskResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.heyu.api.data.annotation.CustomPath;
import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.utils.StringUtils;
import com.heyu.api.alibaba.AlibabaBaseHandle;
import com.heyu.api.alibaba.request.imageseg.ARefineMaskRequest;
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/imageseg/2019-12-30/RefineMask?tab=DOC&lang=JAVA
 * <p>
 * <p>
 * Mask精细化分割
 * <p>
 * RefineMask
 */

@Component
@Slf4j
@CustomPath("refineMask")
public class ARefineMaskHandle extends AlibabaBaseHandle<ARefineMaskRequest, RefineMaskResponse> {

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

    @Autowired
    private OssFileUploadService ossFileUploadService;

    @Override
    public String check(ARefineMaskRequest aRefineMaskRequest) {
        if (StringUtils.isBlank(aRefineMaskRequest.getMaskImageURL())
                && StringUtils.isBlank(aRefineMaskRequest.getMaskImageBase64())) {
            return "maskImageURL 和 maskImageBase64不能同时为空";
        }
        if (StringUtils.isBlank(aRefineMaskRequest.getMaskImageURL())
                && StringUtils.isNotBlank(aRefineMaskRequest.getMaskImageBase64())) {
            String url = ossFileUploadService.uploadFileContentByBase64(aRefineMaskRequest.getMaskImageBase64(), ApiConstants.JPG);
            if (StringUtils.isNotBlank(url)) {
                aRefineMaskRequest.setMaskImageURL(url);
            } else {
                return "maskImageBase64 的编码不正确";
            }
        }
        return checkUrlBase64(aRefineMaskRequest);
    }



    @Override
    public RefineMaskResponse run(ARefineMaskRequest aRefineMaskRequest, RuntimeOptions runtime) throws Exception {
        RefineMaskRequest request = new RefineMaskRequest();
        request.setImageURL(aRefineMaskRequest.getImageUrl());
        request.setMaskImageURL(aRefineMaskRequest.getMaskImageURL());
        // 复制代码运行请自行打印 API 的返回值
        return client.refineMaskWithOptions(request, runtime);
    }
}
