using Common.system;

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

using XHWK.Model;
using XHWK.WKTool.DAL;

namespace XHWK.WKTool.UControl
{
    /// <summary>
    /// 视频信息
    /// </summary>
    public partial class Uc_VideoItem : UserControl
    {
        #region 初始值

        /// <summary>
        /// 视频模型
        /// </summary>
        private Model_Video VideoModel = new Model_Video();

        /// <summary>
        /// 刷新视频列表
        /// </summary>
        public delegate void RefreshVideoList();

        /// <summary>
        /// 刷新视频列表事件
        /// </summary>
        public event RefreshVideoList Click_refreshVideoList;

        /// <summary>
        /// 登录
        /// </summary>
        public delegate void UploadLogin();

        /// <summary>
        /// 登录事件
        /// </summary>
        public event UploadLogin Click_UploadLogin;

        /// <summary>
        /// 上传页面
        /// </summary>
        private UploadWindow W_UploadWindow = null;

        #endregion 初始值

        #region 初始化

        /// <summary>
        /// 视频信息
        /// </summary>
        /// <param name="model_Video"></param>
        public Uc_VideoItem(Model_Video model_Video)
        {
            InitializeComponent();
            App.IsUpLoad = false;
            VideoModel = model_Video;
            DataContext = App.PageContextData;
            if (FileToolsCommon.IsExistFile(VideoModel.ThumbnailPath))
            {
                ImgVideo.Source = ImageHelper.ReadBitmapImageFile(VideoModel.ThumbnailPath);// new BitmapImage(new Uri(VideoModel.ThumbnailPath));
            }
            string videoName = FileToolsCommon.GetIOFileNameNoExtension(VideoModel.VideoPath);
            TbName.Text = videoName.Length > 11 ? videoName.Substring(0, 11) + "..." : videoName;
            TbName.ToolTip = videoName;
            lblDateSize.Content = VideoModel.RSTime + " " + VideoModel.VideoSize;
            if (VideoModel.IsUpload)
            {
                BtnUpload.Visibility = Visibility.Hidden;
            }
        }

        #endregion 初始化

        #region 修改视频名

        /// <summary>
        /// 双击修改视频名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                TxtModify.Text = TbName.ToolTip.ToString();
                TbName.Visibility = Visibility.Hidden;
                GridModify.Visibility = Visibility.Visible;
                //BtnNameModifyOK.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// 失去焦点保存视频名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtModify_LostFocus(object sender, RoutedEventArgs e)
        {
            ModifyVideoName();
        }

        /// <summary>
        /// Enter保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtModify_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                ModifyVideoName();
            }
        }

        /// <summary>
        /// 修改文件名保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNameModifyOK_Click(object sender, RoutedEventArgs e)
        {
            ModifyVideoName();
        }

        /// <summary>
        /// 修改视频文件名
        /// </summary>
        private void ModifyVideoName()
        {
            if (TxtModify.Text != TbName.Text)
            {
                if (ModifyPathName(VideoModel.FileGuid, TxtModify.Text + "." + VideoModel.VideoType, out string ErrMessage))
                {
                    //保存成功
                    TbName.Text = TxtModify.Text.Length > 11 ? TxtModify.Text.Substring(0, 11) + "..." : TxtModify.Text;
                    TbName.ToolTip = TxtModify.Text;
                    TbName.Visibility = Visibility.Visible;
                    GridModify.Visibility = Visibility.Hidden;
                    //BtnNameModifyOK.Visibility = Visibility.Hidden;
                }
                else
                {
                    MessageWindow.Show(ErrMessage);
                }
            }
            else
            {
                TbName.Visibility = Visibility.Visible;
                GridModify.Visibility = Visibility.Hidden;
                //BtnNameModifyOK.Visibility = Visibility.Hidden;
            }
        }

        /// <summary>
        /// 修改视频文件名
        /// </summary>
        /// <param name="Guid">唯一编号</param>
        /// <param name="NewName">新文件名带后缀 不带路径</param>
        /// <param name="Errmessage">错误信息</param>
        /// <returns></returns>
        private bool ModifyPathName(string FileGuid, string NewName, out string Errmessage)
        {
            Errmessage = "";
            foreach (Model_WKData WKData in App.WKDataList)
            {
                if (WKData.VideoList.Exists(x => x.FileGuid == FileGuid))
                {
                    Model_Video model_Video = WKData.VideoList.Find(x => x.FileGuid == FileGuid);
                    string filePathName = model_Video.VideoPath;
                    string filePath = FileToolsCommon.GetDirectoryName(filePathName);
                    string newFilePathName = filePath + NewName;
                    //缩略图
                    string ThumbnailPath = filePath + "ThumbnailPath/";
                    FileToolsCommon.CreateDirectory(ThumbnailPath);
                    //缩略图存储位置
                    string ThumbnailPathName = ThumbnailPath + NewName.Replace(".", "") + ".JPG";
                    if (FileToolsCommon.IsExistFile(newFilePathName))
                    {
                        Errmessage = "文件已存在，请重新修改文件名！";
                        return false;
                    }
                    else
                    {
                        //修改文件名
                        FileToolsCommon.Copy(filePathName, newFilePathName);
                        model_Video.VideoPath = newFilePathName;
                        //修改缩略图名
                        FileToolsCommon.DeleteFile(ThumbnailPathName);
                        FileToolsCommon.Copy(model_Video.ThumbnailPath, ThumbnailPathName);
                        model_Video.ThumbnailPath = ThumbnailPathName;
                        App.SaveWkData();
                        return true;
                    }
                }
                else
                {
                    continue;
                }
            }
            Errmessage = "视频文件有改动，当前文件不存在，请关闭后重新打开“我的”";
            return false;
        }

        #endregion 修改视频名

        #region 删除视频

        /// <summary>
        /// 删除视频
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDelVideo_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult dr = MessageWindow.Show("确定删除该视频？", "提示", MessageBoxButton.OKCancel);
            if (dr == MessageBoxResult.OK)
            {
                foreach (Model_WKData wKData in App.WKDataList)
                {
                    if (wKData.VideoList == null)
                    {
                        continue;
                    }
                    if (wKData.VideoList.Exists(x => x.FileGuid == VideoModel.FileGuid))
                    {
                        try
                        {
                            FileToolsCommon.DeleteFile(wKData.VideoList.Find(x => x.FileGuid == VideoModel.FileGuid).VideoPath);
                            string ThumbnailPath = wKData.VideoList.Find(x => x.FileGuid == VideoModel.FileGuid).ThumbnailPath;
                            wKData.VideoList.Remove(wKData.VideoList.Find(x => x.FileGuid == VideoModel.FileGuid));
                            //初始化页面  刷新视频列表
                            Click_refreshVideoList();
                            ImgVideo.Source = null;
                            GC.Collect();
                            FileToolsCommon.DeleteFile(ThumbnailPath);
                            Visibility = Visibility.Hidden;
                            return;
                        }
                        catch (Exception ex)
                        {
                            MessageWindow.Show("无法删除视频！" + ex.Message);
                            return;
                        }
                    }
                }
            }
        }

        #endregion 删除视频

        #region 播放视频

        private void BtnVideoPlay_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo(VideoModel.VideoPath);
                Process pro = new Process
                {
                    StartInfo = psi
                };
                pro.Start();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("【视频播放】(BtnVideoPlay_Click)" + ex.Message, ex);
                System.Windows.MessageBox.Show(ex.Message);
                return;
            }
        }

        /// <summary>
        /// 视频播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo(VideoModel.VideoPath);
                Process pro = new Process
                {
                    StartInfo = psi
                };
                pro.Start();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("【视频播放】(BtnVideoPlay_Click)" + ex.Message, ex);
                System.Windows.MessageBox.Show(ex.Message);
                return;
            }
        }

        #endregion 播放视频

        /// <summary>
        /// 视频上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpload_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsLoginType == false)
            {
                //登录
                Click_UploadLogin();
                if (App.IsLoginType == false)
                {
                    return;
                }
            }
            if (!App.IsUpLoad)
            {
                App.IsUpLoad = true;
                //BtnUpload.IsEnabled = false;
                //BtnUpload.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#9EA0A7"));
                //BtnUpload.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#999999"));
                DalUpload dAL_Upload = new DalUpload();
                if (dAL_Upload.UploadVideo(VideoModel.FileGuid, out string ErrMessage))
                {
                    App.IsUpLoad = false;
                    //MessageWindow.Show("视频上传服务器成功！");
                    if (W_UploadWindow == null)
                    {
                        W_UploadWindow = new UploadWindow { Owner = App.W_XHMicroLessonSystemWindow };
                        W_UploadWindow.ChangeTextEvents += frm_ChangeTextEvents;
                        ;
                    }

                    //long size = Convert.ToInt64(FileToolsCommon.GetFileSizeByMB(pageData.menuList[i].FilePath));
                    W_UploadWindow.Initialize
                    (
                        TbName.Text,
                        VideoModel.VideoSizebyte,
                        VideoModel.VideoType.ToString(),
                        VideoModel.FileGuid,
                        0
                    );
                }
                else
                {
                    App.IsUpLoad = false;
                    MessageWindow.Show(ErrMessage);
                }
            }
        }

        /// <summary>
        /// 上传返回事件
        /// </summary>
        /// <param name="text"></param>
        private void frm_ChangeTextEvents(string text, int i)
        {
            if ("上传成功".Equals(text))
            {
                W_UploadWindow.Close();
                //BorUploadBtn.Visibility = Visibility.Hidden;
                BtnUpload.IsEnabled = false;
                BtnUpload.Background.Opacity = 0.6;
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (App.W_VideoClipWindow == null)
            {
                App.W_VideoClipWindow = new VideoClipWindow();
            }
            if (App.W_VideoClipWindow.InitClipVideo(VideoModel.VideoPath))
            {
                App.W_VideoClipWindow.ShowDialog();
            }
        }
    }
}
