using Common.system;

using System;
using System.Threading;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

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

using static XHWK.WKTool.MainWindow;

namespace XHWK.WKTool
{
    /// <summary>
    /// UploadWindow.xaml 的交互逻辑
    /// </summary>
    public partial class UploadWindow : Window
    {
        /// <summary>
        /// 调用接口
        /// </summary>
        private readonly XHApi xhapi = new XHApi();

        /// <summary>
        /// 前台数据
        /// </summary>
        internal LoginPageData pageData = new LoginPageData();

        /// <summary>
        /// 文件名
        /// </summary>
        private string Resourcename = string.Empty;

        /// <summary>
        /// 文件大小
        /// </summary>
        private long Resourcesize = 0;

        /// <summary>
        /// 文件类型
        /// </summary>
        private string Suffix = string.Empty;

        /// <summary>
        /// 唯一编号
        /// </summary>
        private string Guid = string.Empty;

        //定义事件
        public event ChangeTextHandlers ChangeTextEvents;

        /// <summary>
        /// 当前视频的下标
        /// </summary>
        private int i = 0;

        private System.Timers.Timer times;

        public UploadWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Initialize(string _resourcename, long _resourcesize, string _suffix, string _guid, int _i)
        {
            i = _i;
            Resourcename = _resourcename;
            Resourcesize = _resourcesize;
            Suffix = _suffix;
            Guid = _guid;
            tip_outer.Visibility = Visibility.Collapsed;
            Tsubjectbook();
        }

        /// <summary>
        /// 教材接口调用
        /// </summary>
        /// <returns>
        /// </returns>
        private void Tsubjectbook()
        {
            int code = xhapi.TsubjectbookList();
            if (code == 0)
            {
                for (int i = 0; i < App.TsubjectbookList.Count; i++)
                {
                    pageData.bookList.Add
                    (
                        new ComboBoxBean()
                        {
                            Key = App.TsubjectbookList[i].Lsbid,
                            //Value = $"{APP.TsubjectbookList[i].Subjectname}  {APP.TsubjectbookList[i].Bookname}"
                            Value = $"{App.TsubjectbookList[i].Subjectname}  {App.TsubjectbookList[i].Versionname}  {App.TsubjectbookList[i].Lsbname}"
                        }
                    );
                }
                book_list.SelectedIndex = 0;
                DataContext = pageData;
                if (App.TsubjectbookList.Count > 0)
                {
                    Director();
                    ShowDialog();
                }
                else
                {
                    App.IsUpLoad = false;
                    Hide();
                    MessageWindow.Show("暂无章节！");
                }
            }
            else
            {
                MessageWindow.Show(App.ServerMsg);
            }
        }

        /// <summary>
        /// 章节接口调用
        /// </summary>
        private void Director()
        {
            int selectIndex = book_list.SelectedIndex;
            if (selectIndex < 0)
            {
                selectIndex = 0;
            }
            if (App.TsubjectbookList.Count > selectIndex)
            {
                int code = xhapi.DirectorList
                (
                    App.TsubjectbookList[selectIndex].Lsbid,
                    4,
                    App.UserInfo.Userid
                );
                if (code == 0)
                {
                    pageData.zhangjieList.Clear();
                    pageData.zhangjieList.Add
                    (
                        new ComboBoxBean()
                        {
                            Key = "0",
                            Value = "全部",
                            leaf = 1
                        }
                    );
                    for (int i = 0; i < App.DirectorList.Count; i++)
                    {
                        Model_DirectorList item = App.DirectorList[i];
                        pageData.zhangjieList.Add
                        (
                            new ComboBoxBean()
                            {
                                Key = item.directorid,
                                Value = item.directorname,
                                leaf = item.leaf
                            }
                        );
                        addChild(item);
                    }
                    cmbTeachingMaterial.SelectedIndex = 0;
                }
                else
                {
                    MessageWindow.Show(App.ServerMsg);
                }
            }
        }

        /// <summary>
        /// 子章节递归
        /// </summary>
        /// <param name="directorList">
        /// </param>
        private void addChild(Model_DirectorList directorList)
        {
            if (directorList.children != null && directorList.children.Count > 0)
            {
                foreach (Model_DirectorList child in directorList.children)
                {
                    pageData.zhangjieList.Add(new ComboBoxBean()
                    {
                        Key = child.directorid,
                        Value = getSpace(child.directorlevel) + child.directorname,
                        leaf = child.leaf
                    });
                    if (child.children != null && child.children.Count > 0)
                    {
                        addChild(child);
                    }
                }
            }
        }

        /// <summary>
        /// 章节是否加空格符
        /// </summary>
        /// <param name="num">
        /// </param>
        /// <returns>
        /// </returns>
        private string getSpace(int num)
        {
            string str = "";
            for (int i = 0; i < num; i++)
            {
                str += "  ";
            }
            return str;
        }

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

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
        }

        /// <summary>
        /// 教材下拉框改变事件
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="e">
        /// </param>
        private void toolbar_list_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (App.TsubjectbookList.Count > 0)
            {
                Director();
            }
            else
            {
                MessageWindow.Show("暂无章节！");
                App.IsUpLoad = false;
                Hide();
            }
        }

        private void BtnDown_Click(object sender, RoutedEventArgs e)
        {
            App.IsUpLoad = false;
            Hide();
        }

        /// <summary>
        /// 上传到个人空间
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="e">
        /// </param>
        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(book_list.Text))
            {
                MessageWindow.Show("请选择教材！");
                return;
            }

            if (cmbTeachingMaterial.SelectedIndex < pageData.zhangjieList.Count)
            {
                int leaf = pageData.zhangjieList[cmbTeachingMaterial.SelectedIndex].leaf;
                if (leaf != 1)
                {
                    MessageWindow.Show("只能选择小节或全部进行上传！");
                    return;
                }
            }

            btnStart.IsEnabled = false;
            book_list.IsEnabled = false;
            cmbTeachingMaterial.IsEnabled = false;
            Thread myThread = new Thread(StartUpload);

            num = 0;
            tip_outer.Visibility = Visibility.Visible;
            myThread.Start();
            times = new System.Timers.Timer(100);
            times.Elapsed += Times_ElapsedClick;
            times.Start();
        }

        private void StartUpload()
        {
            try
            {
                DalUpload dAL_Upload = new DalUpload();
                if (dAL_Upload.UploadVideoTwo(Guid, out string ErrMessage))
                {
                    //        converted: 0
                    //createid: 80
                    //directorid: 1009
                    //duration: 39
                    //imgUrl: ""
                    //level: 2
                    //lsbid: 40
                    //mp4code: "h264"
                    //resourcebelong: 3
                    //resourceclass: 2
                    //resourcecover: "12/resource/20200917/4f297df0-f8c0-11ea-adf5-81f24b97d4ff/weather_pic.jpg"
                    //resourcename: "weather_pic"
                    //resourcesize: 6105268
                    //resourcetype: 0
                    //resourceurl: "12/resource/20200917/4f297df0-f8c0-11ea-adf5-81f24b97d4ff/weather_pic.mp4"
                    //schoolid: 12
                    //suffix: "mp4"
                    //uid: 80
                    Model_ResourceAdd model_ResourceAdd = new Model_ResourceAdd();
                    Dispatcher.Invoke(() =>
                    {
                        model_ResourceAdd = new Model_ResourceAdd
                        {
                            converted = 0,
                            createid = App.UserInfo.Userid,
                            directorid = cmbTeachingMaterial.SelectedValue.ToString(),
                            duration = App.ResourceAddTwo.duration,
                            subjectid = App.TsubjectbookList[book_list.SelectedIndex].Subjectid,
                            imgUrl = "",
                            level = 2,
                            lsbid = book_list.SelectedValue.ToString(),
                            mp4code = App.ResourceAddTwo.mp4code,
                            resourcebelong = 3,
                            resourceclass = 5,
                            resourcecover = App.ResourceAddTwo.coverpath,
                            resourcename = Resourcename,
                            resourcesize = Resourcesize,
                            resourcetype = 10,
                            resourceurl = App.ResourceAddTwo.videopath,
                            schoolid = App.UserInfo.Schoolid
                        };
                    });

                    if (Suffix.Equals("FLV"))
                    {
                        Suffix = "flv";
                    }
                    else if (Suffix.Equals("AVI"))
                    {
                        Suffix = "avi";
                    }
                    else
                    {
                        Suffix = "mp4";
                    }

                    model_ResourceAdd.suffix = Suffix;
                    //model_ResourceAdd.uid = 0;//zxy
                    int code = xhapi.ResourceAdd(model_ResourceAdd);
                    if (code == 0)
                    {
                        Dispatcher.Invoke(() =>
                        {
                            foreach (Model_WKData Vdata in App.WKDataList)
                            {
                                if (Vdata.VideoList == null)
                                {
                                    continue;
                                }
                                foreach (Model_Video videoinfo in Vdata.VideoList)
                                {
                                    if (videoinfo.FileGuid == Guid)
                                    {
                                        videoinfo.IsUpload = true;
                                        break;
                                    }
                                }
                            }

                            btnStart.IsEnabled = true;
                            book_list.IsEnabled = true;
                            cmbTeachingMaterial.IsEnabled = true;
                            num = 99;
                            times.Stop();
                            pgbProcess.Value = 100;
                            lbProcess.Content = "100%";
                            MessageWindow.Show("视频上传成功！");
                            tip_outer.Visibility = Visibility.Collapsed;
                            ChangeTextEvents("上传成功", i);
                            Hide();
                        });
                    }
                    else
                    {
                        Dispatcher.Invoke(() =>
                        {
                            btnStart.IsEnabled = true;
                            book_list.IsEnabled = true;
                            cmbTeachingMaterial.IsEnabled = true;
                            times.Stop();
                            tip_outer.Visibility = Visibility.Collapsed;
                            MessageWindow.Show(App.ServerMsg);
                        });
                    }
                }
                else
                {
                    Dispatcher.Invoke(() =>
                    {
                        btnStart.IsEnabled = true;
                        book_list.IsEnabled = true;
                        cmbTeachingMaterial.IsEnabled = true;
                        times.Stop();
                        tip_outer.Visibility = Visibility.Collapsed;
                        MessageWindow.Show(ErrMessage);
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() =>
                {
                    btnStart.IsEnabled = true;
                    book_list.IsEnabled = true;
                    cmbTeachingMaterial.IsEnabled = true;
                    times.Stop();
                    tip_outer.Visibility = Visibility.Collapsed;
                    MessageWindow.Show("无法上传视频，请检查与服务器链接状态！");
                    App.IsUpLoad = false;
                    Hide();
                    LogHelper.WriteErrLog("【UploadWindow】(BtnStart_Click)" + ex.Message, ex);
                });
            }
        }

        private int num = 0;

        /// <summary>
        /// 计时器
        /// </summary>
        /// <param name="sender">
        /// </param>
        /// <param name="e">
        /// </param>
        private void Times_ElapsedClick(object sender, System.Timers.ElapsedEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                pgbProcess.Value = num;
                lbProcess.Content = num.ToString() + "%";
                if (num < 99)
                {
                    num++;
                    times.Interval += (num / 2);
                }
                else
                {
                    times.Stop();
                }
            });
        }
    }

    public class LoginPageData : NotifyModel
    {
        public ObservableCollection<ComboBoxBean> bookList { get; set; }

        public ObservableCollection<ComboBoxBean> zhangjieList { get; set; }

        public LoginPageData()
        {
            bookList = new ObservableCollection<ComboBoxBean>();
            zhangjieList = new ObservableCollection<ComboBoxBean>();
        }
    }
}
