using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using Aliyun.OSS;
using Microsoft.AspNetCore.Http;
using ASHermed.SinoInterface.ContractModel;

namespace ASHermed.SinoInterface.Tools.Base
{
    /// <summary>
    /// 上传阿里云帮助类
    /// </summary>
    public static class UploadHelper
    {
        #region 上传文件
        private static string AccessKeyID = "LTAI4FkVAEWHKcBUE3tAeZXH";

        private static string AccessKeySecret = "VDg3LkKG2CWqh0KuxgFQO2uFC8Mr1X";

        private static string endPoint = "http://oss-cn-shanghai.aliyuncs.com";

        private static string bucket = "sinoapp";


        private static string fileUrl = "https://sinoapp.oss-cn-shanghai.aliyuncs.com/";
        /// <summary>
        /// 上传文件
        /// </summary>
        public static BaseResponse<string> Upload(IFormFile file, string fname, string fileFolder = "")
        {
            var resu = new BaseResponse<string>();
            resu.Code = 1;

            try
            {
                string url = string.Empty;
                if (file != null)
                {
                    OssClient client = new OssClient(endPoint, AccessKeyID, AccessKeySecret);

                    var objMetadata = new ObjectMetadata();

                    int lastSlashIndex = file.FileName.LastIndexOf("\\");
                    string fileName = file.FileName.Substring(lastSlashIndex + 1, file.FileName.Length - lastSlashIndex - 1);
                    string fix = string.Empty;//获取文件后缀
                    string fnames = string.Empty;//获取文件
                    if (fileName.LastIndexOf(".") > 0)
                    {
                        fix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();//获取文件后缀
                        fnames = fileName.Substring(0, fileName.LastIndexOf("."));//获取文件
                    }


                    //上传文件到指定文件夹中，若没有，则上传到根目录
                    string folderName = string.IsNullOrEmpty(fileFolder) ? string.Empty : fileFolder + "_";
                    string filename = !string.IsNullOrEmpty(fname) ? folderName + fname : fnames + "_" + newCode() + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + fix;
                    var putResult = client.PutObject(bucket, filename, file.OpenReadStream(), objMetadata);
                    url = fileUrl + filename;
                    resu.Data = url;
                    return resu;

                }
                return resu;
            }
            catch (Exception ex)
            {
                resu.Code = 0;
                resu.Msg = ex.Message;
                return resu;
            }
        }

        public static string UploadToStream(Stream stream, string filename)
        {
            string url = string.Empty;
            try
            {
                OssClient client = new OssClient(endPoint, AccessKeyID, AccessKeySecret);
                var objMetadata = new ObjectMetadata();
                var putResult = client.PutObject(bucket, filename, stream, objMetadata);
                url = fileUrl + filename;
            }
            catch (System.Exception e) { }
            return url;
        }
        #endregion

        #region 下载文件(URL)
        public static string HttpDownloadFile(string url, string filename, string fileFolder = "")
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            if (!string.IsNullOrEmpty(fileFolder))
            {
                filename = fileFolder + "/" + filename;
            }
            return UploadToStream(responseStream, filename);
            ////创建本地文件写入流
            //Stream stream = new FileStream(path, FileMode.Create);

            //byte[] bArr = new byte[1024];
            //int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            //while (size > 0)
            //{
            //    stream.Write(bArr, 0, size);
            //    size = responseStream.Read(bArr, 0, (int)bArr.Length);
            //}
            //stream.Close();
            //responseStream.Close();
            //return path;
        }


        #endregion


        #region 随机数
        /// <summary>
        /// 随机数
        /// </summary>
        /// <returns></returns>
        public static string newCode()
        {
            string str = "";
            //for (int i = 0; i < 2; i++)
            //{
            //    Random random = new Random();
            //    int num = random.Next(97, 123);
            //    str += Convert.ToChar(num).ToString();
            //}
            //for (int i = 0; i < 6; i++)
            //{
            //    Random random = new Random();
            //    int n = random.Next(0, 9);   //生成10-20之间的随机数
            //    str += n;
            //}
            Random rnd = new Random();
            str = rnd.Next(100000, 999999).ToString();
            return str;
        }
        #endregion

    }
}
