package com.ytpm.middle.util;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.sls20201230.models.GetLogsResponse;
import com.aliyun.tea.TeaException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Slf4j(topic = "AliOSS")
@Component
@RefreshScope
public class AliOSSUtil {

    private static String endpoint;

    @Value("${oss.aliyun.endpoint}")
    private void setEndpoint(String endpointCon) {
        endpoint = endpointCon;
    }

    private static String accessKeyId;

    @Value("${oss.aliyun.accessKeyId}")
    private void setAccessKeyId(String accessKeyIdCon) {
        accessKeyId = accessKeyIdCon;
    }

    private static String accessKeySecret;

    @Value("${oss.aliyun.accessKeySecret}")
    private void setAccessKeySecret(String accessKeySecretCon) {
        accessKeySecret = accessKeySecretCon;
    }

    private static String bucketName;

    @Value("${oss.aliyun.bucketName}")
    private void setBucketName(String bucketNameCon) {
        bucketName = bucketNameCon;
    }

    /**
     * 上传广告平台文件
     */
    public static String uploadAdvise(InputStream inputStream, String fileName) {
        // 创建 ClientBuilderConfiguration 实例，用于配置 OSS 客户端参数
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 设置签名算法版本为 V4
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        // 设置使用 HTTPS 协议访问 OSS，保证传输安全性
        clientBuilderConfiguration.setProtocol(Protocol.HTTPS);

        Credentials credentials = new DefaultCredentials(accessKeyId,accessKeySecret);
        DefaultCredentialProvider provider = new DefaultCredentialProvider(credentials);
        // 创建 OSS 客户端实例
        clientBuilderConfiguration.setSupportCname(true);// 请注意，设置true开启CNAME选项。
        OSS ossClient = OSSClientBuilder.create()
                .clientConfiguration(clientBuilderConfiguration)
                .endpoint(endpoint)
                .credentialsProvider(provider)
                .clientConfiguration(clientBuilderConfiguration)
                .region("cn-nanjing")
                .build();

        try {
            ossClient.putObject(new PutObjectRequest(bucketName, fileName, inputStream));
        }
        finally {
            ossClient.shutdown();
        }

        return fileName;
    }

    /**
     * 初始化客户端
     */
    public static com.aliyun.sls20201230.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId("LTAI5tJ92xiwYeRdWgdjRG2V")
                .setAccessKeySecret("8EDDgYJOzwnICV7FvPHLuD9l2q3QAS");
        config.endpoint = "cn-nanjing.log.aliyuncs.com";
        return new com.aliyun.sls20201230.Client(config);
    }

    /**
     * 根据传入时间分析查询日志
     */
    public static Map<String, Integer> getCountDownload(int from , int to){
        if(from > to)return new HashMap<>();
        try {
            com.aliyun.sls20201230.Client client = AliOSSUtil.createClient();
            com.aliyun.sls20201230.models.GetLogsRequest getLogsRequest = new com.aliyun.sls20201230.models.GetLogsRequest()
                    .setFrom(from)
                    .setTo(to)
                    .setQuery("* and __topic__: oss_access_log and bucket: yt-advise|SELECT object, count(1) pv from log where object like '%.apk' group by object order by pv Desc");
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            java.util.Map<String, String> headers = new java.util.HashMap<>();
            // 复制代码运行请自行打印 API 的返回值
            GetLogsResponse logsWithOptions = client.getLogsWithOptions("oss-log-1694777633719600-cn-nanjing", "oss-log-store", getLogsRequest, headers, runtime);
            Map<String, Integer> map = new HashMap<>();
            for (Map<String, ?> stringMap : logsWithOptions.getBody()) {
                String key = stringMap.get("object").toString();
                map.put(key.substring(key.lastIndexOf("/")+1).toLowerCase(Locale.ROOT), Integer.parseInt(stringMap.get("pv").toString()));
            }
            return map;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error(error.getMessage());
            // 诊断地址
            log.error(error.getData().get("Recommend").toString());
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            log.error(error.getMessage());
            // 诊断地址
            log.error(error.getData().get("Recommend").toString());
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return new HashMap<>();
    }

    public static void main(String[] args) throws Exception {
//        getCountDownload(Math.toIntExact(DateUtil.getTodayStart().getTime() / 1000), (int) (System.currentTimeMillis()/1000));
        com.aliyun.sls20201230.Client client = AliOSSUtil.createClient();
        com.aliyun.sls20201230.models.GetLogsRequest getLogsRequest = new com.aliyun.sls20201230.models.GetLogsRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        java.util.Map<String, String> headers = new java.util.HashMap<>();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.getLogsWithOptions("", "", getLogsRequest, headers, runtime);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

