using DotNetSpeech;
using Microsoft.AppCenter.Utils.Files;
using PDF_Master.Helper;
using PDF_Master.Model;
using PDF_Master.Model.PageEdit;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace PDF_Master.ViewModels.Dialog.PageEditDialogs
{
    public class InsertDialogViewModel : BindableBase, IDialogAware
    {
        public string Title => "";

        /// <summary>
        /// 数据模型
        /// </summary>
        private CustomInsertModel Model = new CustomInsertModel();

        public event Action<IDialogResult> RequestClose;

        private Size size = new Size();

        private int height;
        private int width;

        private string currentPageSize;

        /// <summary>
        /// 当前页的尺寸大小  括号显示的形式
        /// </summary>
        public string CurrentPageSize
        {
            get { return currentPageSize; }
            set
            {
                SetProperty(ref currentPageSize, value);
            }
        }

        private int listSelectedIndex;

        public int ListSelectedIndex
        {
            get { return listSelectedIndex; }
            set
            {
                SetProperty(ref listSelectedIndex, value);
            }
        }

        private int itemSelectedIndex = 0;

        /// <summary>
        /// 自定义页面的选中索引
        /// </summary>
        public int ItemSelectedIndex
        {
            get { return itemSelectedIndex; }
            set
            {
                SetProperty(ref itemSelectedIndex, value);
                if (Model != null)
                {
                    Model.filepath = Pages[itemSelectedIndex].FilePath;
                }
            }
        }

        private string customWidth;

        /// <summary>
        /// 自定义页面宽度
        /// </summary>
        public string CustomWidth
        {
            get { return customWidth; }
            set
            {
                SetProperty(ref customWidth, value);
                if ((string.IsNullOrEmpty(value) == false))
                {
                    Model.width = int.Parse(value);
                    if (IsVerticalSelected == false && IsCustomSelected)
                    {
                        width = int.Parse(CustomHeight);
                        height = int.Parse(value);
                    }
                }
            }
        }

        private string customHeight;

        /// <summary>
        /// 自定义页面高度
        /// </summary>
        public string CustomHeight
        {
            get { return customHeight; }
            set
            {
                SetProperty(ref customHeight, value);
                if ((string.IsNullOrEmpty(value) == false))
                {
                    Model.height = int.Parse(value);
                    if (IsVerticalSelected == false && IsCustomSelected)
                    {
                        height = int.Parse(CustomWidth);
                        width = int.Parse(value);
                    }
                }
            }
        }

        private int unitsSelectedIndex = 0;

        /// <summary>
        /// 单位下拉框的选中项索引
        /// </summary>
        public int UnitsSelectedIndex
        {
            get { return unitsSelectedIndex; }
            set
            {
                SetProperty(ref unitsSelectedIndex, value);
            }
        }

        private int pageSizeSelectedIndex = 0;

        /// <summary>
        /// 页面尺寸选中项
        /// </summary>
        public int PageSizeSelectedIndex
        {
            get { return pageSizeSelectedIndex; }
            set
            {
                SetProperty(ref pageSizeSelectedIndex, value);
                if (pageSizeSelectedIndex != -1)
                {
                    PageSizeInfo pageSizeInfo = PageSizeInfos[pageSizeSelectedIndex];
                    if (pageSizeInfo != null)
                    {
                        if (IsVerticalSelected == false)
                        {
                            IsVerticalSelected = true;
                        }

                        CustomWidth = pageSizeInfo.Width;
                        CustomHeight = pageSizeInfo.Height;

                        Model.width = Convert.ToInt32(pageSizeInfo.Width);
                        Model.height = Convert.ToInt32(pageSizeInfo.Height);

                        height = Model.height;
                        width = Model.width;
                    }
                }
            }
        }

        private bool isCurrentIsEnabled = true;

        public bool IsCurrentIsEnabled
        {
            get { return isCurrentIsEnabled; }
            set
            {
                SetProperty(ref isCurrentIsEnabled, value);
            }
        }

        private bool isCurrentSelected = true;

        public bool IsCurrentSelected
        {
            get { return isCurrentSelected; }
            set
            {
                SetProperty(ref isCurrentSelected, value);
                if (IsCurrentSelected && size != null)
                {
                    if (IsVerticalSelected == false)
                    {
                        IsVerticalSelected = true;
                    }

                    CustomWidth = size.Width.ToString("F0");
                    CustomHeight = size.Height.ToString("F0");

                    Model.width = Convert.ToInt32(size.Width);
                    Model.height = Convert.ToInt32(size.Height);

                    height = Model.height;
                    width = Model.width;
                }
            }
        }

        private bool isStandSelcted;

        public bool IsStandSelected
        {
            get { return isStandSelcted; }
            set
            {
                SetProperty(ref isStandSelcted, value);
                PageSizeInfo pageSizeInfo = PageSizeInfos[PageSizeSelectedIndex];
                if (IsStandSelected && pageSizeInfo != null)
                {
                    if (IsVerticalSelected == false)
                    {
                        IsVerticalSelected = true;
                    }
                    CustomWidth = pageSizeInfo.Width;
                    CustomHeight = pageSizeInfo.Height;
                    Model.width = Convert.ToInt32(pageSizeInfo.Width);
                    Model.height = Convert.ToInt32(pageSizeInfo.Height);

                    height = Model.height;
                    width = Model.width;
                }
            }
        }

        private bool isCustomSelected;

        public bool IsCustomSelected
        {
            get { return isCustomSelected; }
            set
            {
                SetProperty(ref isCustomSelected, value);
                if (IsCustomSelected)
                {
                    IsVerticalSelected = true;
                }
            }
        }

        private bool isVerticalSelected = true;

        public bool IsVerticalSelected
        {
            get { return isVerticalSelected; }
            set
            {
                SetProperty(ref isVerticalSelected, value);
                if (isVerticalSelected)
                {
                    if (height != 0 && width != 0)
                    {
                        if (height.ToString() != CustomHeight)
                        {
                            CustomHeight = height.ToString();
                        }
                        if (width.ToString() != CustomWidth)
                        {
                            CustomWidth = width.ToString();
                        }
                        Model.width = width;
                        Model.height = height;
                    }
                }
            }
        }

        private bool isHorizontalSelected;

        public bool IsHorizontalSelected
        {
            get { return isHorizontalSelected; }
            set
            {
                SetProperty(ref isHorizontalSelected, value);
                if (isHorizontalSelected)
                {
                    if (IsCustomSelected)
                    {
                        height = Model.height;
                        width = Model.width;
                    }
                    if (width != 0 && height != 0)
                    {
                        if (CustomHeight != width.ToString())
                        {
                            CustomHeight = width.ToString();
                        }
                        if (CustomWidth != height.ToString())
                        {
                            CustomWidth = height.ToString();
                        }

                        Model.width = height;
                        Model.height = width;
                    }
                }
            }
        }

        /// <summary>
        /// 自定义页面的路径集合
        /// </summary>
        public ObservableCollection<CustomPageItem> Pages { get; set; }

        /// <summary>
        /// 页面单位集合
        /// </summary>
        public List<string> Units { get; set; }

        public List<string> PageSize { get; set; }
        public List<PageSizeInfo> PageSizeInfos { get; set; }
        public DelegateCommand CancelCommand { get; set; }

        public DelegateCommand InsertCommnad { get; set; }

        public InsertDialogViewModel()
        {
            InitPageSource();
            InitUnits();
            InitPage();

            CancelCommand = new DelegateCommand(cancel);
            InsertCommnad = new DelegateCommand(insert);
        }

        private void InitPage()
        {
            PageSize = new List<string>();
            //PageSize.Add("Letter(8.5x11 inches)");
            //PageSize.Add("Legal (210 x 297mm)");
            //PageSize.Add("A3 (297 x 420mm)");
            //PageSize.Add("A4 (210 x 297mm)");
            //PageSize.Add("A5 (148 x 210mm)");
            //PageSize.Add("B4 (250 x 353mm)");
            //PageSize.Add("B5 (176 x 250mm)");
            //PageSize.Add("Executive (7.25x10.5 inches)");
            //PageSize.Add("US4x6 (4x6 inches)");
            //PageSize.Add("US4x8 (4x8 inches)");
            //PageSize.Add("US5x7 (5x7 inches)");
            //PageSize.Add("Comm10 (4.125x9.5 inches)");

            PageSizeInfos = new List<PageSizeInfo>() {
             new PageSizeInfo(){ Name="A3",Width="297",Height="420",Unit="mm"},
             new PageSizeInfo(){ Name="A4",Width="210",Height="297",Unit="mm"},
             new PageSizeInfo(){ Name="A5",Width="148",Height="210",Unit="mm"},
             new PageSizeInfo(){ Name="B5",Width="176",Height="250",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_10Envelope"),Width ="105",Height="241",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_Choukei3"),Width="120",Height="235",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_DLEnvelope"),Width="110",Height="220",Unit="mm"},
             new PageSizeInfo(){ Name="JIS B5",Width="182",Height="257",Unit="mm"},
             new PageSizeInfo(){ Name="ROC 16K",Width="197",Height="273",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_SuperB"),Width="330",Height="483",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_TabloidPaper"),Width="279",Height="432",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_TabloidPaperBig"),Width="305",Height="457",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_USLegalPaper"),Width="216",Height="356",Unit="mm"},
             new PageSizeInfo(){ Name=App.MainPageLoader.GetString("PageEdit_USLetterPaper"),Width="216",Height="279",Unit="mm"},
            };
            foreach (var item in PageSizeInfos)
            {
                PageSize.Add($"{item.Name}({item.Width} x {item.Height} {item.Unit})");
            }
        }

        /// <summary>
        /// 初始化页面大小单位集合
        /// </summary>
        private void InitUnits()
        {
            Units = new List<string>();
            Units.Add("mm");
            Units.Add("cm");
            Units.Add("in");
        }

        /// <summary>
        /// 初始化自定义页面集合
        /// </summary>
        private void InitPageSource()
        {
            Pages = new ObservableCollection<CustomPageItem>();

            //20230704 插入自定义弹窗,弹窗不出来的情况,保险起见 先注释掉这部分代码
            //Pages.Add(new CustomPageItem() { Name = "空白页", FilePath = "" });

            //string filePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Resources\PageEdit\HorizontalLine.jpg");
            //if (System.IO.File.Exists(filePath))
            //{
            //    Pages.Add(new CustomPageItem() { Name = "横线", FilePath = filePath });
            //}
            //filePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Resources\PageEdit\Staff.jpg");
            //if (System.IO.File.Exists(filePath))
            //{
            //    Pages.Add(new CustomPageItem() { Name = "五线谱", FilePath = filePath });
            //}
            //filePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Resources\PageEdit\GridLine.jpg");
            //if (System.IO.File.Exists(filePath))
            //{
            //    Pages.Add(new CustomPageItem() { Name = "格子线", FilePath = filePath });
            //}
            //Pages.Add(new CustomPageItem() { Name = "横线", FilePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Resources\PageEdit\HorizontalLine.jpg") });
            //Pages.Add(new CustomPageItem() { Name = "五线谱", FilePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Resources\PageEdit\Staff.jpg") });
            //Pages.Add(new CustomPageItem() { Name = "格子线", FilePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Resources\PageEdit\GridLine.jpg") });
        }

        private void cancel()
        {
            RequestClose.Invoke(new DialogResult(ButtonResult.Cancel));
        }

        private void insert()
        {
            //最后统一处理页面尺寸
            if (IsCurrentSelected)
            {
                Model.width = Convert.ToInt32(size.Width);
                Model.height = Convert.ToInt32(size.Height);
            }
            else if (IsStandSelected)
            {
                PageSizeInfo pageSizeInfo = PageSizeInfos[PageSizeSelectedIndex];
                if (pageSizeInfo != null)
                {
                    Model.width = Convert.ToInt32(pageSizeInfo.Width);
                    Model.height = Convert.ToInt32(pageSizeInfo.Height);
                }
            }
            else
            {
                int width = Convert.ToInt32(size.Width);
                int height = Convert.ToInt32(size.Height);
                int.TryParse(customWidth, out width);
                int.TryParse(customHeight, out height);
                if (width <= 0)
                {
                    width = Convert.ToInt32(size.Width);
                }
                if (height <= 0)
                {
                    height = Convert.ToInt32(size.Height);
                }
                switch (unitsSelectedIndex)
                {
                    case 1:
                        width = width / 10;
                        height = height / 10;
                        break;

                    case 2:
                        width = Convert.ToInt32(width / 25.4);
                        height = Convert.ToInt32(height / 25.4);
                        break;

                    case 0:
                    default:
                        break;
                }
                Model.width = width;
                Model.height = height;
            }

            //方向处理
            if (isVerticalSelected)
            {
                if (Model.height <= Model.width)
                {
                    //纵向  需要重新定义宽高
                    var temp = Model.height;
                    Model.height = Model.width;
                    Model.width = temp;
                }
            }
            else
            {
                if (Model.height > Model.width)
                {
                    var temp = Model.height;
                    Model.height = Model.width;
                    Model.width = temp;
                }
            }

            DialogParameters valuePairs = new DialogParameters();
            //将mm转换成像素单位
            Model.width = (int)CommonHelper.GetPageSizeFomrUnit(Model.width);
            Model.height = (int)CommonHelper.GetPageSizeFomrUnit(Model.height);
            valuePairs.Add(ParameterNames.DataModel, Model);
            RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
        }

        #region 弹窗接口

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters != null)
            {
                size = parameters.GetValue<Size>(ParameterNames.CurrentPageSize);
                ListSelectedIndex = parameters.GetValue<int>(ParameterNames.PageEditSelectedIndex);

                //未选择页面时,【当前页】项置灰不可点击,默认选中【标准】A4
                if (ListSelectedIndex == -1)
                {
                    IsCurrentIsEnabled = false;
                    PageSizeSelectedIndex = 1;
                    IsStandSelected = true;
                }
                else
                {
                    CurrentPageSize = $"({size.Width.ToString("F0")}mm*{size.Height.ToString("F0")}mm)";
                    IsCurrentIsEnabled = true;
                    IsCurrentSelected = true;
                }
                IsVerticalSelected = true;
            }
        }

        #endregion 弹窗接口
    }
}