package com.heyu.api.controller.face;


import com.aliyun.facebody20191230.models.RecognizeExpressionResponse;
import com.aliyun.facebody20191230.models.RecognizeExpressionResponseBody;
import com.heyu.api.alibaba.handle.facebody.ARecognizeExpressionHandle;
import com.heyu.api.alibaba.request.facebody.ARecognizeExpressionRequest;
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.face.RecognizeExpressionReq;
import com.heyu.api.resp.face.RecognizeExpressionResp;
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/facebody/2019-12-30/RecognizeExpression?RegionId=cn-shanghai&tab=DEMO&lang=JAVA
 *
 * 表情识别
 *
 * RecognizeExpression
 *
 */

@Slf4j
@RestController
@RequestMapping("/face/expression")
@NotIntercept
public class RecognizeExpressionController extends BaseController {


    @Autowired
    private ARecognizeExpressionHandle aRecognizeExpressionHandle;


    @RequestMapping("/recognize")
    @CacheResult
    public R recognize(RecognizeExpressionReq req) {
        List<RecognizeExpressionResp> respList = new ArrayList<>();

        ARecognizeExpressionRequest arecognizeExpressionRequest = new ARecognizeExpressionRequest();
        arecognizeExpressionRequest.setImageBase64(req.getImageBase64());
        arecognizeExpressionRequest.setImageUrl(req.getImageUrl());

        ApiR<RecognizeExpressionResponse> aR = aRecognizeExpressionHandle.handle(arecognizeExpressionRequest);
        if (aR.isSuccess() && isSuccessStatusCode(aR.getData().getStatusCode())) {
            RecognizeExpressionResponseBody.RecognizeExpressionResponseBodyData responseBodyData = aR.getData().getBody().getData();
            List<RecognizeExpressionResponseBody.RecognizeExpressionResponseBodyDataElements> elements = responseBodyData.getElements();
            if (CollectionUtils.isNotEmpty(elements)) {
                for (RecognizeExpressionResponseBody.RecognizeExpressionResponseBodyDataElements element : elements) {
                    RecognizeExpressionResp recognizeExpressionResp = new RecognizeExpressionResp();

                    recognizeExpressionResp.setExpression(element.getExpression());
                    recognizeExpressionResp.setFaceProbability(element.getFaceProbability());

                    respList.add(recognizeExpressionResp);
                }
            }
            return R.ok().setData(respList);
        }
        return R.error();
    }
}
