using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.vod.Model.V20170321;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JiaZhiQuan.Common.AliVod
{
    public class AliVODHelper
    {
        readonly VodConfig config;
        DefaultAcsClient client;

        public AliVODHelper(VodConfig config)
        {
            this.config = config;
        }

        public DefaultAcsClient GetVodClient()
        {
            //string regionId = "cn-shanghai";
            //IClientProfile profile = DefaultProfile.GetProfile(regionId, config.AccessKeyId, config.AccessKeySecret);
            //// DefaultProfile.AddEndpoint(regionId, regionId, "vod", "vod." + regionId + ".aliyuncs.com");
            //return new DefaultAcsClient(profile);

            if (client == null)
            {
                lock (this)
                {
                    if (client == null)
                    {
                        string regionId = "cn-shanghai";
                        IClientProfile profile = DefaultProfile.GetProfile(regionId, config.AccessKeyId, config.AccessKeySecret);
                        // DefaultProfile.AddEndpoint(regionId, regionId, "vod", "vod." + regionId + ".aliyuncs.com");
                        client = new DefaultAcsClient(profile);
                    }
                    return client;
                }
            }
            else
            {
                return client;
            }
        }

        /// <summary>
        /// 人工批量审核
        /// </summary>
        /// <param name="videoIds">最多20条</param>
        /// <param name="pass">是否通过</param>
        /// <param name="reason">如果未通过，给出理由</param>
        /// <param name="comment">审核备注</param>
        /// <returns></returns>
        public CreateAuditResponse ManualAudit(List<string> videoIds, bool pass, string reason, string comment)
        {
            var req = new CreateAuditRequest();
            JArray auditContents = new JArray();
            foreach (var videoId in videoIds)
            {
                JObject auditContent = new JObject();
                auditContent.Add("VideoId", videoId);
                auditContent.Add("Status", pass ? "Normal" : "Blocked");
                if (!pass && !string.IsNullOrEmpty(reason)) {
                    auditContent.Add("Reason", reason);
                }
                if (!string.IsNullOrEmpty(comment))
                {
                    auditContent.Add("Comment", comment);
                }
                auditContents.Add(auditContent);
            }
            req.AuditContent = auditContents.ToString();
            return GetVodClient().GetAcsResponse(req);
        }

        public CreateAuditResponse AutoManualAudit(string videoId)
        {
            var req = new CreateAuditRequest();
            JArray auditContents = new JArray();
            JObject auditContent = new JObject();
            auditContent.Add("VideoId", videoId);
            auditContent.Add("Status", "Normal");
            auditContent.Add("Comment", "机审通过，人工自动通过");
            auditContents.Add(auditContent);
            req.AuditContent = auditContents.ToString();
            return GetVodClient().GetAcsResponse(req);
        }

        /// <summary>
        /// 获取视频上传地址和凭证
        /// </summary>
        /// <param name="title">长度不超过128个字符或汉字。</param>
        /// <param name="fileName">必须带扩展名，且扩展名不区分大小写</param>
        /// <param name="tags">
        /// 最多不超过16个标签，多个用逗号分隔。单个标签不超过32个字符或汉字。
        /// </param>
        /// <param name="cateId">分类</param>
        /// <returns></returns>
        public CreateUploadVideoResponse GetUploadVideoInfo(string title, string fileName, string tags, long cateId)
        {
            CreateUploadVideoRequest request = new CreateUploadVideoRequest();
            request.Title = title;
            request.FileName = fileName;
            request.Tags = tags;
            request.CateId = cateId;
            request.WorkflowId = config.AutofitDefaultWorkflow;
            // 发起请求，并得到响应结果
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 刷新视频上传凭证
        /// </summary>
        /// <param name="videoId"></param>
        /// <param name="client"></param>
        public RefreshUploadVideoResponse RefreshUploadVideoInfo(string videoId)
        {
            RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
            request.VideoId = videoId;
            // 发起请求，并得到 response
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 获取图片上传地址和凭证
        /// </summary>
        /// <param name="imageType">
        /// 图片类型。取值范围：default（默认）cover（封面）控制台暂时只支持default类型的图片管理。
        /// </param>
        /// <param name="imageExt">
        /// 图片文件扩展名。取值范围：png jpg jpeg gif 默认值：png
        /// </param>
        public CreateUploadImageResponse GetUploadImageInfo(string imageType, string imageExt)
        {
            CreateUploadImageRequest request = new CreateUploadImageRequest();
            request.ImageType = imageType;
            request.ImageExt = imageExt;
            // 发起请求，并得到 response
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 获取视频播放地址，8小时有效
        /// </summary>
        /// <param name="videoId"></param>
        /// <returns></returns>
        public GetPlayInfoResponse GetPlayInfo(string videoId)
        {
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.VideoId = videoId;
            request.Definition = "AUTO,HD,SD,OD";
            request.AuthTimeout = 3600 * 8; // 8小时
            //request.Formats = "mp4";
            //request.OutputType = "oss";
            //request.PlayConfig = JsonConvert.SerializeObject(new { EncryptType = "Unencrypted" });
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 获取视频播放地址（试看）
        /// </summary>
        /// <param name="videoId"></param>
        /// <param name="previewSeconds">试看多少秒</param>
        /// <returns></returns>
        public GetPlayInfoResponse GetPlayInfo(string videoId, int previewSeconds)
        {
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.VideoId = videoId;
            request.Definition = "AUTO,HD,SD,OD";
            request.AuthTimeout = 3600 * 2; // 两小时
            request.PlayConfig = JsonConvert.SerializeObject(new
            {
                PreviewTime = previewSeconds
            });
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 获取视频播放凭证
        /// </summary>
        /// <param name="videoId"></param>
        /// <returns></returns>
        public GetVideoPlayAuthResponse GetPlayAuth(string videoId)
        {
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.VideoId = videoId;
            request.AuthInfoTimeout = 3000;
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 获取视频信息
        /// </summary>
        /// <param name="videoId"></param>
        /// <returns></returns>
        public GetVideoInfoResponse GetVideoInfo(string videoId)
        {
            GetVideoInfoRequest request = new GetVideoInfoRequest();
            request.VideoId = videoId;
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 获取原始视频信息
        /// </summary>
        /// <param name="videoId"></param>
        /// <returns></returns>
        public GetMezzanineInfoResponse GetMezzanineInfo(string videoId)
        {
            var request = new GetMezzanineInfoRequest();
            request.ActionName = "GetMezzanineInfo";
            request.AuthTimeout = 60 * 60 * 24 * 15L;
            request.VideoId = videoId;
            request.OutputType = "cdn";
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 批量获取视频信息
        /// </summary>
        /// <param name="videoIds">
        /// 逗号分隔，最多支持20个
        /// </param>
        /// <returns></returns>
        public GetVideoInfosResponse GetVideoInfos(string videoIds)
        {
            GetVideoInfosRequest request = new GetVideoInfosRequest();
            request.VideoIds = videoIds;
            return GetVodClient().GetAcsResponse(request);
        }

        /// <summary>
        /// 批量删除视频
        /// </summary>
        /// <param name="videoIds">
        /// 逗号分隔，最多支持20个。
        /// </param>
        /// <returns></returns>
        public DeleteVideoResponse DeleteVideos(string videoIds)
        {
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.VideoIds = videoIds;
            return GetVodClient().GetAcsResponse(request);
        }
    }
}
