package com.zcloud.common.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.vod20170321.AsyncClient;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod20170321.Client;
import com.aliyun.vod20170321.models.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.aliyun.sdk.service.vod20170321.models.DescribeVodDomainUsageDataResponseBody.DataModule;
import com.aliyun.sdk.service.vod20170321.models.DescribeVodDomainUsageDataResponse;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author fangjiakai
 * @date 2023/12/13 14:26
 */
@ConfigurationProperties(prefix = "aliplay")
@Component
@Data
public class AliVideoUtil {
    private String accessKeyId;
    private String accessKeySecret;
    private String templateGroupId;
    private String sdTemplateGroupId;
    private String ldTemplateGroupId;
    private String regionId;
    private String endpoint;
    private String shangHaiRegionId;
    private String shangHaiEndpoint;

    public DefaultAcsClient initVodClient() throws ClientException {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }
    public Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(this.accessKeyId)
                .setAccessKeySecret(this.accessKeySecret);
        // 访问的域名
        config.endpoint = this.endpoint;
        return new com.aliyun.vod20170321.Client(config);
    }
    public AsyncClient createTrafficClient() throws Exception {

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(this.accessKeyId)
                .accessKeySecret(this.accessKeySecret)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region(this.shangHaiRegionId) // 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/vod
                                .setEndpointOverride(this.shangHaiEndpoint)
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        return client;
    }

    //流方式上传视频
    public Map<String, String> uploadVideo(String title, String fileName, InputStream inputStream) throws Exception {
        Map<String, String> result = new HashMap<>();
        UploadStreamRequest request = new UploadStreamRequest(this.accessKeyId, this.accessKeySecret, title, fileName, new BufferedInputStream(inputStream));
        request.setShowWaterMark(true);
        request.setTemplateGroupId(this.templateGroupId);
        request.setApiRegionId(this.regionId);
        /* 设置自定义上传进度回调（必须继承 VoDProgressListener）*/
        /*默认关闭。如果开启了这个功能，上传过程中服务端会在日志中返回上传详情。如果不需要接收此消息，需关闭此功能*/
        request.setProgressListener(new PutObjectProgressListener());
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        result.put("RequestId", response.getRequestId());
        if (response.isSuccess()) {
            result.put("VideoId", response.getVideoId());
        } else {
            throw new RuntimeException("ErrorCode=[" + response.getCode() + "],ErrorMessage=[" + response.getMessage() + "]");
        }
        return result;
    }



    /**
     * 视频上传（不转码）
     * @param title
     * @param fileName
     * @param inputStream
     * @return
     * @throws Exception
     */
    public Map<String, String> uploadVideoNoGroup(String title, String fileName, InputStream inputStream) throws Exception {
        Map<String, String> result = new HashMap<>();
        UploadStreamRequest request = new UploadStreamRequest(this.accessKeyId, this.accessKeySecret, title, fileName, new BufferedInputStream(inputStream));
        request.setShowWaterMark(false);
        request.setApiRegionId(this.regionId);
        /* 设置自定义上传进度回调（必须继承 VoDProgressListener）*/
        /*默认关闭。如果开启了这个功能，上传过程中服务端会在日志中返回上传详情。如果不需要接收此消息，需关闭此功能*/
        request.setProgressListener(new PutObjectProgressListener());
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        result.put("RequestId", response.getRequestId());
        if (response.isSuccess()) {
            result.put("VideoId", response.getVideoId());
        } else {
            throw new RuntimeException("ErrorCode=[" + response.getCode() + "],ErrorMessage=[" + response.getMessage() + "]");
        }
        return result;
    }


    //获取上传地址
//    public CreateUploadVideoResponse createUploadVideo(VideoCreateForm form) throws Exception {
//        Client client = createClient();
//        CreateUploadVideoRequest createUploadVideoRequest = new CreateUploadVideoRequest()
//                .setFileName(form.getFileName())
//                .setTitle(form.getTitle())
//                .setTemplateGroupId(templateGroupId);
//        // 复制代码运行请自行打印 API 的返回值
//        CreateUploadVideoResponse  resp=  client.createUploadVideo(createUploadVideoRequest);
//        return resp;
//    }


    //获取播放地址
    public GetPlayInfoResponse getPlayInfo(String videoId) throws Exception {
        Client client = createClient();
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        request.setResultType("Multiple");
        RuntimeOptions runtime = new RuntimeOptions();
        return client.getPlayInfoWithOptions(request,runtime);
    }



    // 查询转码配置的详细信息
    public void GetTranscodeTemplateGroup(String groupId) throws Exception {
        Client client = createClient();
        GetTranscodeTemplateGroupRequest getTranscodeTemplateGroupRequest = new GetTranscodeTemplateGroupRequest()
                .setTranscodeTemplateGroupId(groupId);
        RuntimeOptions runtime = new RuntimeOptions();
            // 复制代码运行请自行打印 API 的返回值
        client.getTranscodeTemplateGroupWithOptions(getTranscodeTemplateGroupRequest, runtime);
    }

    /**
     * 提交转码任务
     * @param params
     * @throws Exception
     */
    public void submitTranscodeJobs(Map<String, String> params) throws Exception {
        Client client = createClient();
        SubmitTranscodeJobsRequest submitTranscodeJobsRequest = new SubmitTranscodeJobsRequest()
                .setVideoId(params.get("videoId"))
                .setTemplateGroupId(params.get("templateGroupId"));
        RuntimeOptions runtime = new RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        client.submitTranscodeJobsWithOptions(submitTranscodeJobsRequest, runtime);
    }

    /**
     * 查询转码任务列表
     * @param videoId
     * @return
     * @throws Exception
     */
    public ListTranscodeTaskResponse ListTranscodeTask(String videoId) throws Exception {
        Client client = createClient();
        ListTranscodeTaskRequest listTranscodeTaskRequest = new ListTranscodeTaskRequest()
                .setVideoId(videoId);
        RuntimeOptions runtime = new RuntimeOptions();
        return client.listTranscodeTaskWithOptions(listTranscodeTaskRequest, runtime);
    }

    public void GetMezzanineInfo(String videoId) throws Exception {
        Client client = createClient();
        GetMezzanineInfoRequest getMezzanineInfoRequest = new GetMezzanineInfoRequest()
                .setVideoId(videoId);
        RuntimeOptions runtime = new RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        client.getMezzanineInfoWithOptions(getMezzanineInfoRequest, runtime);
    }





    public  List<DataModule> getYesterdayFlow(String domainName, String startDate, String endDate) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("startTime", startDate + " 00:00:00");
        params.put("endTime", endDate + " 23:59:59");
        params.put("interval", "86400");
        params.put("domainName", domainName);
        DescribeVodDomainUsageDataResponse response = DescribeVodDomainUsageData(params);
        return response.getBody().getUsageDataPerInterval().getDataModule();
    }
    public DescribeVodDomainUsageDataResponse DescribeVodDomainUsageData(Map<String, String> params) throws Exception {
        AsyncClient client = createTrafficClient();
        try {
            com.aliyun.sdk.service.vod20170321.models.DescribeVodDomainUsageDataRequest describeVodDomainUsageDataRequest = com.aliyun.sdk.service.vod20170321.models.DescribeVodDomainUsageDataRequest.builder()
                    .domainName(params.get("domainName").toString())   //  域名
                    .area("CN")
                    .type("all")
                    .field("traf")  //数据类型 traf：流量
                    .startTime(DateUtil.parseCSTToUTC(params.get("startTime").toString()))    //  获取数据起始时间点。格式为：yyyy-MM-ddTHH:mm:ssZ（UTC时间）。
                    .endTime(DateUtil.parseCSTToUTC(params.get("endTime").toString())) //  获取数据结束时间点，需晚于起始时间。格式为：yyyy-MM-ddTHH:mm:ssZ（UTC时间）。
                    .interval(params.get("interval").toString())   //  	强制指定获取指定时间粒度的数据，单位为秒。支持300（5分钟）、3600（1小时）和86400（1天）。

                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.crea0te().setHttpHeaders(new HttpHeaders()))
                    .build();
            if(params.get("domainName") != null){
                describeVodDomainUsageDataRequest.toBuilder().domainName(params.get("domainName").toString());
            }
            // Request-level configuration rewrite, can set Http request parameters, etc.
            // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))

            // Asynchronously get the return value of the API request
            CompletableFuture<DescribeVodDomainUsageDataResponse> response = client.describeVodDomainUsageData(describeVodDomainUsageDataRequest);
            // Synchronously get the return value of the API request

            DescribeVodDomainUsageDataResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            return resp;
        } finally {
            client.close();
        }

    }

}
