package com.malk.kabeiyi.util;

import cn.hutool.json.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.ocr_api20210707.models.*;
import com.aliyun.sdk.service.ocr_api20210707.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;
import org.springframework.beans.factory.annotation.Value;

//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.io.*;
import java.util.stream.Collectors;

public class RecognizeAllText {
    /*@Value("${aliyun.accessKeyId}")
    private static String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private static String accessKeySecret;*/

    public static String recognizeText(String filePath,String type,String accessKeyId,String accessKeySecret) throws Exception {
        if (!type.equals("Advanced") && !type.equals("Table")){
            return null;
        }
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
//                .securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .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
        InputStream bodyStream = Files.newInputStream(new File(filePath).toPath());
        RecognizeAllTextRequest recognizeAllTextRequest = RecognizeAllTextRequest.builder()
                .type(type)
                .body(bodyStream)
                // 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<RecognizeAllTextResponse> response = client.recognizeAllText(recognizeAllTextRequest);
        // Synchronously get the return value of the API request
        RecognizeAllTextResponse resp = response.get();
        String jsonString = new Gson().toJson(resp);
        JSONObject jsonObject = new JSONObject(jsonString);

        Map<String, Object> map = jsonObject.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue
                ));
        Map body = (Map) map.get("body");
        Map data = (Map) body.get("data");
        String content = String.valueOf(data.get("content"));
        System.out.println(content);
        /*if (!type.equals("MixedInvoice")){

        }else {
            List<Map> subImages = (List<Map>) data.get("subImages");
            for (Map subImage : subImages) {
                String type2 = subImage.get("type").toString();
                Map kvInfo = (Map) subImage.get("kvInfo");
                Map<String, String> data2 = (Map) kvInfo.get("data");
                content += type2 + ":\n";
                List<String> valueList = new ArrayList<>();
                for (String key : data2.keySet()) {
                     valueList.add(data2.get(key));
                }
                content += String.join(",", valueList) + "\n";
            }
        }*/



        // 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
        client.close();
        return content;
    }

}

