package com.heyu.api.controller.imageseg;

import com.aliyun.imageseg20191230.models.SegmentHeadResponse;
import com.aliyun.imageseg20191230.models.SegmentHeadResponseBody;
import com.heyu.api.alibaba.handle.imageseg.ASegmentHeadHandle;
import com.heyu.api.alibaba.request.imageseg.ASegmentHeadRequest;
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.SegmentHeadReq;
import com.heyu.api.resp.imageseg.SegmentHeadResp;
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;

@Slf4j
@RestController
@RequestMapping("/head")
@NotIntercept
public class SegmentHeadController extends BaseController {


    @Autowired
    private ASegmentHeadHandle segmentHeadHandle;


    @RequestMapping("/segment")
    @CacheResult
    public R segment(SegmentHeadReq request) {
        List<SegmentHeadResp> respList = new ArrayList<>();
        ASegmentHeadRequest aSegmentHeadRequest = new ASegmentHeadRequest();


        aSegmentHeadRequest.setReturnType(request.getReturnType());
        aSegmentHeadRequest.setImageBase64(request.getImageBase64());
        aSegmentHeadRequest.setImageUrl(request.getImageUrl());


        ApiR<SegmentHeadResponse> aR = segmentHeadHandle.handle(aSegmentHeadRequest);
        if (aR.isSuccess() && isSuccessStatusCode(aR.getData().getStatusCode())) {
            SegmentHeadResponseBody.SegmentHeadResponseBodyData responseBodyData = aR.getData().getBody().getData();
            if (CollectionUtils.isNotEmpty(responseBodyData.getElements())) {
                for (SegmentHeadResponseBody.SegmentHeadResponseBodyDataElements element : responseBodyData.getElements()) {
                    SegmentHeadResp segmentHeadResp = new SegmentHeadResp();
                    segmentHeadResp.setImageURL(element.getImageURL());
                    segmentHeadResp.setY(element.getY());
                    segmentHeadResp.setX(element.getX());
                    segmentHeadResp.setWidth(element.getWidth());
                    segmentHeadResp.setHeight(element.getHeight());
                    respList.add(segmentHeadResp);
                }
                return R.ok().setData(respList);
            }


        }

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


    }
}
