package com.docus.server.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.docus.core.util.Func;
import com.docus.core.util.StopWatch;
import com.docus.server.api.ocr.OcrApi;
import com.docus.server.vo.ocr.Datas;
import com.docus.server.vo.ocr.OcrResponse;
import com.docus.server.vo.ocr.Sort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
@Slf4j
public class OcrServiceImpl implements OcrApi {

    @Value("${ocr.api-url:http://192.168.16.85:9999/uploadfile}")
    private String ocrHttpUrl;


    private final static Lock HTTP_POST_LOCK = new ReentrantLock();

    @Override
    public List<String> getText(String path,String ocrHttpUrl) {
        try {

            StopWatch watch = new StopWatch();

            OcrResponse response = ocr(path,ocrHttpUrl);

            log.info("ocr请求截图耗时:{}ms，请求图片地址:{}", watch.elapsedTime(), path);

            List<Datas> datas = response.getDatas();

            List<String> texts = new ArrayList<>();

            if (Func.isNotEmpty(datas)) {
                datas.forEach(p -> {
                    List<List<Sort>> sorts = p.getSort();

                    if (Func.isNotEmpty(sorts)) {
                        sorts.forEach(s -> s.forEach(l -> {
                            String text = l.getText();

                            if (Func.isNotBlank(text)) {
                                texts.add(text);
                            }

                        }));
                    }

                });

            }

            return texts;

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return Collections.emptyList();
        }
    }

    @Override
    public OcrResponse ocr(String path,String ocrHttpUrl) {
        File file = new File(path);
        Map<String, Object> data = new HashMap<>();
        data.put("file", file);
        data.put("filetype", "jpg");
        return uploadFile(data,ocrHttpUrl);
    }

    @Override
    public OcrResponse uploadFile(Map<String, Object> params,String ocrHttpUrl) {

        HTTP_POST_LOCK.lock();
        try {

            String body = HttpRequest.post(ocrHttpUrl)
                .form(params)
                .contentType("multipart/form-data")
                .execute()
                .body();

            if (StrUtil.isNotBlank(body)) {
                return JSON.parseObject(body, OcrResponse.class);
            }

            return new OcrResponse();
        } finally {
            HTTP_POST_LOCK.unlock();
        }
    }

}
