package com.afanticar.aliyun.fc;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.afanticar.aliyun.fc.dto.request.AwemeSimpleRequest;
import com.afanticar.aliyun.fc.dto.response.AwemeCallbackContent;
import com.afanticar.aliyun.fc.util.FFmpegUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.Credentials;
import com.aliyun.fc.runtime.PojoRequestHandler;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @Author: wuzhancai
 * @Desc: 下载视频-上传oss
 * @Date: 2023/6/2 13:51
 */
public class AwemeAudioDownloadOss implements PojoRequestHandler<AwemeSimpleRequest, AwemeCallbackContent> {


    private static final Logger log = LoggerFactory.getLogger(AwemeAudioDownloadOss.class);

    @Override
    public AwemeCallbackContent handleRequest(AwemeSimpleRequest request, Context context) {

        AwemeCallbackContent message = getAudio(request,context);
        return message;
    }

    public static void main(String[] args) {
        AwemeSimpleRequest request = new AwemeSimpleRequest();
        request.setAwemeId("3454335345");
        request.setAwemeUrl("https://api-hl.amemv.com/aweme/v1/play/?video_id=v0d00fg10000chqub8bc77u0q4inptmg&line=1&file_id=ef3e15d11fae40db94f49c8fb3be11d7&sign=8ae7630595ecd49fb598e5bbae9b19a4&is_play_url=1&source=PackSourceEnum_PUBLISH");
//        request.setContentCenterUrl("https://api-dev.afanticar.com/content-center/v1/kaize/publish/task");
        request.setContentCenterUrl("http://localhost:18902/v1/aweme/recognize");
        Date beginDate = new Date();
        log.info("begin time {}",beginDate);
        AwemeCallbackContent audio = getAudio(request,null);
        Date endDate = new Date();
        log.info("end time {} user {} ",endDate,(endDate.getTime()-beginDate.getTime()));
        System.out.println(audio);
    }

    private static AwemeCallbackContent getAudio(AwemeSimpleRequest request,Context context) {
//        String url = "https://api.amemv.com/aweme/v1/play/?video_id=v0200fg10000cgbkfqjc77u3udkfff30&line=1&file_id=db82e40c28ad49fb860a247ace95f8b8&sign=44b50f681b684101c3f33ce7c25ffd02&is_play_url=1&source=PackSourceEnum_PUBLISH";

        String url = request.getAwemeUrl();
        String awemeId = request.getAwemeId();
        awemeId=UUID.randomUUID().toString();
        String folderPath = "/code/temp/aweme";
        String fileName = awemeId+".mp4";
        String localWavPath = "/code/temp/"+ fileName;
        String ossAudioFolderPath = "recognize/audio/";
        String ossAwemeFolderPath = "recognize/aweme/";
        String ossFrameFolderPath = "recognize/frame/"+awemeId+"/";
        String localFrameFolderPath = "/code/temp/aweme/"+awemeId;


        File folder = new File(localFrameFolderPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        // Bucket名称, 需要预先创建。
        String bucketName = "cont-aweme-dev";
        // Endpoint必须填写Bucket所在地域对应的Endpoint，推荐使用内网访问地址。以华东1（杭州）为例，内网访问Endpoint为https://oss-cn-hangzhou-internal.aliyuncs.com。
        String endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";

        // 获取密钥信息，执行前，确保函数所在的服务配置了角色信息，并且角色需要拥有AliyunOSSFullAccess权限。
        // 建议直接使用AliyunFCDefaultRole角色。
        String os = System.getProperty("os.name");
        if(os.toLowerCase().indexOf("win")!=-1){
            endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        }
//        log.info("context {}", context);
        /*Credentials creds = null;
        if(context != null){
            creds = context.getExecutionCredentials();
            log.info("creds.getAccessKeyId{},creds.getAccessKeySecret{},creds.getSecurityToken{}",creds.getAccessKeyId(),creds.getAccessKeySecret(),creds.getSecurityToken());
        }*/


        //下载视频
        Date beginDate = new Date();
        log.info("date begin time {}",beginDate);
        HttpUtil.downloadFile(getTransferUrl(url),localWavPath);
        Date endDate = new Date();
        log.info("date end time {}",endDate);
        log.info("sheng yu {}",endDate.getTime()-beginDate.getTime());

        OSS ossClient =null;
        if(context != null){
//            ossClient = new OSSClientBuilder().build(endpoint, creds.getAccessKeyId(), creds.getAccessKeySecret(),creds.getSecurityToken());
            ossClient = new OSSClientBuilder().build(endpoint, "LTAI5tGcLYurZDbTExbdFAZL", "Ji3DsPdK6u2cHup7IdxolR1CpCqaPY");
        }else{
            ossClient = new OSSClientBuilder().build(endpoint, "LTAI5tGcLYurZDbTExbdFAZL", "Ji3DsPdK6u2cHup7IdxolR1CpCqaPY");
        }

        // 填写Byte数组。
        byte[] content = "Hello FC".getBytes();
        File localAwemePathfile = new File(localWavPath);
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, ossAwemeFolderPath + fileName, localAwemePathfile);
        Date uploadDate = new Date();
        log.info("上传时间{}",uploadDate.getTime()-beginDate.getTime());
        // 关闭OSSClient。
        ossClient.shutdown();

        //上传完 把本地文件删掉
        localAwemePathfile.delete();


        AwemeCallbackContent awemeContent = new AwemeCallbackContent();
        awemeContent.setAwemeAudioUrl(ossAwemeFolderPath + fileName);
        String post = HttpUtil.post(request.getContentCenterUrl(), JSONObject.toJSONString(awemeContent));
        log.info("post {}",post);

//        gc();

        return awemeContent;
    }

    public static String getTransferUrl(String url)  {
        if (url.indexOf("PUBLISH") > 0) {
            String awemeUrl = url;
            HttpURLConnection conn = null;
            try{
                conn = (HttpURLConnection) new URL(awemeUrl).openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(5000);
                String location = conn.getHeaderField("location");
                if (StrUtil.isEmpty(location)) {
                    log.info("中转链接为空url{},状态码{},conn为{}", url, conn.getResponseCode(), conn);
                }
                return location;
            }catch (Exception e){
                log.error("转抛错",e);
            }
        }
        return url;
    }

    /**
     * gc clean current dump
     */
    private static void gc() {
        //获取当前堆的大小 byte 单位
        long heapSize = Runtime.getRuntime().totalMemory();
        log.info("Current heap size{}m",heapSize/1024/1024);

        //获取堆的最大大小byte单位
        //超过将抛出 OutOfMemoryException
        long heapMaxSize = Runtime.getRuntime().maxMemory();
        log.info("Gets the maximum heap size{}m",heapMaxSize/1024/1024);

        //获取当前空闲的内存容量byte单位
        long heapFreeSize = Runtime.getRuntime().freeMemory();
        log.info("Gets the current free memory capacity{}m",heapFreeSize/1024/1024);

        System.gc();

        log.info("gc-after");

        heapSize = Runtime.getRuntime().totalMemory();
        log.info("Current heap size{}m",heapSize/1024/1024);

        //获取堆的最大大小byte单位
        //超过将抛出 OutOfMemoryException
        heapMaxSize = Runtime.getRuntime().maxMemory();
        log.info("Gets the maximum heap size{}m",heapMaxSize/1024/1024);

        //获取当前空闲的内存容量byte单位
        heapFreeSize = Runtime.getRuntime().freeMemory();
        log.info("Gets the current free memory capacity{}m",heapFreeSize/1024/1024);

        System.gc();
    }

}
