package com.heyu.api.controller.imagerecog;


import com.aliyun.imagerecog20190930.models.RecognizeFoodResponse;
import com.aliyun.imagerecog20190930.models.RecognizeFoodResponseBody;
import com.heyu.api.alibaba.handle.imagerecog.ARecognizeFoodHandle;
import com.heyu.api.alibaba.request.imagerecog.ARecognizeFoodRequest;
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.EvaluateCertificateQualityReq;
import com.heyu.api.resp.imagerecog.RecognizeFoodResp;
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/RecognizeFood?RegionId=cn-shanghai
 *菜品识别
 *
 * RecognizeFood
 *
 * 功能描述
 * 菜品识别能力可以识别出图片中的菜品类别名称和热量。
 *
 *应用场景
 * 减肥 App：拍摄每天的饮食，计算菜品的热量，可协助您控制好热量摄入。
 * 运动管理 App：通过识别菜品类别，计算累计摄入热量，给出每天的运动计划量。
 * 餐饮、菜场等自动收银结算：通过识别餐饮的类别，可提供自动结算服务。
 */
@Slf4j
@RestController
@RequestMapping("/food")
@NotIntercept
public class RecognizeFoodController extends BaseController {


    @Autowired
    private ARecognizeFoodHandle arRecognizeFoodHandle;


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

        List<RecognizeFoodResp> respList = new ArrayList<>();

        ARecognizeFoodRequest arRecognizeFoodRequest = new ARecognizeFoodRequest();
        arRecognizeFoodRequest.setImageBase64(req.getImageBase64());
        arRecognizeFoodRequest.setImageUrl(req.getImageUrl());


        ApiR<RecognizeFoodResponse> aR = arRecognizeFoodHandle.handle(arRecognizeFoodRequest);
        if (aR.isSuccess() && isSuccessStatusCode(aR.getData().getStatusCode())) {
            RecognizeFoodResponseBody.RecognizeFoodResponseBodyData responseBodyData = aR.getData().getBody().getData();
            if (CollectionUtils.isNotEmpty(responseBodyData.getTopFives())) {
                for (RecognizeFoodResponseBody.RecognizeFoodResponseBodyDataTopFives topFive : responseBodyData.getTopFives()) {
                    RecognizeFoodResp resp = new RecognizeFoodResp();
                    resp.setScore(topFive.getScore());
                    resp.setCategory(topFive.getCategory());
                    resp.setCalorie(topFive.getCalorie());
                    respList.add(resp);
                }
                return R.ok().setData(respList);
            }
        }
        return R.error(aR.getErrorMsg());
    }


}
