package com.heyu.api.controller.file;


import com.aliyun.ocr20191230.models.RecognizePdfResponse;
import com.aliyun.ocr20191230.models.RecognizePdfResponseBody;
import com.heyu.api.alibaba.handle.common.text.ARecognizePdfHandle;
import com.heyu.api.alibaba.request.common.text.ARecognizePdfRequest;
import com.heyu.api.controller.BaseController;
import com.heyu.api.request.file.RecognizePdfReq;
import com.heyu.api.resp.file.RecognizePdfResp;
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 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/ocr/2019-12-30/RecognizePdf
 *
 *
 * PDF 识别能力可以对 PDF 上的文字进行结构化识别。
 */
@Slf4j
@RestController
@RequestMapping("/pdf")
@NotIntercept
public class RecognizePdfController extends BaseController {


    @Autowired
    private ARecognizePdfHandle recognizePdfHandle;


    @RequestMapping("/recognize")
    @CacheResult
    public R recognize(RecognizePdfReq req) {
        ARecognizePdfRequest aRecognizePdfRequest = new ARecognizePdfRequest();
        aRecognizePdfRequest.setImageUrl(req.getFileURL());
        aRecognizePdfRequest.setImageBase64(req.getFileBase64());
        RecognizePdfResp resp = new RecognizePdfResp();
        List<String> words = new ArrayList<>();
        ApiR<RecognizePdfResponse> aR = recognizePdfHandle.handle(aRecognizePdfRequest);
        if (aR.isSuccess() && isSuccessStatusCode(aR.getData().getStatusCode())) {
            RecognizePdfResponse response = aR.getData();
            RecognizePdfResponseBody responseBody = response.getBody();
            RecognizePdfResponseBody.RecognizePdfResponseBodyData responseBodyData = responseBody.getData();

            List<RecognizePdfResponseBody.RecognizePdfResponseBodyDataWordsInfo> wordsInfo = responseBodyData.getWordsInfo();

            if(CollectionUtils.isNotEmpty(wordsInfo)){
                for (RecognizePdfResponseBody.RecognizePdfResponseBodyDataWordsInfo dataWordsInfo : wordsInfo) {
                    words.add(dataWordsInfo.getWord());
                }
                resp.setWords(words);
            }
        }
        return R.ok().setData(resp);


    }

}
