using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Aliyun.OSS;
using Aliyun.OSS.Common;

namespace BPASmartClient.IoT.Model
{
    public class OSS_Helper
    {
        const string accessKeyId = "xxx";
        const string accessKeySecret = "xxx";
        const string endpoint = "http://oss-cn-shanghai.aliyuncs.com";
        const string bucketName = "xxx";
        OssClient client = null;

        public OSS_Helper()
        {
            // 由用户指定的OSS访问地址、阿里云颁发的AccessKeyId/AccessKeySecret构造一个新的OssClient实例。
            client = new OssClient(endpoint, accessKeyId, accessKeySecret);
        }

        /*简单上传：文件最大不能超过5GB。
          追加上传：文件最大不能超过5GB。
          断点续传上传：支持并发、断点续传、自定义分片大小。大文件上传推荐使用断点续传。最大不能超过48.8TB。
          分片上传：当文件较大时，可以使用分片上传，最大不能超过48.8TB。*/
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objectName"></param>
        /// <param name="localFilename"></param>
        public void Simple_Up(string objectName, string localFilename)
        {

            //var objectName = "Project/222.jpg";
            //var localFilename = @"C:\tiger.jpg";
            // 创建OssClient实例。
            try
            {
                // 上传文件。
                client.PutObject(bucketName, objectName, localFilename);
                Console.WriteLine("Put object succeeded");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put object failed, {0}", ex.Message);
            }
        }
        /// <summary>
        /// 分片上传
        /// </summary>
        /// <param name="objectName"></param>
        /// <param name="localFilename"></param>
        public void Multipar_tUp(string objectName, string localFilename)
        {
            var uploadId = "";
            try
            {
                // 定义上传文件的名字和所属存储空间。在InitiateMultipartUploadRequest中，可以设置ObjectMeta，但不必指定其中的ContentLength。
                var request = new InitiateMultipartUploadRequest(bucketName, objectName);
                var result = client.InitiateMultipartUpload(request);
                uploadId = result.UploadId;
                // 打印UploadId。
                Console.WriteLine("Init multi part upload succeeded");
                Console.WriteLine("Upload Id:{0}", result.UploadId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            // 计算分片总数。
            var partSize = 1024 * 1024;
            var fi = new FileInfo(localFilename);
            var fileSize = fi.Length;
            var partCount = fileSize / partSize;
            if (fileSize % partSize != 0)
            {
                partCount++;
            }
            // 开始分片上传。partETags是保存partETag的列表，OSS收到用户提交的分片列表后，会逐一验证每个分片数据的有效性。 当所有的数据分片通过验证后，OSS会将这些分片组合成一个完整的文件。
            var partETags = new List<PartETag>();
            try
            {
                using (var fs = File.Open(localFilename, FileMode.Open))
                {
                    for (var i = 0; i < partCount; i++)
                    {
                        var skipBytes = (long)partSize * i;
                        // 定位到本次上传起始位置。
                        fs.Seek(skipBytes, 0);
                        // 计算本次上传的片大小，最后一片为剩余的数据大小。
                        var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
                        var request = new UploadPartRequest(bucketName, objectName, uploadId)
                        {
                            InputStream = fs,
                            PartSize = size,
                            PartNumber = i + 1
                        };
                        // 调用UploadPart接口执行上传功能，返回结果中包含了这个数据片的ETag值。
                        var result = client.UploadPart(request);
                        partETags.Add(result.PartETag);
                        Console.WriteLine("finish {0}/{1}", partETags.Count, partCount);
                    }
                    Console.WriteLine("Put multi part upload succeeded");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            // 列举已上传的分片。
            try
            {
                var listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId);
                var listPartsResult = client.ListParts(listPartsRequest);
                Console.WriteLine("List parts succeeded");
                // 遍历所有分片。
                var parts = listPartsResult.Parts;
                foreach (var part in parts)
                {
                    Console.WriteLine("partNumber: {0}, ETag: {1}, Size: {2}", part.PartNumber, part.ETag, part.Size);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            // 完成分片上传。
            try
            {
                var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
                foreach (var partETag in partETags)
                {
                    completeMultipartUploadRequest.PartETags.Add(partETag);
                }
                var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
                Console.WriteLine("complete multi part succeeded");
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="objectName"></param>
        /// <param name="localFilename"></param>
        /// <param name="checkpointDir"></param>
        public void chkin_Up(string objectName, string localFilename, string checkpointDir)
        {
            try
            {
                // 通过UploadFileRequest设置多个参数。
                UploadObjectRequest request = new UploadObjectRequest(bucketName, objectName, localFilename)
                {
                    // 指定上传的分片大小。
                    PartSize = 1024 * 1024,
                    // 指定并发线程数。
                    ParallelThreadCount = 10,
                    // checkpointDir保存断点续传的中间状态，用于失败后继续上传。如果checkpointDir为null，断点续传功能不会生效，每次失败后都会重新上传。
                    CheckpointDir = checkpointDir,
                };
                // 断点续传上传。
                client.ResumableUploadObject(request);
                Console.WriteLine("Resumable upload object:{0} succeeded", objectName);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }

        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="objectName"></param>
        /// <param name="downloadFilename"></param>
        public void Stream_Down(string objectName, string downloadFilename)
        {
            // objectName 表示您在下载文件时需要指定的文件名称，如abc/efg/123.jpg。
            //var objectName = "Project/cc.jpg";
            //var downloadFilename = @"D:\GG.jpg";
            // 创建OssClient实例。
            //var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                // 下载文件到流。OssObject 包含了文件的各种信息，如文件所在的存储空间、文件名、元信息以及一个输入流。
                var obj = client.GetObject(bucketName, objectName);
                using (var requestStream = obj.Content)
                {
                    byte[] buf = new byte[1024];
                    var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
                    var len = 0;
                    // 通过输入流将文件的内容读取到文件或者内存中。
                    while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                    {
                        fs.Write(buf, 0, len);
                    }
                    fs.Close();
                }
                Console.WriteLine("Get object succeeded");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Get object failed. {0}", ex.Message);
            }
        }

        public void DownPBar()
        {

        }

        public static void GetObjectProgress()
        {
            var endpoint = "<yourEndpoint>";
            var accessKeyId = "<yourAccessKeyId>";
            var accessKeySecret = "<yourAccessKeySecret>";
            var bucketName = "<yourBucketName>";
            var objectName = "<yourObjectName>";
            // 创建OssClient实例。
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                var getObjectRequest = new GetObjectRequest(bucketName, objectName);
                getObjectRequest.StreamTransferProgress += streamProgressCallback;
                // 下载文件。
                var ossObject = client.GetObject(getObjectRequest);
                using (var stream = ossObject.Content)
                {
                    var buffer = new byte[1024 * 1024];
                    var bytesRead = 0;
                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        // 处理读取的数据（此处代码省略）。
                    }
                }
                Console.WriteLine("Get object:{0} succeeded", objectName);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }

        private static void streamProgressCallback(object sender, StreamTransferProgressArgs args)
        {
            System.Console.WriteLine("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ",
                args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes);
        }

    }
}
