package com.platform.plugs.live.handlers;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.vod.upload.impl.UploadImageImpl;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.impl.VoDProgressListener;
import com.aliyun.vod.upload.req.UploadImageRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadImageResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.platform.modules.live.utils.ForeignProperties;
import com.platform.plugs.live.config.LiveUploadToVoDConfig;
import com.platform.plugs.live.rpcEntity.LiveUploadVideo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;

public class LiveUploadToVoDHandler implements ILiveUploadToVoDHandler {

    private LiveUploadToVoDConfig liveUploadToVoDConfig;
    private DefaultAcsClient client;
    @Autowired
    private ForeignProperties foreignProperties;

    public void configLiveUploadToVoD(LiveUploadToVoDConfig liveUploadToVoDConfig) {
        this.liveUploadToVoDConfig = liveUploadToVoDConfig;
        this.client = new DefaultAcsClient(DefaultProfile.getProfile(liveUploadToVoDConfig.getApiRegionId(), liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret()));
    }

    @Override
    public UploadStreamResponse uploadStream(String title, String fileName, InputStream inputStream, boolean isShowWaterMark, Long cateId, String tags,
                                             String description, String coverURL, String templateGroupId, boolean printProgress, VoDProgressListener voDProgressListener) {
        UploadStreamRequest request = new UploadStreamRequest(liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret(), title, fileName, inputStream);
        /* 是否使用默认水印(可选)，指定模板组ID时，根据模板组配置确定是否使用默认水印*/
        request.setShowWaterMark(isShowWaterMark);
        /* 设置上传完成后的回调URL(可选)，建议通过点播控制台配置消息监听事件，参见文档 https://help.aliyun.com/document_detail/57029.html */
//       request.setCallback("http://s34bjit.hn3.mofasuidao.cn/platform/live/notify/fileUploadComplete");
        /* 自定义消息回调设置，参数说明参考文档 https://help.aliyun.com/document_detail/86952.html#UserData */
//       request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}");
        /* 视频分类ID(可选) */
        request.setCateId(cateId);
        /* 视频标签,多个用逗号分隔(可选) */
        request.setTags(tags);
        /* 视频描述(可选) */
        request.setDescription(description);
        /* 封面图片(可选) */
        request.setCoverURL(coverURL);
        /* 模板组ID(可选) */
        if (templateGroupId != null) {
            request.setTemplateGroupId(templateGroupId);
        }

        /* 工作流ID(可选) */
        //request.setWorkflowId("d4430d07361f0*be1339577859b0177b");
        /* 存储区域(可选) */
        request.setStorageLocation(liveUploadToVoDConfig.getBucket() + "." + liveUploadToVoDConfig.getEndpoint());
        /* 开启默认上传进度回调 */
        request.setPrintProgress(printProgress);
        /* 设置自定义上传进度回调 (必须继承 VoDProgressListener) */
        request.setProgressListener(voDProgressListener);
        request.setApiRegionId(liveUploadToVoDConfig.getApiRegionId());
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return response;
    }

    @Override
    public UploadVideoResponse uploadLocalVideo(String title, String fileName, LiveUploadVideo uploadVideo) {
        UploadVideoRequest request = new UploadVideoRequest(liveUploadToVoDConfig.getAccessKeyId(),
                liveUploadToVoDConfig.getAccessKeySecret(), title, fileName);
        /* 可指定分片上传时每个分片的大小，默认为2M字节 */
        request.setPartSize(4 * 1024 * 1024L);
        /* 可指定分片上传时的并发线程数，默认为1，(注：该配置会占用服务器CPU资源，需根据服务器情况指定）*/
        request.setTaskNum(5);
        if (null != uploadVideo.getEnableCheckpoint()) {
            request.setEnableCheckpoint(uploadVideo.getEnableCheckpoint());
        }
        /* OSS慢请求日志打印超时时间，是指每个分片上传时间超过该阈值时会打印debug日志，如果想屏蔽此日志，请调整该阈值。单位: 毫秒，默认为300000毫秒*/
        //request.setSlowRequestsThreshold(300000L);
        /* 可指定每个分片慢请求时打印日志的时间阈值，默认为300s*/
        //request.setSlowRequestsThreshold(300000L);
        /* 是否显示水印(可选)，指定模板组ID时，根据模板组配置确定是否显示水印 */
        if (null != uploadVideo.getIsShowWaterMark()) {
            request.setIsShowWaterMark(uploadVideo.getIsShowWaterMark());
        }
        /* 设置上传完成后的回调URL(可选)，建议您通过点播控制台配置事件通知，参见文档 https://help.aliyun.com/document_detail/55627.html */
        //request.setCallback("http://callback.sample.com");
        /* 自定义消息回调设置(可选)，参数说明参考文档 https://help.aliyun.com/document_detail/86952.html#UserData */
        // request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}");
        /* 视频分类ID(可选) */
        if (null != uploadVideo.getCateId()) {
            request.setCateId(uploadVideo.getCateId());
        }
        /* 视频标签,多个用逗号分隔(可选) */
        if (StringUtils.isNotBlank(uploadVideo.getTags())) {
            request.setTags(uploadVideo.getTags());
        }
        /* 视频描述(可选) */
        if (StringUtils.isNotBlank(uploadVideo.getDescription())) {
            request.setDescription(uploadVideo.getDescription());
        }
        /* 封面图片(可选) */
        if (StringUtils.isNotBlank(uploadVideo.getCoverURL())) {
            request.setCoverURL(uploadVideo.getCoverURL());
        }
        /* 模板组ID(可选) */
        if (StringUtils.isNotBlank(uploadVideo.getTemplateGroupId())) {
            request.setTemplateGroupId(uploadVideo.getTemplateGroupId());
        }
        /* 工作流ID(可选) */
        if (StringUtils.isNotBlank(uploadVideo.getWorkflowId())) {
            request.setWorkflowId(uploadVideo.getWorkflowId());
        }
        /* 存储区域(可选) */
        request.setStorageLocation(liveUploadToVoDConfig.getBucket() + "." + liveUploadToVoDConfig.getEndpoint());
        /* 开启默认上传进度回调 */
        if (null != uploadVideo.getPrintProgress()) {
            request.setPrintProgress(uploadVideo.getPrintProgress());
        }
        /* 设置自定义上传进度回调 (必须继承 VoDProgressListener) */
        if (null != uploadVideo.getProgressListener()) {
            request.setProgressListener(uploadVideo.getProgressListener());
        }
        request.setApiRegionId(liveUploadToVoDConfig.getApiRegionId());
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        return response;
    }

    @Override
    public UploadImageResponse uploadImageStream(String title, String fileName, InputStream inputStream, String imageType, String imageExt, String tags,
                                                 boolean printProgress, VoDProgressListener voDProgressListener) {
        /* 图片类型（必选）取值范围：default（默认)，cover（封面），watermark（水印）*/
        UploadImageRequest request = new UploadImageRequest(liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret(), imageType);
        /* 图片文件扩展名（可选）取值范围：png，jpg，jpeg */
        request.setImageExt(imageExt);
        /* 图片标题（可选）长度不超过128个字节，UTF8编码 */
        request.setTitle(title);
        /* 图片标签（可选）单个标签不超过32字节，最多不超过16个标签，多个用逗号分隔，UTF8编码 */
        request.setTags(tags);
        /* 存储区域（可选）*/
        request.setStorageLocation(liveUploadToVoDConfig.getBucket() + "." + liveUploadToVoDConfig.getEndpoint());
        /* 流式上传时，InputStream为必选，fileName为源文件名称，如:文件名称.png(可选)*/
        request.setFileName(fileName);
        /* 开启默认上传进度回调 */
        request.setPrintProgress(printProgress);
        /* 设置自定义上传进度回调 (必须继承 VoDProgressListener) */
        request.setProgressListener(voDProgressListener);
        request.setApiRegionId(liveUploadToVoDConfig.getApiRegionId());
        /* 设置图片文件流*/
        if (null != inputStream) {
            request.setInputStream(inputStream);
        }

        // 开始上传图片
        UploadImageImpl uploadImage = new UploadImageImpl();
        UploadImageResponse response = uploadImage.upload(request);
        if (!response.isSuccess()) {
            System.out.println("----------------------" + JSONObject.toJSONString(response));
            System.out.println("----------------------" + JSONObject.toJSONString(request));
            System.out.println("----------------------" + JSONObject.toJSONString(liveUploadToVoDConfig));
        }
        return response;
    }

    @Override
    public UpdateVideoInfoResponse updateVideoInfo(String videoId, String title, String description, Long cateId, String tags) throws ServerException, ClientException {
//        DefaultAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(liveUploadToVoDConfig.getApiRegionId(), liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret()));
        UpdateVideoInfoRequest request = new UpdateVideoInfoRequest();
        request.setVideoId(videoId);
        request.setTitle(title);
        request.setDescription(description);
        request.setCateId(cateId);
        request.setTags(tags);
//	    request.setCoverURL(coverURL);
        return this.client.getAcsResponse(request);
    }

    @Override
    public UpdateImageInfosResponse updateContent(String imageId, String title, String description, Long cateId, String tags) throws ServerException, ClientException {
//        DefaultAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(liveUploadToVoDConfig.getApiRegionId(), liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret()));
        UpdateImageInfosRequest request = new UpdateImageInfosRequest();
        JSONArray array = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("ImageId", imageId);
        json.put("Title", title);
        json.put("Description", description);
        json.put("CateId", cateId);
        json.put("Tags", tags);
        array.add((json));
        request.setUpdateContent(array.toJSONString());
        return this.client.getAcsResponse(request);
    }

    @Override
    public GetMezzanineInfoResponse getMezzanineInfo(String videoId) throws Exception {
//        DefaultAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(liveUploadToVoDConfig.getApiRegionId(), liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret()));
        GetMezzanineInfoRequest request = new GetMezzanineInfoRequest();
        request.setVideoId(videoId);
        return this.client.getAcsResponse(request);
    }

    /**
     * 获取视频信息
     *
     * @throws Exception
     */
    @Override
    public GetVideoInfoResponse getVideoInfo(String videoId) throws Exception {
//        DefaultAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(liveUploadToVoDConfig.getApiRegionId(), liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret()));
        GetVideoInfoRequest request = new GetVideoInfoRequest();
        request.setVideoId(videoId);
        return this.client.getAcsResponse(request);
    }

    /**
     * 获取图片信息函数
     *
     * @throws Exception
     */
    public GetImageInfoResponse getImageInfo(String imageId) throws Exception {
//        DefaultAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile(liveUploadToVoDConfig.getApiRegionId(), liveUploadToVoDConfig.getAccessKeyId(), liveUploadToVoDConfig.getAccessKeySecret()));
        GetImageInfoRequest request = new GetImageInfoRequest();
        request.setImageId(imageId);
        return this.client.getAcsResponse(request);
    }

	@Override
	public GetPlayInfoResponse getM3u8PlayInfo(String videoId) throws ClientException {

    	GetPlayInfoRequest request = new GetPlayInfoRequest();
    	request.setVideoId(videoId);
    	request.setFormats("m3u8");

		return this.client.getAcsResponse(request);
	}
}
