using System;
using System.Threading;
using System.Linq;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Library;
using System.Text.RegularExpressions;
using MySystem.Models;

namespace MySystem
{
    public class OssHelper
    {
        string key = "LTAI5tAp9ASZtq4wYzuXfeer"; //阿里云AccessKey ID
        string secret = "N0o6TwowU8r4aeNWoefMnnus9Q2saW";  //阿里云Access Key Secret
        public string PathName = ConfigurationManager.AppSettings["Database"].ToString();
        public string endpoint = "oss-cn-chengdu.aliyuncs.com";  //endpoint
        public string bucketName = "kexiaoshuang";
        public string SourceHost = ConfigurationManager.AppSettings["OssHost"].ToString();
        public bool OssStatus = true;
        public readonly static OssHelper Instance = new OssHelper();
        private OssHelper()
        {
            // SystemSet set = new WebCMSEntities().SystemSet.FirstOrDefault() ?? new SystemSet();
            // if (set.UploadOss == 1)
            // { 
            //     SourceHost = "http://" + ConfigurationManager.AppSettings["OSSBucketName"].ToString() + "." + ConfigurationManager.AppSettings["OSSEndpoint"].ToString();
            //     OssStatus = true;
            // }
            // else
            // { 
            //     SourceHost = "";
            //     OssStatus = false;
            // }
        }

        public void Start()//启动
        {
            Thread thread = new Thread(threadStart);
            thread.IsBackground = true;
            thread.Start();
        }

        public void Add(string data)
        {
            function.WritePage("/OSSTempFiles/", function.MD532(Guid.NewGuid().ToString()) + ".txt", data);
        }

        private void threadStart()
        {
            var client = new OssClient(endpoint, key, secret);
            while (true)
            {
                string dataFilePath = function.getPath("/OSSTempFiles/");
                DirectoryInfo TheFolder = new DirectoryInfo(dataFilePath);
                if (TheFolder.Exists)
                {
                    //遍历文件
                    if (TheFolder.GetFiles().Length > 0)
                    {
                        try
                        {
                            foreach (FileInfo NextFile in TheFolder.GetFiles())
                            {
                                string FileFullName = dataFilePath + NextFile.Name;
                                string data = function.ReadInstance("/OSSTempFiles/" + NextFile.Name);
                                ScanQueue(data, FileFullName, client);
                            }
                        }
                        catch (Exception ex)
                        {
                            function.WriteLog(ex.ToString(), "OSS上传队列异常");
                        }
                    }
                }
                //没有任务，休息1秒钟
                Thread.Sleep(1000);
            }
        }

        //要执行的方法
        public void ScanQueue(string data, string FileFullName)
        {
            // SystemSet set = new WebCMSEntities().SystemSet.FirstOrDefault() ?? new SystemSet();
            // if (set.UploadOss == 1)
            if(OssStatus)
            {
                var client = new OssClient(endpoint, key, secret);
                ScanQueue(data, FileFullName, client);
            }
        }
        private void ScanQueue(string data, string FileFullName, OssClient client)
        {
            // 上传文件。
            string localFile = function.getPath(PathName + data);
            string filePath = data.TrimStart('/');
            if (!data.StartsWith(PathName))
            {
                filePath = PathName + data;
            }
            var result = client.PutObject(bucketName, filePath, localFile, new ObjectMetadata()
            {
                ExpirationTime = DateTime.Parse("2050-12-31 23:59:59")
            });
            if (!string.IsNullOrEmpty(result.ETag))
            {
                if (result.ETag.Length == 32)
                {
                    if (File.Exists(localFile))
                    {
                        File.Delete(localFile);
                    }
                }
            }

            if (File.Exists(FileFullName))
            {
                File.Delete(FileFullName);
            }
        }




        /// <summary>
        /// 解析编辑器中的图片(oss)
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string CheckOSSPic(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                content = "";
            }
            if (OssStatus)
            {
                MatchCollection MC = Regex.Matches(content, "<img.*?>");
                foreach (Match match in MC)
                {
                    string imgstr = match.Value;
                    Match submatch = Regex.Match(imgstr, "src=\".*?\"");
                    if (submatch.Success)
                    {
                        string src = submatch.Value.Replace("src=\"", "").Replace("\"", "");
                        if (!src.StartsWith("http"))
                        {
                            content = content.Replace(src, OssHelper.Instance.SourceHost + src);
                        }
                    }
                }
            }
            return content;
        }
    }
}