package cn.com.ctop.common.module.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.mts.model.v20140618.*;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Configuration
@PropertySource("classpath:config.properties")
public class MpsUtils {
    public static final String OSS_LOCATION = "oss-cn-beijing";
    public static final String OSS_BUCKET = "ctop-part";

    /**
     * 排列选择（从列表中选择n个排列）
     * @param dataList 待选列表
     * @param n 选择个数
     */
    public static void arrangementSelect(String[] dataList, int n) {
        arrangementSelect(dataList, new String[n], 0);
    }

    /**
     * 排列选择
     * @param dataList 待选列表
     * @param resultList 前面（resultIndex-1）个的排列结果
     * @param resultIndex 选择索引，从0开始
     */
    private static void arrangementSelect(String[] dataList, String[] resultList, int resultIndex) {
        int resultLen = resultList.length;
        // 全部选择完时，输出排列结果
        if (resultIndex >= resultLen) {
            return;
        }

        // 递归选择下一个
        for (int i = 0; i < dataList.length; i++) {
            // 判断待选项是否存在于排列结果中
            boolean exists = false;
            for (int j = 0; j < resultIndex; j++) {
                if (dataList[i].equals(resultList[j])) {
                    exists = true;
                    break;
                }
            }
            // 排列结果不存在该项，才可选择
            if (!exists) {
                resultList[resultIndex] = dataList[i];
                arrangementSelect(dataList, resultList, resultIndex + 1);
            }
        }
    }

    /**
     * 组合选择（从列表中选择n个组合）
     * @param dataList 待选列表
     * @param n 选择个数
     */
    public static void combinationSelect(String[] dataList, int n) {

        combinationSelect(dataList, 0, new String[n], 0);
    }

    /**
     * 组合选择
     * @param dataList 待选列表
     * @param dataIndex 待选开始索引
     * @param resultList 前面（resultIndex-1）个的组合结果
     * @param resultIndex 选择索引，从0开始
     */
    private static void combinationSelect(String[] dataList, int dataIndex, String[] resultList, int resultIndex) {
        int resultLen = resultList.length;
        int resultCount = resultIndex + 1;
        // 全部选择完时，输出组合结果
        if (resultCount > resultLen) {
            return;
        }

        // 递归选择下一个
        for (int i = dataIndex; i < dataList.length + resultCount - resultLen; i++) {
            resultList[resultIndex] = dataList[i];
            combinationSelect(dataList, i + 1, resultList, resultIndex + 1);
        }
    }

    public static QueryJobListResponse.Job getJobStatus(String jobId){
        QueryJobListResponse.Job job = null;
        IAcsClient client = getClient();
        QueryJobListRequest request = new QueryJobListRequest();
        request.setJobIds(jobId);
        try {
            QueryJobListResponse response = client.getAcsResponse(request);
            job = response.getJobList().get(0);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return job;
    }
    /**
     * 排列计算公式A<sup>m</sup><sub>n</sub> = n!/(n - m)!
     * @param m
     * @param n
     * @return
     */
    public static long arrangement(int m, int n) {
        return m <= n ? factorial(n) / factorial(n - m) : 0;
    }

    /**
     * 计算阶乘数，即n! = n * (n-1) * ... * 2 * 1
     * @param n
     * @return
     */
    private static long factorial(int n) {
        long sum = 1;
        while( n > 0 ) {
            sum = sum * n--;
        }
        return sum;
    }

    /**
     * 组合计算公式C<sup>m</sup><sub>n</sub> = n! / (m! * (n - m)!)
     * @param m
     * @param n
     * @return
     */
    public static long combination(int m, int n) {
        return m <= n ? factorial(n) / (factorial(m) * factorial((n - m))) : 0;
    }

    public static IAcsClient getClient(){
        // 地域ID // RAM账号的AccessKey ID // RAM账号Access Key Secret
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-beijing",
                "LTAIbNbqWzSOklQV",
                "1rkPz7JNoXk8sJevPaeYHWqfkQXBGh");
        IAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    public static String mergeOneVideo(String startPart, List<String> videoPart, String endPart){
        IAcsClient client = getClient();
        String pipelineId = getPipelineId(client);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String outputFilename = "output/"+sdf.format(new Date())+"/"+ UUID.randomUUID()+".mp4";
        List<String> videos = new ArrayList<>();
        videos.add(startPart);
        videos.addAll(videoPart);
        videos.add(endPart);
        return mergeVideo(client,pipelineId,videos,outputFilename);
    }

    public static String mergeVideo(IAcsClient client, String pipelineId, List<String> videos, String outputName){
        String jobId = null;
        SubmitJobsRequest request = new SubmitJobsRequest();
        JSONArray mergeList = new JSONArray();
        if (videos != null && videos.size() > 0){
            for (int i = 0; i < videos.size();i++){
                String url = videos.get(i);
                if (i == 0){
                    JSONObject input = new JSONObject();
                    input.put("Location", OSS_LOCATION);
                    input.put("Bucket", OSS_BUCKET);
                    try {
                        input.put("Object", URLEncoder.encode(url, "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException("input URL encode failed");
                    }
                    request.setInput(input.toJSONString());
                }else {
                    JSONObject mergeVideo = new JSONObject();
                    String mergeVideoUrl;
                    try {
                        mergeVideoUrl = String.format(
                                "http://%s.%s.aliyuncs.com/%s",
                                OSS_BUCKET,
                                OSS_LOCATION,
                                URLEncoder.encode(url, "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException("mergeVideoURL encode failed");
                    }
                    mergeVideo.put("MergeURL", mergeVideoUrl);
                    mergeList.add(mergeVideo);
                }
            }
        }
//        String outputOssObject;
//        try {
//            outputOssObject = URLEncoder.encode(outputName, "utf-8");
//            outputOssObject = outputName;
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException("output URL encode failed");
//        }
        JSONObject output = new JSONObject();
        output.put("OutputObject", outputName);
        JSONObject video = new JSONObject();
        video.put("Width", "720");
        video.put("Height", "1280");
        output.put("Video", video.toJSONString());
        output.put("MergeList", mergeList.toJSONString());
        // Outputs
        JSONArray outputs = new JSONArray();
        outputs.add(output);
        request.setOutputs(outputs.toJSONString());
        request.setOutputBucket(OSS_BUCKET);
        request.setOutputLocation(OSS_LOCATION);
        // PipelineId
        request.setPipelineId(pipelineId);
        // call api
        SubmitJobsResponse response;
        try {
            response = client.getAcsResponse(request);
            if (response.getJobResultList().get(0).getSuccess()) {
                jobId = response.getJobResultList().get(0).getJob().getJobId();
            } else {
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return jobId;
    }

    public String videoWaterMark(String videoPath,String waterMarkPath,String watermarkTemplateId,Integer height){
        String jobId = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String outputFilename = "watermark/"+sdf.format(new Date())+"/"+ UUID.randomUUID()+".mp4";
        IAcsClient client = getClient();
        String pipelineId = getPipelineId(client);
        SubmitJobsRequest request = new SubmitJobsRequest();
        JSONObject input = new JSONObject();
        input.put("Location", OSS_LOCATION);
        input.put("Bucket", "ctop-media");
        input.put("Object", videoPath);
        request.setInput(input.toJSONString());
        JSONObject videoWatermarkInput = new JSONObject();
        videoWatermarkInput.put("Location", OSS_LOCATION);
        videoWatermarkInput.put("Bucket", "ctop-media");
        videoWatermarkInput.put("Object", waterMarkPath);
        JSONObject videoWatermark = new JSONObject();
        videoWatermark.put("WaterMarkTemplateId", watermarkTemplateId);
        videoWatermark.put("Type", "Image");
        videoWatermark.put("InputFile", videoWatermarkInput);
        videoWatermark.put("ReferPos", "BottomLeft");
        videoWatermark.put("Height", height);
        videoWatermark.put("Dx", "0");
        videoWatermark.put("Dy", "0");
        JSONObject output = new JSONObject();
        output.put("OutputObject", outputFilename);
        JSONArray watermarks = new JSONArray();
        watermarks.add(videoWatermark);
        output.put("WaterMarks", watermarks.toJSONString());
        // Outputs
        JSONArray outputs = new JSONArray();
        outputs.add(output);
        request.setOutputs(outputs.toJSONString());
        request.setOutputBucket("ctop-media");
        request.setOutputLocation(OSS_LOCATION);
        // PipelineId
        request.setPipelineId(pipelineId);
        SubmitJobsResponse response;
        try {
            response = client.getAcsResponse(request);
            if (response.getJobResultList().get(0).getSuccess()) {
                jobId = response.getJobResultList().get(0).getJob().getJobId();
            } else {

            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return jobId;
    }


    public static String getPipelineId(IAcsClient client){
        String pipelineId = null;
        // 创建API请求并设置参数
        SearchPipelineRequest request = new SearchPipelineRequest();
        // 发起请求并处理应答或异常
        SearchPipelineResponse response;
        try {
            response = client.getAcsResponse(request);
            pipelineId = response.getPipelineList().get(0).getId();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return pipelineId;
    }
}
