package com.heyu.api.controller.imagerecog;


import com.aliyun.imagerecog20190930.models.DetectImageElementsResponse;
import com.aliyun.imagerecog20190930.models.DetectImageElementsResponseBody;
import com.heyu.api.alibaba.handle.imagerecog.ADetectImageElementsHandle;
import com.heyu.api.alibaba.request.imagerecog.ADetectImageElementsRequest;
import com.heyu.api.controller.BaseController;
import com.heyu.api.data.annotation.CacheResult;
import com.heyu.api.data.annotation.NotIntercept;
import com.heyu.api.data.utils.ApiR;
import com.heyu.api.data.utils.R;
import com.heyu.api.request.imagerecog.DetectImageElementsReq;
import com.heyu.api.resp.imagerecog.DetectImageElementsResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/***
 * https://next.api.aliyun.com/api/imagerecog/2019-09-30/DetectImageElements?tab=DEMO&lang=JAVA&RegionId=cn-shanghai
 *元素识别
 *
 * DetectlmageElements
 *
 *
 * 功能描述
 * 元素识别能力用于识别输入图像中所包含的元素内容，用矩形框标注出其位置，并区分其对应的基本类型（人物、修饰、文案）。
 *
 *
 */
@Slf4j
@RestController
@RequestMapping("/image")
@NotIntercept
public class DetectImageElementsController extends BaseController {


    @Autowired
    private ADetectImageElementsHandle aDetectImageElementsHandle;


    @RequestMapping("/detect")
    @CacheResult
    public R classifying(DetectImageElementsReq req) {
        List<DetectImageElementsResp> respList = new ArrayList<>();


        ADetectImageElementsRequest request = new ADetectImageElementsRequest();
        request.setImageBase64(req.getImageBase64());
        request.setImageUrl(req.getImageUrl());


        ApiR<DetectImageElementsResponse> aR = aDetectImageElementsHandle.handle(request);
        if (aR.isSuccess() && isSuccessStatusCode(aR.getData().getStatusCode())) {

            DetectImageElementsResponseBody.DetectImageElementsResponseBodyData responseBodyData = aR.getData().getBody().getData();

            if (CollectionUtils.isNotEmpty(responseBodyData.getElements())) {
                for (DetectImageElementsResponseBody.DetectImageElementsResponseBodyDataElements element : responseBodyData.getElements()) {
                    DetectImageElementsResp resp = new DetectImageElementsResp();
                    resp.setY(element.getY());
                    resp.setX(element.getX());
                    resp.setWidth(element.getWidth());
                    resp.setHeight(element.getHeight());
                    respList.add(resp);
                }
            }
            return R.ok().setData(respList);
        }

        return R.error(aR.getErrorMsg());
    }


}




