package com.tzld.piaoquan.api.util;

import cn.hutool.core.net.URLEncodeUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.cdn.model.v20141111.DescribeDomainBpsDataRequest;
import com.aliyuncs.cdn.model.v20141111.DescribeDomainBpsDataResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.stuuudy.commons.external.filestorage.enums.EnumFileType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

public class CdnUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(CdnUtil.class);

//    public static final String VIDEO_CDN_URL_HOST = "https://xycdn.yishihui.com/";
    public static final String VIDEO_CDN_URL_HOST = "http://rescdn.yishihui.com/";

    public static final String PICTURE_CDN_URL_HOST_PICTURE = "http://rescdn.yishihui.com/";
    public static final String DOWNLOAD_CDN_URL_HOST_PICTURE = "https://rescdn.yishihui.com/";


    private static IAcsClient client;

    static {
        if (Objects.isNull(client)) {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAInlg8tWvBeiJe", "hDu5v2nrOmdY0AjlqGnZkW57mxCOLO");
            /** use STS Token
             DefaultProfile profile = DefaultProfile.getProfile(
             "<your-region-id>",           // The region ID
             "<your-access-key-id>",       // The AccessKey ID of the RAM account
             "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
             "<your-sts-token>");          // STS Token
             **/
            client = new DefaultAcsClient(profile);
        }
    }


    public static Double getDescribeDomainBpsData() {
        DescribeDomainBpsDataRequest request = new DescribeDomainBpsDataRequest();
        //需要时区为GMT
        LocalDateTime endTime = LocalDateTime.now().plusHours(-8);
        LocalDateTime startTime = endTime.plusMinutes(-10);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String[] starts = startTime.format(df).split(" ");
        String[] ends = endTime.format(df).split(" ");
        String start = starts[0] + "T" + starts[1] + "Z";
        String end = ends[0] + "T" + ends[1] + "Z";
        request.setStartTime(start);
        request.setEndTime(end);
        LOGGER.info("getDescribeDomainBpsData request = {}", JSON.toJSONString(request));
        try {
            DescribeDomainBpsDataResponse response = client.getAcsResponse(request);
            LOGGER.info("getDescribeDomainBpsData response = {}", JSON.toJSONString(response));
            if (Objects.isNull(response) || Objects.isNull(response.getBpsDataPerInterval())
                    || response.getBpsDataPerInterval().isEmpty() || response.getBpsDataPerInterval().size() <= 1) {
                //只有1条可能不准确
                return null;
            }
            DescribeDomainBpsDataResponse.DataModule module1 = response.getBpsDataPerInterval().get(1);
            if (Objects.nonNull(module1) && Objects.equals("0", module1.getValue())) {
                return null;
            }
            DescribeDomainBpsDataResponse.DataModule module = response.getBpsDataPerInterval().get(0);
            if (Objects.nonNull(module) && Objects.nonNull(module.getValue())) {
                return Double.parseDouble(module.getValue()) / 1000 / 1000 / 1000;
            }
        } catch (ServerException e) {
            LOGGER.error("getDescribeDomainBpsData ServerException", e);
        } catch (ClientException e) {
            LOGGER.error("getDescribeDomainBpsData ClientException", e);
        }
        return null;
    }

    public static String getCdnUrlHost(EnumFileType fileType) {
        if (Objects.isNull(fileType)) {
            return null;
        }
        switch (fileType) {
            case VIDEO:
                return VIDEO_CDN_URL_HOST;
            case PICTURE:
                return PICTURE_CDN_URL_HOST_PICTURE;
        }
        return null;
    }

//    public static void main(String[] args_) throws Exception {
//        DescribeDomainBpsDataRequest request = new DescribeDomainBpsDataRequest();
//        //需要时区为GMT
//        LocalDateTime endTime = LocalDateTime.now().plusHours(-8);
//        LocalDateTime startTime = endTime.plusMinutes(-10);
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String[] starts = startTime.format(df).split(" ");
//        String[] ends = endTime.format(df).split(" ");
//        String start = starts[0] + "T" + starts[1] + "Z";
//        String end = ends[0] + "T" + ends[1] + "Z";
//        request.setStartTime(start);
//        request.setEndTime(end);
//        System.out.println("---" + JSON.toJSONString(request));
//        try {
//            DescribeDomainBpsDataResponse response = client.getAcsResponse(request);
//
//            System.out.println("---" + JSON.toJSONString(response));
//            DescribeDomainBpsDataResponse.DataModule module = response.getBpsDataPerInterval().get(0);
//
//            System.out.println("---" + module.getValue());
//            double d = Double.valueOf(module.getValue()) / 1000 / 1000 / 1000;
//            System.out.println(d);
//
////            System.out.println(new Gson().toJson(response));
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            System.out.println("ErrCode:" + e.getErrCode());
//            System.out.println("ErrMsg:" + e.getErrMsg());
//            System.out.println("RequestId:" + e.getRequestId());
//        }
//
//    }

    public static String getFileExtensionFromUrl(String uri) {
        if (StringUtils.isBlank(uri)) {
            return "";
        }
        String fileExtension = "";
        try {
            if (uri.contains(".")) {
                int lastDotIndex = uri.lastIndexOf('.');
                if (lastDotIndex > 0) {
                    fileExtension = uri.substring(lastDotIndex + 1);
                }
            }
        } catch (Exception e) {
            LOGGER.error("getFileExtensionFromURL error", e);
        }
        return fileExtension;
    }


    public static String getOssHttpUrl(String key) {
        if (StringUtils.isBlank(key)) {
            return key;
        }
        if (StringUtils.startsWithIgnoreCase(key, "http")) {
            return key;
        } else {
            String url = DOWNLOAD_CDN_URL_HOST_PICTURE + key;
            return URLEncodeUtil.encode(url);
        }
    }

    public static void main(String[] args) {
        String url = "ad/material_1564536000000.mp4";
        System.out.println(getFileExtensionFromUrl(url));
    }

}
