package com.gree.mall.manager.utils.ocr;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ocr_api20210707.AsyncClient;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeHandwritingRequest;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeHandwritingResponse;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeHandwritingResponseBody;
import com.gree.mall.manager.exception.RemoteServiceException;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class OCRUtil {

    @Value("${ali.access.key.id}")
    private String ACCESS_KEY_ID;
    @Value("${ali.access.key.secert}")
    private String ACCESS_KEY_SECERT;

    public AsyncClient buildClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(ACCESS_KEY_SECERT)
                .build());
        return AsyncClient.builder()
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
                                // 服务地址 ocr-api.cn-hangzhou.aliyuncs.com
                                // VPC地址 ocr-api-vpc.cn-hangzhou.aliyuncs.com
                                .setEndpointOverride("ocr-api-vpc.cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
    }

    public String handwritingORC(ByteArrayInputStream byteArrayInputStream) {
        AsyncClient client = buildClient();
        // Parameter settings for API request
        RecognizeHandwritingRequest recognizeHandwritingRequest = RecognizeHandwritingRequest.builder()
                .body(byteArrayInputStream)
                .needRotate(false)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        CompletableFuture<RecognizeHandwritingResponse> response = client.recognizeHandwriting(recognizeHandwritingRequest);
        String content = "";
        try {
            final RecognizeHandwritingResponse resp = response.get();
            final RecognizeHandwritingResponseBody body = resp.getBody();
            final JSONObject data = JSONUtil.parseObj(body.getData());
            content = StrUtil.replace(data.get("content", String.class), " ", "");
        } catch (Exception e) {
            throw new RemoteServiceException("OCR服务异常");
        } finally {
            client.close();
        }

        return content;
    }
}
