using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VIZ.Framework.Core;
using VIZ.Package.Domain;

namespace VIZ.Package.Module
{
    public class MediaResourceFileController
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(typeof(MediaResourceFileController));

        /// <summary>
        /// VIZ资源缩略图控制器
        /// </summary>
        /// <param name="support">支持</param>
        public MediaResourceFileController(IMediaResourceFileSupport support)
        {
            this.Support = support;
        }

        /// <summary>
        /// 支持
        /// </summary>
        public IMediaResourceFileSupport Support { get; private set; }


        /// <summary>
        /// 根目录
        /// </summary>
        public string RootPath { get; set; }
        /// <summary>
        /// 更新文件模型
        /// </summary>
        /// <param name="folder">文件夹</param>
        public void UpdateFileModels(MHResourceFolderModel folder)
        {
            // 文件夹对象不存在
            if (folder == null)
            {
                this.Support.FileModels = null;
                this.Support.SelectedFileModel = null;
                return;
            }

            //// 已经获取过文件
            if (folder.IsRefreshedFiles)
            {
                this.Support.FileModels = folder.Files;
                return;
            }

            WPFHelper.BeginInvoke(async () =>
            {
                try
                {
                    string header = string.Format("{0}GetListFile?filePath={1}&isResize=false", ApplicationDomainEx.MediaConfig.Url, folder.Path);
                    log.Info("调用接口开始");
                    var FileResult = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(header, "");
                    log.Info("调用接口结束");
                    List<MHResourceFileModel> list = new List<MHResourceFileModel>();
                    // folder.Files = new System.Collections.ObjectModel.ObservableCollection<GHResourceFileModel>();
                    if (FileResult==null||FileResult.masterData == null) return;
                    int i = 0;
                    foreach (var file in FileResult.masterData)
                    {
                        //Task.Run(async () =>
                        //{
                        try
                        {
                            MHResourceFileModel GHFile = new MHResourceFileModel();
                            if (ThumbnailHelper.IsImageByName(file.fileName)|| ThumbnailHelper.IsVideo(file.fileName))
                            {
                                GHFile.Name = file.fileName;
                                GHFile.Path = file.smallIconUrl;
                                string url = string.Format("{0}GetFile?filePath={1}", ApplicationDomainEx.MediaConfig.Url, GHFile.Path);

                                log.Info("获取图片开始");
                                var fileResult = await MediaResourceFileService.GetImage(url);

                                log.Info("后去图片结束");

                                if (ThumbnailHelper.IsImageByName(file.fileName))
                                {
                                    GHFile.FileType = ResourceFileType.IMAGE;
                                }
                                else
                                {
                                    GHFile.FileType = ResourceFileType.VIDEO;   
                                }
                                GHFile.Date = Convert.ToDateTime(file.fileUpdateTime).ToString("yyyy/MM/dd HH:mm");
                                GHFile.FileSize = file.fileSize;

                                if (ThumbnailHelper.IsVideo(fileResult))
                                {
                                    Image img = Image.FromStream(fileResult);

                                    // img = ThumbnailHelper.GetThumbnail(img, img.Width / 2, img.Height / 2);

                                    //Bitmap originBmp = new Bitmap(img);

                                    GHFile.OriginThumbnailBitmap = img;

                                    //缩略图
                                    //img = ThumbnailHelper.GetThumbnail(img, img.Width / 2, img.Height / 2);
                                    Bitmap bmp = new Bitmap(img);
                                    GHFile.ThumbnailBitmap = bmp;
                                }
                                

                                list.Add(GHFile);

                                log.Info("转换图片结束");
                                log.Info("图片处理");

                            }
                            //else if (ThumbnailHelper.IsVideo(file.fileName))
                            //{
                            //    GHFile.Name = file.fileName;
                            //    GHFile.Path = file.smallIconUrl;
                            //    GHFile.FileType = ResourceFileType.VIDEO;
                            //    GHFile.Date = Convert.ToDateTime(file.fileUpdateTime).ToString("yyyy/MM/dd HH:mm");
                            //    GHFile.FileSize = file.fileSize;
                            //    string strVedioPath = string.Format("{0}{1}", System.Environment.CurrentDirectory, "\\Resources\\Vedio.jpeg");
                            //    Image vedioImage = Image.FromFile(strVedioPath);
                            //    vedioImage = ThumbnailHelper.GetThumbnail(vedioImage, vedioImage.Width / 2, vedioImage.Height / 2);
                            //    Bitmap vedioBtm = new Bitmap(vedioImage);
                            //    GHFile.ThumbnailBitmap = vedioBtm;
                            //    GHFile.FileType = ResourceFileType.VIDEO;
                            //    list.Add(GHFile);
                            //}
                            i++;
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex.Message);
                        }

                        //});
                    }

                    folder.Files = list.ToObservableCollection();

                    this.Support.FileModels = folder.Files;

                    log.Info("总的结束");
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
            });
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="oldPath"></param>
        /// <param name="newPath"></param>
        public async Task<fileListResult> MoveFile(string oldPath, string newPath)
        {
            string header = string.Format("{0}MoveFile?oldFile={1}&newFile={2}", ApplicationDomainEx.MediaConfig.Url, oldPath, newPath);
            var result = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(header, "");
            return result;
        }

        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="path"></param>
        public async Task<fileListResult> CreateFolder(string path)
        {
            string header = string.Format("{0}CreateFiles?filePath={1}", ApplicationDomainEx.MediaConfig.Url, path);
            var result = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(header, "");
            return result;
        }


        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path"></param>
        public async Task<fileListResult> DeleteFolder(string path)
        {
            string header = string.Format("{0}DeleteFiles?filePath={1}", ApplicationDomainEx.MediaConfig.Url, path);
            var result = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(header, "");
            return result;
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task<fileUploadResult> CreateFile(string filePath, string fileName)
        {
            string requestUri = string.Format("{0}UplodFile?filePath={1}", ApplicationDomainEx.MediaConfig.Url, this.Support.SelectedFolderModel.Path + "\\");

            fileUploadResult upLoadResult = await MediaResourceFileService.PostImage<fileUploadResult>(requestUri, filePath, fileName);

            if (upLoadResult == null)
                return null;

            return upLoadResult;

        }


        /// <summary>
        /// 创建截图文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task<fileUploadResult> CreateCutImageFile(Bitmap bitmap, string fileName)
        {

            string requestUri = string.Format("{0}UplodFile?filePath={1}&isResize=false", ApplicationDomainEx.MediaConfig.Url, this.Support.SelectedFolderModel.Path + "\\");

            fileUploadResult upLoadResult = await MediaResourceFileService.PostCutImage<fileUploadResult>(requestUri, bitmap, fileName);

            if (upLoadResult == null)
                return null;

            return upLoadResult;

        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        public async Task<fileListResult> DeleteFile(string path)
        {
            try
            {
                string header = string.Format("{0}DeleteFile?filePath={1}", ApplicationDomainEx.MediaConfig.Url, path);
                var result = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(header, "");
                return result;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return null;
            }

        }


        /// <summary>
        ///获取文件夹
        /// </summary>
        /// <returns></returns>

        public async Task<List<MHResourceFolderModel>> GetMeiaResourceFolder()
        {
            //  var config = 

            var folderResult = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(string.Format("{0}GetListFiles", ApplicationDomainEx.MediaConfig.Url), "");
            if (folderResult == null)
                return null;
            RootPath = folderResult.rootPath;


            return GetFolder(folderResult.masterData);
        }


        /// <summary>
        /// 获取回收站的文件
        /// </summary>
        public void GetMeiaResourceRecycleFile()
        {

            WPFHelper.BeginInvoke(async () =>
            {
                try
                {
                    var recycelFiles = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(string.Format("{0}GetDeleteListFiles", ApplicationDomainEx.MediaConfig.Url), "");

                    if (recycelFiles == null) return;

                    List<MHResourceFileModel> list = new List<MHResourceFileModel>();
                    foreach (var tempreycyleFile in recycelFiles.masterData)
                    {
                        MHResourceFileModel GHFile = new MHResourceFileModel();

                        GHFile.Name = tempreycyleFile.fileName;
                        GHFile.Path = tempreycyleFile.smallIconUrl;
                        GHFile.FileFolder = tempreycyleFile.fileType;
                       // GHFile.FileType = tempreycyleFile.fileType;
                        GHFile.Date = Convert.ToDateTime(tempreycyleFile.fileUpdateTime).ToString("yyyy/MM/dd HH:mm");
                        GHFile.FileSize = tempreycyleFile.fileSize;

                        list.Add(GHFile);


                    }

                    this.Support.FileRecycleModels = list.ToObservableCollection();
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
            });

        }

        // RestoreFile

        /// <summary>
        /// 还原文件
        /// </summary>
        public async Task<fileListResult> ReStoreRecycFile(string fileName)
        {
            try
            {
                string header = string.Format("{0}RestoreFile?fileName={1}", ApplicationDomainEx.MediaConfig.Url, fileName);
                var result = await MediaResourceFileService.PostObjectAsync<fileListResult, string>(header, "");
                return result;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获取文件夹
        /// </summary>
        /// <param name="foldersDatas"></param>
        /// <returns></returns>
        private List<MHResourceFolderModel> GetFolder(List<ms> foldersDatas)
        {
            List<MHResourceFolderModel> listFolderModel = new List<MHResourceFolderModel>();

            foreach (var floderData in foldersDatas)
            {
                if (floderData.fileType == "floder")
                {
                    MHResourceFolderModel child = new MHResourceFolderModel();
                    child.Name = floderData.fileName;
                    child.FolderType = ResourceFolderType.Folder;
                    child.Path = floderData.smallIconUrl;

                    List<MHResourceFolderModel> children_list = GetFolder(floderData.m);

                    foreach (MHResourceFolderModel item in children_list)
                    {

                        child.Children.Add(item);
                        item.Parent = child;
                    }

                    listFolderModel.Add(child);
                }

            }

            return listFolderModel;
        }

        /// <summary>
        /// 销毁文件模型
        /// </summary>
        public void DisposeFileModels(MHResourceFolderModel folder)
        {
            if (folder == null || folder.Files == null || folder.Files.Count == 0)
                return;

            foreach (MHResourceFileModel file in folder.Files)
            {
                file.Dispose();
            }
        }
    }
}
