using Common.system;

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;

using XHWK.Model;

namespace XHWK.WKTool
{
    /// <summary>
    /// 创建微课
    /// </summary>
    public partial class CreateAMicroLessonWindow
    {
        #region 字段

        private FolderBrowserDialog _ofd;
        private DialogResult _result;

        #endregion 字段

        /// <summary>
        /// 创建微课
        /// </summary>
        public CreateAMicroLessonWindow()
        {
            InitializeComponent();
            ResizeMode = ResizeMode.NoResize;

            txbStoragePath.Text = FileToolsCommon.GetConfigValue("VideoSavePath");

            var versionCode = FileToolsCommon.GetConfigValue("VersionCode");
            var versionName = FileToolsCommon.GetConfigValue("VersionName");
            var isDebug = FileToolsCommon.GetConfigValue("IsDebug");
            var debugStr = "测试版";
            if (isDebug == "1")
            {
                debugStr = "测试版";
            }
            else if (isDebug == "0")
            {
                debugStr = "正式版";
            }

            versionLabel.Content = debugStr + " v" + versionName + "(" + versionCode + ")";

            LoadingCarouseImg();
        }

        #region 轮播图

        /// <summary>
        /// 图片宽度，每次切换的宽度
        /// </summary>
        private double _imgWidth = 502.00;

        /// <summary>
        /// 轮播时移动增加的宽度
        /// </summary>
        private double _imgMove = 1;

        /// <summary>
        /// 当前展示的图片序号Index从0开始
        /// </summary>
        private int _imgNumIndex;

        /// <summary>
        /// 加载录播图
        /// </summary>
        private void LoadingCarouseImg()
        {
            new Thread(() =>
            {
                Thread.Sleep(3000);
                Dispatcher.Invoke(() =>
                {
                    _imgWidth = ImgCarouse1.ActualWidth;
                    _imgMove = _imgWidth / 250.00;
                    CarouseImg();
                    //timesCarouse = new System.Timers.Timer(2000);
                    //timesCarouse.Elapsed += TimesCarouse_Elapsed; ;
                    //timesCarouse.Start();
                });
            }).Start();
        }

        /// <summary>
        /// 轮播图
        /// </summary>
        private void CarouseImg()
        {
            new Thread(() =>
            {
                while (true)
                {
                    for (double i = _imgMove; i < _imgWidth; i += _imgMove)
                    {
                        var i1 = i;
                        Dispatcher.Invoke(() =>
                        {
                            if (Math.Abs(
                                    i1 + _imgMove) < _imgWidth)
                            {
                                //图片移动轮播
                                SplCarouse.Margin = new Thickness(SplCarouse.Margin.Left - _imgMove, 0, 0, 0);
                            }
                            else
                            {
                                if (_imgNumIndex >= 2)
                                {
                                    _imgNumIndex = 0;
                                    SplCarouse.Margin = new Thickness(0, 0, 0, 0);
                                }
                                else
                                {
                                    _imgNumIndex++;
                                    SplCarouse.Margin = new Thickness(-(_imgNumIndex * _imgWidth), 0, 0, 0);
                                }
                            }
                        });
                        Thread.Sleep(3);
                    }

                    bool isBreak = false;
                    Dispatcher.Invoke(() =>
                    {
                        if (this.Visibility != Visibility.Visible)
                        {
                            SplCarouse.Margin = new Thickness(0);
                            isBreak = true;
                        }
                    });
                    Thread.Sleep(5000);
                    if (isBreak)
                    {
                        break;
                    }
                }
            }).Start();
        }

        #endregion 轮播图

        #region 事件

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="e">
        /// </param>
        private void BtnDown_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult dr = MessageWindow.Show("确定退出系统？", "提示", MessageBoxButton.OKCancel);
            if (dr == MessageBoxResult.OK)
            {
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// 浏览
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="e">
        /// </param>
        private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            _ofd = new FolderBrowserDialog();

            _result = _ofd.ShowDialog();
            if (_result == System.Windows.Forms.DialogResult.OK)
            {
                if (_ofd.SelectedPath != "")
                {
                    txbStoragePath.Text = _ofd.SelectedPath;
                }
            }
        }

        private bool _isPressButton;

        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="e">
        /// </param>
        private async void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            #region 防止连击

            if (_isPressButton)
            {
                return;
            }
            else
            {
                _isPressButton = true;
                new Thread(() =>
                {
                    Thread.Sleep(500);
                    _isPressButton = false;
                }).Start();
            }

            #endregion 防止连击

            #region 合法性判断

            if (string.IsNullOrWhiteSpace(txbExplainName.Text.Trim()))
            {
                MessageWindow.Show("讲解名称不可为空！");
                return;
            }

            if (string.IsNullOrWhiteSpace(txbStoragePath.Text.Trim()))
            {
                MessageWindow.Show("路径不可为空！");
                return;
            }

            try
            {
                FileToolsCommon.CreateDirectory(txbStoragePath.Text.Trim());
            }
            catch (Exception)
            {
                MessageWindow.Show("路径无法访问，解决方案：\r\n1,检查路径是否可访问。\r\n2,关闭杀毒软件或信任软件。");
                return;
            }

            #endregion 合法性判断

            LblCreate.Visibility = Visibility.Visible;
            string wkpath = FileToolsCommon.GetLegalPath(txbStoragePath.Text) + txbExplainName.Text.Trim() + "/";
            string storagePath = txbStoragePath.Text;
            string wkName = txbExplainName.Text;
            await Task.Run(() =>
            {
                try
                {
                    //读取微课数据
                    App.ReadWkData(wkpath);
                    if (App.WKData == null)
                    {
                        App.WKData = new Model_WKData
                        {
                            WkPath = wkpath,
                            WkName = wkName,
                            WkCreateDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        };
                    }

                    try
                    {
                        //创建文件夹
                        FileToolsCommon.CreateDirectory(App.WKData.WkPath);
                        FileToolsCommon.DeleteDirectory(wkpath + "temp");
                        FileToolsCommon.DeleteDirectory(wkpath + "_temppath");
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrLog("【微课创建课程】文件夹创建删除失败：" + ex.Message, ex);
                    }

                    //存储文件
                    FileToolsCommon.SetConfigValue("VideoSavePath", storagePath);
                    App.ReadDrawData();
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrLog("【微课创建课程】读取课堂数据失败：" + ex.Message, ex);
                }
            });
            if (App.W_XHMicroLessonSystemWindow == null)
            {
                App.W_XHMicroLessonSystemWindow = new MainWindow();
            }
            App.W_XHMicroLessonSystemWindow.Show();
            LblCreate.Visibility = Visibility.Hidden;
            Hide();
        }

        /// <summary>
        /// 窗体移动
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="e">
        /// </param>
        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        #endregion 事件

        /// <summary>
        /// 检测APP更新
        /// </summary>
        private void GetNewApp()
        {
            new Thread(o =>
            {
                //读取本地
                App.ReadServiceAddressData();
                int versionThis = int.Parse(FileToolsCommon.GetConfigValue("VersionCode"));
                if (versionThis < 0)
                {
                    //软件是否更新，版本号小于0不更新
                    return;
                }
                string url = App.apiUrl + "/sapi/apprecord/get_new";
                string result = HttpHelper.PostAndRespStr(url, "{}");
                var resultObj = JsonHelper.JsonToObj<ResultVo<Model_App>>(result);
                if (result != null && resultObj.code == 0)
                {
                    if (resultObj.obj != null)
                    {
                        try
                        {
                            int versionCode = resultObj.obj.versioncode;
                            if (versionThis < versionCode)
                            {
                                Dispatcher.Invoke(() =>
                                {
                                    string pathTemp = AppDomain.CurrentDomain.BaseDirectory + "Temp\\";
                                    FileToolsCommon.CreateDirectory(pathTemp);
                                    AppUpdateShow(resultObj.obj);
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteErrLog("【检查更新】（getNewApp）版本号错误：" + ex.Message, ex);
                        }
                    }
                }
            }).Start();
        }

        /// <summary>
        /// 应用更新
        /// </summary>
        /// <param name="app">
        /// </param>
        private void AppUpdateShow(Model_App app)
        {
            AppUpdateWin win = new AppUpdateWin(app)
            {
                Topmost = true,
                Owner = this
            };
            win.Show();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            GetNewApp();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }
    }
}
