package com.heyu.api.controller.imagerecog;


import com.aliyun.imagerecog20190930.models.RecognizeImageColorResponse;
import com.aliyun.imagerecog20190930.models.RecognizeImageColorResponseBody;
import com.heyu.api.alibaba.handle.imagerecog.ARecognizeImageColorHandle;
import com.heyu.api.alibaba.request.imagerecog.ARecognizeImageColorRequest;
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.RecognizeImageColorReq;
import com.heyu.api.resp.imagerecog.RecognizeImageColorResp;
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/RecognizeImageColor?tab=DOC
 * 颜色识别
 *
 *
 * RecognizelmageColor
 *
 * 功能描述
 * 颜色识别能力可以对输入图片的颜色信息进行分析，输出颜色值（RGB 形式和 HEX 格式）与对应的占比信息。
 *
 */
@Slf4j
@RestController
@RequestMapping("/image/color")
@NotIntercept
public class RecognizeImageColorController extends BaseController {


    @Autowired
    private ARecognizeImageColorHandle arRecognizeImageColorHandle;


    @RequestMapping("/recognize")
    @CacheResult
    public R recognize(RecognizeImageColorReq req) {

        List<RecognizeImageColorResp> respList = new ArrayList<>();
        ARecognizeImageColorRequest request = new ARecognizeImageColorRequest();

        request.setImageUrl(req.getImageUrl());
        request.setColorCount(req.getColorCount());
        request.setImageBase64(req.getImageBase64());


        ApiR<RecognizeImageColorResponse> aR = arRecognizeImageColorHandle.handle(request);
        if (aR.isSuccess() && isSuccessStatusCode(aR.getData().getStatusCode())) {
            RecognizeImageColorResponseBody.RecognizeImageColorResponseBodyData responseBodyData = aR.getData().getBody().getData();
            if (CollectionUtils.isNotEmpty(responseBodyData.getColorTemplateList())) {
                for (RecognizeImageColorResponseBody.RecognizeImageColorResponseBodyDataColorTemplateList templateList : responseBodyData.getColorTemplateList()) {

                    RecognizeImageColorResp resp = new RecognizeImageColorResp();
                    resp.setColor(templateList.getColor());
                    resp.setPercentage(templateList.getPercentage());
                    resp.setLabel(templateList.getLabel());
                    respList.add(resp);
                }
            }

            return R.ok().setData(respList);

        }

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


    }
}
