using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.Mvvm.Xpf;
using DevExpress.Xpf.Core;
using log4net;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Shapes;
using VIZ.Framework.Core;
using VIZ.Package.Domain;
using VIZ.Package.Service;
using VIZ.Package.Storage;
using static System.Net.WebRequestMethods;


namespace VIZ.Package.Module
{
    public class MediaResourcePanelViewModel : ViewModelBase, IMediaResourceFileSupport
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(typeof(MediaResourceViewModel));

        /// <summary>
        /// 操作日志服务
        /// </summary>
        private RecordLogService recordLogService = new RecordLogService();

        public MediaResourcePanelViewModel()
        {
            // 初始化控制器
            this.initController();

            // 初始化命令
            this.initCommand();
        }

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void initCommand()
        {
            this.LoadedCommand = new VCommand(this.Loaded);


            this.RefreshFolderCommand = new VCommand(this.RefreshFolder);
            this.RefreshFileCommand = new VCommand(this.RefreshFile);

            this.CreateFloderCommand = new VCommand(this.CreateFloder);
            this.DeleteFloderCommand = new VCommand(this.DeleteFloder);
            this.CreateFileCommand = new VCommand(this.CreateFile);
            this.DeleteFileCommand = new VCommand(this.DeleteFile);
            this.MoveFileCommand = new VCommand(this.MoveFile);
            this.MoveFloderCommand = new VCommand(this.MoveFileFloder);
            this.ExportFileCommand = new VCommand(this.ExprotFile);
            this.ExportFolderFilesCommand = new VCommand(this.ExportFolderFiles);
            this.FilesListCommand = new VCommand(this.FilesList);


            this.ShowImageListCommand = new VCommand(this.ShowImageList);
            this.SortFileNameCommand = new VCommand(this.SortFileName);
            this.SortDateCommand = new VCommand(this.SortDate);

            this.FolderExpandCommand = new VCommand<DevExpress.Xpf.Grid.TreeList.NodeDoubleClickEventArgs>(this.FolderExpand);
            this.FileFilterCommand = new VCommand<ResourceFileType>(this.FileFilter);
            this.FileRowFilterCommand = new DevExpress.Mvvm.DelegateCommand<RowFilterArgs>(this.FileRowFilter);
            this.FileDoubleClickCommand = new VCommand(this.FileDoubleClick);
            this.EditImageCommand = new VCommand(this.EditImage);
            this.ShowImageCommand = new VCommand(this.ShowImage);
            //this.FileContextMenuOpendCommand = new VCommand(this.FileContextMenuOpend);
            //this.AddProgramTemplateCommand = new VCommand(this.AddProgramTemplate, this.CanAddProgramTemplate);
            // this.CopyFilePathCommand = new VCommand(this.CopyFilePath, this.CanCopyFilePath);

            this.RefresRecyclehFileCommand = new VCommand(this.RefresRecyclehFile);
            this.RecyclehFileCommand = new VCommand(this.RecyclehFile);

        }

        /// <summary>
        /// 初始化控制器
        /// </summary>
        private void initController()
        {
            this.mediaResourceFileController = new MediaResourceFileController(this);
        }

        // ==================================================================================
        // Property
        // ==================================================================================

        #region FolderModels -- 文件夹目录集合

        private ObservableCollection<MHResourceFolderModel> folderModels;
        /// <summary>
        /// 文件夹目录集合
        /// </summary>
        public ObservableCollection<MHResourceFolderModel> FolderModels
        {
            get { return folderModels; }
            set { folderModels = value; this.RaisePropertyChanged(nameof(FolderModels)); }
        }

        #endregion

        #region SelectedFolderModel -- 当前选中的文件夹

        private MHResourceFolderModel selectedFolderModel;
        /// <summary>
        /// 当前选中的文件夹
        /// </summary>
        public MHResourceFolderModel SelectedFolderModel
        {
            get { return selectedFolderModel; }
            set
            {
                selectedFolderModel = value;
                this.RaisePropertyChanged(nameof(SelectedFolderModel));
                // 更新文件模型
                this.mediaResourceFileController.UpdateFileModels(value);
            }
        }

        #endregion

        #region FileModels -- 文件集合

        private ObservableCollection<MHResourceFileModel> fileModels;
        /// <summary>
        /// 文件集合
        /// </summary>
        public ObservableCollection<MHResourceFileModel> FileModels
        {
            get { return fileModels; }
            set { fileModels = value; this.RaisePropertyChanged(nameof(FileModels)); }
        }

        #endregion

        #region SelectedFileModel -- 选中的文件模型

        private MHResourceFileModel selectedFileModel;
        /// <summary>
        /// 选中的文件模型
        /// </summary>
        public MHResourceFileModel SelectedFileModel
        {
            get { return selectedFileModel; }
            set
            {
                selectedFileModel = value;
                this.RaisePropertyChanged(nameof(SelectedFileModel));
                this.OnSelectedFileModelChanged?.Invoke(this, new MHResourceSelectedFileChangedEventArgs { File = value });
            }
        }

        #endregion


        #region 回收文件


        private ObservableCollection<MHResourceFileModel> fileRecycleModels;
        /// <summary>
        /// 回收文件集合
        /// </summary>
        public ObservableCollection<MHResourceFileModel> FileRecycleModels
        {
            get { return fileRecycleModels; }
            set { fileRecycleModels = value; this.RaisePropertyChanged(nameof(FileRecycleModels)); }
        }



        private MHResourceFileModel selectedfileRecycleFileModel;
        /// <summary>
        /// 选中的文件模型
        /// </summary>
        public MHResourceFileModel SelectedfileRecycleFileModel
        {
            get { return selectedfileRecycleFileModel; }
            set
            {
                selectedfileRecycleFileModel = value;
                this.RaisePropertyChanged(nameof(SelectedfileRecycleFileModel));

            }
        }


        #endregion

        #region IsFolderLoading -- 是否正在加载文件夹

        private bool isFolderLoading;
        /// <summary>
        /// 是否正在加载文件夹
        /// </summary>
        public bool IsFolderLoading
        {
            get { return isFolderLoading; }
            set { isFolderLoading = value; this.RaisePropertyChanged(nameof(IsFolderLoading)); }
        }

        #endregion

        #region IsFileLoading -- 是否正在加载文件

        private bool isFileLoading;
        /// <summary>
        /// 是否正在加载文件
        /// </summary>
        public bool IsFileLoading
        {
            get { return isFileLoading; }
            set { isFileLoading = value; this.RaisePropertyChanged(nameof(IsFileLoading)); }
        }

        #endregion

        #region FilterResourceFileType -- 资源文件类型

        private ResourceFileType filterResourceFileType;
        /// <summary>
        /// 资源文件类型
        /// </summary>
        public ResourceFileType FilterResourceFileType
        {
            get { return filterResourceFileType; }
            set { filterResourceFileType = value; this.RaisePropertySaveChanged(nameof(FilterResourceFileType)); }
        }

        #endregion

        // ==================================================================================
        // Service & Controller
        // ==================================================================================

        /// <summary>
        /// GH 资源服务
        /// </summary>
        //private IGHResourceService ghResourceService = new GHResourceService();

        /// <summary>
        /// VIZ资源文件控制器
        /// </summary>
        private MediaResourceFileController mediaResourceFileController;

        // ==================================================================================
        // Command
        // ==================================================================================

        #region LoadedCommand -- 加载命令

        /// <summary>
        /// 加载命令
        /// </summary>
        public VCommand LoadedCommand { get; set; }

        /// <summary>
        /// 加载
        /// </summary>
        private void Loaded()
        {
            if (this.IsAlreadyLoaded)
                return;

            this.IsFolderLoading = true;

            // 刷新文件夹
            this.RefreshFolder();

            this.IsAlreadyLoaded = true;

            mediaResourceFileController.GetMeiaResourceRecycleFile();
        }

        #endregion


        /// <summary>
        /// 选择文件改变时触发
        /// </summary>
        public event EventHandler<MHResourceSelectedFileChangedEventArgs> OnSelectedFileModelChanged;

        /// <summary>
        /// 文件双击时触发
        /// </summary>
        public event EventHandler<MHResourceFileDoubleClickEventArgs> OnFileDoubleClick;

        #region FileDoubleClickCommand -- 文件双击命令

        /// <summary>
        /// 文件双击命令
        /// </summary>
        public VCommand FileDoubleClickCommand { get; set; }

        /// <summary>
        /// 文件双击
        /// </summary>
        private void FileDoubleClick()
        {
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_DOUBLECLICK);

            this.OnFileDoubleClick?.Invoke(this, new MHResourceFileDoubleClickEventArgs { File = this.SelectedFileModel });
        }

        #endregion


        #region RefreshFolderCommand -- 刷新文件夹命令

        /// <summary>
        /// 刷新文件夹命令
        /// </summary>
        public VCommand RefreshFolderCommand { get; set; }

        /// <summary>
        /// 刷新文件夹
        /// </summary>
        private void RefreshFolder()
        {

            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FLODER_REFRESH);
            this.IsFolderLoading = false;



            Task.Run(async () =>
            {
                try
                {


                    List<MHResourceFolderModel> list = await this.mediaResourceFileController.GetMeiaResourceFolder();

                    if (list == null)
                    {
                        return;
                    }


                    this.FolderModels = list.ToObservableCollection();
                    this.IsFolderLoading = false;
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            });
        }

        #endregion

        #region RefreshFileCommand -- 刷新文件命令



        /// <summary>
        /// 刷新文件命令
        /// </summary>
        public VCommand RefreshFileCommand { get; set; }

        /// <summary>
        /// 刷新文件
        /// </summary>
        private void RefreshFile()
        {
            MHResourceFolderModel folder = this.SelectedFolderModel;

            if (folder == null)
                return;
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_REFRESH);
            this.mediaResourceFileController.DisposeFileModels(folder);
            folder.IsRefreshedFiles = false;
            this.mediaResourceFileController.UpdateFileModels(this.SelectedFolderModel);
        }

        #endregion


        #region 回收站可见性

        private Visibility visibilityReCycle = Visibility.Visible;

        public Visibility VisibilityReCycle
        {
            get { return visibilityReCycle; }
            set { visibilityReCycle = value; this.RaisePropertyChanged(nameof(VisibilityReCycle)); }
        }

        #endregion


        #region 文件列表
        private Visibility visibilityList = Visibility.Hidden;

        public Visibility VisibilityList
        {
            get { return visibilityList; }
            set { visibilityList = value; this.RaisePropertyChanged(nameof(VisibilityList)); }
        }
        #endregion


        #region 图片可见性

        private Visibility visibilityImage = Visibility.Visible;

        public Visibility VisibilityImage
        {
            get { return visibilityImage; }
            set { visibilityImage = value; this.RaisePropertyChanged(nameof(VisibilityImage)); }
        }



        #endregion
        #region 创建文件夹

        public VCommand CreateFloderCommand { get; set; }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        private async void CreateFloder()
        {

            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FLODER_CREATE);
            CreateFolderWindow floderView = new CreateFolderWindow();

            CreateFolderViewModel vm = floderView.createFolderView.DataContext as CreateFolderViewModel;

            floderView.ShowDialog();

            if (vm == null || !vm.IsEnter)
                return;

            if (this.FolderModels == null)
                return;
            string createPath = "";
            //创建根目录文件夹
            if (this.FolderModels.Count == 0)
            {
                createPath = string.Format("{0}\\{1}", this.mediaResourceFileController.RootPath, vm.FolderName);
                var result = await this.mediaResourceFileController.CreateFolder(createPath);
                if (result != null)
                {
                    if (result.status == "0")
                    {

                        this.folderModels.Add(new MHResourceFolderModel()
                        {
                            Name = vm.FolderName,
                            Path = createPath,
                            FolderType = ResourceFolderType.Folder
                        });
                    }
                    else
                    {
                        log.Error(result.message);
                    }

                }

            }
            else
            {
                createPath = string.Format("{0}\\{1}", selectedFolderModel.Path, vm.FolderName);
                var result = await this.mediaResourceFileController.CreateFolder(createPath);
                if (result != null)
                {
                    if (result.status == "0")
                    {
                        SelectedFolderModel.Children.Add(new MHResourceFolderModel()
                        {
                            Name = vm.FolderName,
                            Path = createPath,
                            FolderType = ResourceFolderType.Folder,
                            Parent = selectedFolderModel
                        });
                    }
                    else
                    {
                        log.Error(result.message);
                    }

                }
            }
        }

        #endregion

        #region 删除文件夹

        public VCommand DeleteFloderCommand { get; set; }

        private async void DeleteFloder()
        {
            if (selectedFolderModel != null)
            {

                //记录操作log日志
                this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FLODER_DELETE);
                if ((DialogResult)DXMessageBox.Show("是否此文件夹", "", MessageBoxButton.OKCancel) == DialogResult.OK)
                {
                    string path = SelectedFolderModel.Path;
                    var result = await this.mediaResourceFileController.DeleteFolder(path);

                    if (result != null)
                    {
                        if (SelectedFolderModel.Parent != null)
                        {
                            if (result.status == "0")
                            {
                                SelectedFolderModel.Parent.Children.Remove(SelectedFolderModel);
                            }
                            else
                            {
                                log.Error(result.message);
                            }
                        }
                        else
                        {
                            this.FolderModels.Remove(SelectedFolderModel);
                        }

                    }
                }
            }
        }
        #endregion

        #region 创建文件

        public VCommand CreateFileCommand { get; set; }

        /// <summary>
        /// 创建文件方法
        /// </summary>
        private async void CreateFile()
        {
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_CREATE);

            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();

            ofd.Filter = ApplicationDomainEx.MediaConfig.MediaFilter;
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] fileNames = ofd.FileNames;

                bool flag = false;
                foreach (var tempFileName in fileNames)
                {
                    string path = System.IO.Path.GetFullPath(tempFileName);
                    string fileName = ThumbnailHelper.GetFileFolderName(path);
                    try
                    {

                        var fileResult = await this.mediaResourceFileController.CreateFile(path, fileName);
                        if (fileResult != null && fileResult.errCode == "0")
                        {
                            flag = true;
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                    }
                    //if (fileResult != null && fileResult.errCode == "0")
                    //{
                    //try
                    //{
                    //    //MHResourceFileModel fileModel = new MHResourceFileModel();

                    //if (ThumbnailHelper.IsImageByName(fileName))
                    //{
                    //    Image image = ThumbnailHelper.GetImage(path, 100, 200);
                    //    Bitmap btm = new Bitmap(image);
                    //    fileModel.ThumbnailBitmap = btm;
                    //    fileModel.FileType = ResourceFileType.IMAGE;
                    //    fileModel.Name = fileName;
                    //    this.FileModels.Add(fileModel);
                    //}
                    //else if (ThumbnailHelper.IsVideo(fileName))
                    //{
                    //    string vedioImage = string.Format("{0}{1}", System.Environment.CurrentDirectory, "\\Resource\\VedioImage\\Vedio.jpeg");
                    //    Image image = ThumbnailHelper.GetImage(vedioImage, 100, 200);
                    //    Bitmap btm = new Bitmap(image);
                    //    fileModel.ThumbnailBitmap = btm;
                    //    fileModel.FileType = ResourceFileType.Video;
                    //    fileModel.Name = fileName;
                    //    this.FileModels.Add(fileModel);
                    //}

                    // }
                    //catch (Exception ex)
                    //{
                    //    log.Error(ex.Message);
                    //}
                    // }
                }

                if (flag)
                {
                    if (this.SelectedFolderModel != null)
                    {
                        this.mediaResourceFileController.UpdateFileModels(this.SelectedFolderModel);
                    }

                }

            }
        }
        #endregion 创建文件

        #region 删除文件

        public VCommand DeleteFileCommand { get; set; }

        private async void DeleteFile()
        {
            if (selectedFileModel == null) return;

            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_DELETE);

            if ((DialogResult)DXMessageBox.Show("是否删除此文件", "", MessageBoxButton.OKCancel) == DialogResult.OK)
            {

                var result = await this.mediaResourceFileController.DeleteFile(selectedFileModel.Path);
                if (result != null)
                {
                    if (result.status == "0")
                    {
                        this.FileModels.Remove(this.SelectedFileModel);
                    }
                    else
                    {
                        log.Error(result.message);
                    }
                }


            }
        }

        #endregion

        #region 移动文件

        public VCommand MoveFileCommand { get; set; }


        public string moveFilePath = "";
        public MHResourceFileModel moveFileModel = null;


        private void MoveFile()
        {
            if (selectedFileModel != null)
            {
                //记录操作log日志
                this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_MOVE);

                if ((DialogResult)DXMessageBox.Show("是否移动此文件", "", MessageBoxButton.OKCancel) == DialogResult.OK)
                {

                    moveFilePath = selectedFileModel.Path;
                    moveFileModel = selectedFileModel;
                }
            }

        }


        #region 查看文件列表
        public VCommand FilesListCommand { get; set; }


        private void FilesList()
        {
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_LIST);
            VisibilityImage = Visibility.Hidden;
            VisibilityList = Visibility.Visible;
        }

        #endregion


        #region 查看图片列表
        public VCommand ShowImageListCommand { get; set; }

        private void ShowImageList()
        {
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_IMAGELIST);
            VisibilityImage = Visibility.Visible;
            VisibilityList = Visibility.Hidden;
        }

        #endregion


        #region 文件列表按照文件名排序
        public VCommand SortFileNameCommand { get; set; }

        private void SortFileName()
        {
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_SORTNAME);
            this.FileModels = this.FileModels.OrderBy(a => a.Name).ToObservableCollection();
        }

        #endregion


        #region 文件列表按照日期排序
        public VCommand SortDateCommand { get; set; }

        private void SortDate()
        {
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_DATE);
            this.FileModels = this.FileModels.OrderBy(a => Convert.ToDateTime(a.Date)).ToObservableCollection();
        }

        #endregion





        /// <summary>
        /// 导出文件夹的素材
        /// </summary>
        public VCommand ExportFolderFilesCommand { get; set; }


        private async void ExportFolderFiles()
        {

            if (SelectedFolderModel == null || FileModels == null) return;

            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FLODER_EXPORT);

            try
            {
                System.Windows.Forms.FolderBrowserDialog ofd = new System.Windows.Forms.FolderBrowserDialog();
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string path = ofd.SelectedPath;
                    foreach (var fileModel in FileModels)
                    {

                        string url = string.Format("{0}GetFile?filePath={1}&isResize=false", ApplicationDomainEx.MediaConfig.Url, fileModel.Path);
                        var fileResult = await MediaResourceFileService.GetImage(url);



                        string filePath = String.Format("{0}\\{1}", path, fileModel.Name);


                        if (ThumbnailHelper.IsImageByName(fileModel.Name))
                        {

                            Image img = Image.FromStream(fileResult);
                            if (!System.IO.File.Exists(filePath))
                            {
                                img.Save(filePath);
                            }
                        }

                        else if (ThumbnailHelper.IsVideo(fileModel.Name))
                        {
                            if (!System.IO.File.Exists(filePath))
                            {
                                FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                                fileResult.WriteTo(file);
                                file.Close();
                                fileResult.Close();
                            }

                        }



                    }

                    DXMessageBox.Show("素材导出成功");

                }
            }

            catch (Exception ex)
            {
                DXMessageBox.Show("素材导出失败");
                log.Error(ex.Message);
            }

        }


        /// <summary>
        /// 导入文件素材
        /// </summary>


        public VCommand ExportFileCommand { get; set; }


        private async void ExprotFile()
        {



            if (SelectedFileModel == null) return;

            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_EXPORT);
            try
            {
                System.Windows.Forms.FolderBrowserDialog ofd = new System.Windows.Forms.FolderBrowserDialog();
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {



                    string path = ofd.SelectedPath;

                    string filePath = String.Format("{0}\\{1}", path, SelectedFileModel.Name);


                    string url = string.Format("{0}GetFile?filePath={1}&isResize=false", ApplicationDomainEx.MediaConfig.Url, SelectedFileModel.Path);

                    var fileResult = await MediaResourceFileService.GetImage(url);


                    if (ThumbnailHelper.IsImageByName(SelectedFileModel.Name))
                    {
                        Image img = Image.FromStream(fileResult);

                        if (!System.IO.File.Exists(filePath))
                        {
                            img.Save(filePath);
                        }
                    }

                    else if (ThumbnailHelper.IsVideo(SelectedFileModel.Name))
                    {
                        if (!System.IO.File.Exists(filePath))
                        {
                            FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                            fileResult.WriteTo(file);
                            file.Close();
                            fileResult.Close();
                        }

                    }

                    DXMessageBox.Show("素材导出成功");
                }
            }

            catch (Exception ex)
            {
                DXMessageBox.Show("素材导出失败");
                log.Error(ex.Message);
            }
        }

        public VCommand MoveFloderCommand { get; set; }

        /// <summary>
        /// 移动文件到文件夹
        /// </summary>

        private async void MoveFileFloder()
        {
            if (string.IsNullOrEmpty(moveFilePath))
            {

                // DXMessageBox.Show("请先选择移入的文件,在选择移动此文件夹","移入当前文件夹", MessageBoxButton.YesNo);
                DXMessageBox.Show("请先选择移入的文件,在选择移动此文件夹");
                // MessageBox.Show("请先选择移入的文件");
            }
            else
            {
                //记录操作log日志
                this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FLODER_MOVEFILE);
                var result = await this.mediaResourceFileController.MoveFile(moveFilePath, selectedFolderModel.Path);

                if (result != null)
                {
                    if (result.status == "0")
                    {
                        if (moveFileModel != null)
                        {
                            this.FileModels.Add(moveFileModel);
                        }
                    }
                    else
                    {
                        log.Error(result.message);
                    }
                }


            }
        }
        #endregion

        #region 编辑图片选项

        /// <summary>
        /// 编辑图片
        /// </summary>
        public VCommand EditImageCommand { get; set; }

        private async void EditImage()
        {

            try
            {


                if (selectedFileModel == null || selectedFileModel.ThumbnailBitmap == null||selectedFileModel.FileType==ResourceFileType.VIDEO) return;

                //记录操作log日志
                this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FILE_EDITIMAGE);
                ImageEditWindow imageEditWindow = new ImageEditWindow();

                ImageEditViewModel vm = imageEditWindow.ImageCut.DataContext as ImageEditViewModel;

                string url = string.Format("{0}GetFile?filePath={1}&isResize=false", ApplicationDomainEx.MediaConfig.Url, SelectedFileModel.Path);


                var imageResult = await MediaResourceFileService.GetImage(url);
                Image img = Image.FromStream(imageResult);
                Bitmap bmp = new Bitmap(img);

                vm.OriginImage = vm.BitmapToBitmapImage(bmp);

                imageEditWindow.ShowDialog();

                if (vm.IsEnter)
                {
                    string fileName = string.Format("{0}.png", GenerateStringID());

                    Bitmap bp = new Bitmap(vm.CutImage);

                    bool flag = false;
                    try
                    {

                        var fileResult = await this.mediaResourceFileController.CreateCutImageFile(bp, fileName);
                        if (fileResult != null && fileResult.errCode == "0")
                        {
                            flag = true;
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                    }

                    if (flag)
                    {
                        if (this.SelectedFolderModel != null)
                        {
                            this.mediaResourceFileController.UpdateFileModels(this.SelectedFolderModel);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }

        }

        /// <summary>
        /// 随机生成GuID字符串
        /// </summary>
        /// <returns></returns>
        private string GenerateStringID()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        #endregion


        #region 查看图片选项

        public VCommand ShowImageCommand { get; set; }

        private async void ShowImage()
        {

            try
            {

                if (selectedFileModel == null || selectedFileModel.ThumbnailBitmap == null||selectedFileModel.FileType==ResourceFileType.VIDEO) return;

                //记录操作log日志
                this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, "图片查看");
                ImageShowWindow imageShowWindow = new ImageShowWindow();

                ImageShowViewModel vm = imageShowWindow.DataContext as ImageShowViewModel;

                string url = string.Format("{0}GetFile?filePath={1}&isResize=false", ApplicationDomainEx.MediaConfig.Url, SelectedFileModel.Path);


                var imageResult = await MediaResourceFileService.GetImage(url);
                Image img = Image.FromStream(imageResult);
                //Bitmap bmp = new Bitmap(img);

             
                Bitmap bmp = new Bitmap(img);

        
                vm.ShowImage = vm.BitmapToBitmapImage(bmp); 

                imageShowWindow.ShowDialog();

            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }

        }

        #endregion


        #region 刷新回收站文件

        public VCommand RefresRecyclehFileCommand { get; set; }

        private void RefresRecyclehFile()
        {
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_RECYCLEH_REFRESH);
            this.mediaResourceFileController.GetMeiaResourceRecycleFile();
        }

        #endregion


        #region 还原文件

        public VCommand RecyclehFileCommand { get; set; }


        private async void RecyclehFile()
        {
            if (SelectedfileRecycleFileModel == null) return;

            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_RECYCLEH_FILE);

            var result = await this.mediaResourceFileController.ReStoreRecycFile(SelectedfileRecycleFileModel.Name);

            if (result.status == "0")
            {
                DXMessageBox.Show("文件还原成功！");
                RefreshFile();
                RefresRecyclehFile();

            }
            else
            {
                DXMessageBox.Show(String.Format("还原失败！{0}", result.message));
            }


        }

        #endregion

        #region FolderExpandCommand -- 文件夹展开命令

        /// <summary>
        /// 文件夹展开命令
        /// </summary>
        public VCommand<DevExpress.Xpf.Grid.TreeList.NodeDoubleClickEventArgs> FolderExpandCommand { get; set; }

        /// <summary>
        /// 文件夹展开
        /// </summary>
        private void FolderExpand(DevExpress.Xpf.Grid.TreeList.NodeDoubleClickEventArgs e)
        {
            if (this.SelectedFolderModel == null || e.ChangedButton != System.Windows.Input.MouseButton.Left)
                return;
            //记录操作log日志
            this.recordLogService.AppendLog(ApplicationConstants.APPLICATION_GROUP_NAME, RecordLogOperate.Operate, RecordLogTrigger.Human, RecordLogConstants.OPERATE_FLODER_EXPAND);

            this.SelectedFolderModel.IsExpand = !this.SelectedFolderModel.IsExpand;
        }

        #endregion

        #region FileFilterCommand -- 文件过滤命令

        /// <summary>
        /// 文件过滤命令
        /// </summary>
        public VCommand<ResourceFileType> FileFilterCommand { get; set; }

        /// <summary>
        /// 文件过滤
        /// </summary>
        /// <param name="type"></param>
        private void FileFilter(ResourceFileType type)
        {
            this.FilterResourceFileType = type;

            MediaResourcePanel view = this.GetView<MediaResourcePanel>();
            if (view == null)
                return;

            view.fileGrid.RefreshData();
        }

        #endregion

        #region FileContextMenuOpendCommand -- 文件右键菜单打开命令

        /// <summary>
        /// 文件右键菜单打开命令
        /// </summary>
        public VCommand FileContextMenuOpendCommand { get; set; }

        /// <summary>
        /// 文件右键菜单打开
        /// </summary>
        private void FileContextMenuOpend()
        {
            this.AddProgramTemplateCommand.RaiseCanExecute();
            this.CopyFilePathCommand.RaiseCanExecute();
        }

        #endregion

        #region AddProgramTemplateCommand -- 添加节目模板命令

        /// <summary>
        /// 添加节目模板命令
        /// </summary>
        public VCommand AddProgramTemplateCommand { get; set; }

        /// <summary>
        /// 是否可以执行添加节目模板
        /// </summary>
        /// <returns>是否可以执行添加节目模板</returns>
        private bool CanAddProgramTemplate()
        {
            return this.SelectedFileModel != null && this.SelectedFileModel.FileType == ResourceFileType.SCENE;
            //&& ApplicationDomainEx.CurrentProjectDomain != null;
        }

        /// <summary>
        /// 添加节目模板
        /// </summary>
        private void AddProgramTemplate()
        {
            if (this.SelectedFileModel == null || this.SelectedFileModel.FileType != ResourceFileType.SCENE)
                return;

            //IProgramListViewService service = ApplicationDomainEx.ServiceManager.GetService<IProgramListViewService>(ServiceKeys.PROGRAM_LIST_VIEW_SERVICE);
            //if (service == null)
            //    return;

            // service.AddSceneTemplate(this.SelectedFileModel);
        }

        #endregion

        #region FileRowFilterCommand -- 文件行筛选命令

        /// <summary>
        /// 文件行筛选命令, 该命令必须使用Dev的命令基类
        /// </summary>
        public DevExpress.Mvvm.DelegateCommand<RowFilterArgs> FileRowFilterCommand { get; set; }

        /// <summary>
        /// 文件行筛选
        /// </summary>
        /// <param name="e">赛选参数</param>
        private void FileRowFilter(RowFilterArgs e)
        {
            MHResourceFileModel fileModel = e.Item as MHResourceFileModel;
            if (fileModel == null)
            {
                e.Visible = false;
                return;
            }

            if (this.FilterResourceFileType == ResourceFileType.NONE)
            {
                e.Visible = true;
                return;
            }

            e.Visible = fileModel.FileType == this.FilterResourceFileType;
        }

        #endregion

        #region CopyFilePathCommand -- 拷贝文件路径命令

        /// <summary>
        /// 拷贝文件路径命令
        /// </summary>
        public VCommand CopyFilePathCommand { get; set; }

        /// <summary>
        /// 是否可以执行拷贝文件路径
        /// </summary>
        /// <returns>是否可以执行拷贝文件路径</returns>
        private bool CanCopyFilePath()
        {
            return this.SelectedFileModel != null;
        }

        /// <summary>
        /// 拷贝文件路径
        /// </summary>
        private void CopyFilePath()
        {
            if (this.SelectedFileModel == null)
                return;

            // Clipboard.SetText($"{this.SelectedFileModel.FileType}*{this.SelectedFileModel.Path}");
        }

        #endregion

        // ==================================================================================
        // Public Function
        // ==================================================================================

        /// <summary>
        /// 销毁
        /// </summary>
        //public override void Dispose()
        //{

        //}
    }
}
