package com.hzy.common.utils;

import com.aliyun.auth.credentials.provider.DefaultCredentialProvider;
import com.aliyun.sdk.service.ocr_api20210707.AsyncClient;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeInvoiceRequest;
import com.aliyun.sdk.service.ocr_api20210707.models.RecognizeInvoiceResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AliUtils {

    public static RecognizeInvoiceResponse RecognizeInvoice(RecognizeInvoiceRequest recognizeInvoiceRequest) throws ExecutionException, InterruptedException {

        // Configure Credentials authentication information
        DefaultCredentialProvider provider = DefaultCredentialProvider.builder().build();

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.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
                                .setEndpointOverride("ocr-api.cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
//        RecognizeInvoiceRequest recognizeInvoiceRequest = RecognizeInvoiceRequest.builder()
//                // Request-level configuration rewrite, can set Http request parameters, etc.
//                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
//                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<RecognizeInvoiceResponse> response = client.recognizeInvoice(recognizeInvoiceRequest);
        // Synchronously get the return value of the API request
        RecognizeInvoiceResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();

        return resp;
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
    }
}
