using ComPDFKitViewer;
using ComPDFKitViewer.PdfViewer;
using Microsoft.Win32;
using PDF_Master.Helper;
using PDF_Master.Model;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace PDF_Master.ViewModels.PropertyPanel.PDFEdit
{
    public class ImageEditPropertyViewModel : PDFEditVM, INavigationAware
    {
        #region 变量
        //防止自动保存属性值
        private bool isCanSave = false;
        public event EventHandler ClearCheckedAglin;
        #endregion

        #region 属性

        #region 是否为多选内容
        private bool _isMultiSelectImage = false;
        public bool IsMultiSelectImage { get { return _isMultiSelectImage; } set { SetProperty(ref _isMultiSelectImage, value); } }
        #endregion

        #region 不透明度
        private double _opacity;
        public double OpacityUI
        {
            get { return _opacity; }
            set { SetProperty(ref _opacity, value); }
        }
        private double _transpent;
        public double Transpent
        {
            get { return _transpent; }
            set
            {
                SetProperty(ref _transpent, value);
                if (TextEditEvent != null && isCanSave)
                {
                    if (IsMultiSelectImage)
                    {
                        foreach (var item in TextEditEventList)
                        {
                            item.Transparent = (int)(_transpent * 2.55);
                            item.UpdatePDFEditByEventArgs();
                        }
                    }
                    else
                    {
                        TextEditEvent.Transparent = (int)(_transpent * 2.55);
                        TextEditEvent.UpdatePDFEditByEventArgs();
                        OpacityUI = _transpent / 100.0;
                    }

                }
            }
        }
        #endregion

        #region 是否为图片裁剪状态
        private bool _isCrop = false;
        public bool IsCrop { get { return _isCrop; } set { SetProperty(ref _isCrop, value); } }
        #endregion

        #region 当前显示图像
        //选中的图像
        private System.Windows.Media.Imaging.BitmapSource _currentImg;
        public System.Windows.Media.Imaging.BitmapSource CurrentImg { get { return _currentImg; } set { SetProperty(ref _currentImg, value); } }

        #endregion

        #endregion

        #region Command
        //替换
        public DelegateCommand ReplaceImgCommand { get; set; }
        //导出
        public DelegateCommand ExportImgCommand { get; set; }
        //裁剪
        public DelegateCommand CropImgCommand { get; set; }
        //对齐
        public DelegateCommand<object> ImgAlignCheckedCommand { get; set; }

        //逆时针旋转
        public DelegateCommand AntiClockwiseCommand { get; set; }

        //顺时针旋转
        public DelegateCommand ClockwiseCommand { get; set; }
        //裁剪状态
        public DelegateCommand CropModeCommand { get; set; }
        //取消裁剪状态
        public DelegateCommand CancelCropCommand { get; set; }
        //添加文本
        public DelegateCommand AddTextCommand { get; set; }
        //添加图片
        public DelegateCommand AddImgCommand { get; set; }
        #endregion

        public ImageEditPropertyViewModel()
        {
           
            InitCommand();
        }

        private void InitCommand()
        {
            AddTextCommand = new DelegateCommand(AddText);
            AddImgCommand = new DelegateCommand(AddImg);

            ReplaceImgCommand = new DelegateCommand(ReplaceImg);
            ExportImgCommand = new DelegateCommand(ExportImg);
            CropImgCommand = new DelegateCommand(CropImg);
            ImgAlignCheckedCommand = new DelegateCommand<object>(ImgAlignChecked);

            AntiClockwiseCommand = new DelegateCommand(AntiClockwise);
            ClockwiseCommand = new DelegateCommand(Clockwise);
            CropModeCommand = new DelegateCommand(CropMode);
            CancelCropCommand = new DelegateCommand(CancelCropImg);
        }

        #region Command实现

        private void AddText()
        {
            PDFViewer.SetPDFEditCreateType(ComPDFKit.PDFPage.CPDFEditType.EditText);
        }

        private void CancelCropImg()
        {
            if (TextEditEvent != null)
            {
                TextEditEvent.ClipImage = false;
                TextEditEvent.CancelClip();

                TextEditEvent.UpdatePDFEditByEventArgs();
                IsCrop = false;
            }
        }

        private void CropImg()
        {
            if (TextEditEvent != null)
            {
                TextEditEvent.SaveClip();
                TextEditEvent.ClipImage = false;
                TextEditEvent.UpdatePDFEditByEventArgs();
                IsCrop = false;
            }
        }

        private void ExportImg()
        {
            if (PDFViewer == null || TextEditEvent == null || TextEditEvent.EditType != ComPDFKit.PDFPage.CPDFEditType.EditImage) return;

            System.Windows.Forms.FolderBrowserDialog folder = new System.Windows.Forms.FolderBrowserDialog();
            folder.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

            if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(folder.SelectedPath))
                    return;

                var keyValueList = PDFViewer.GetSelectedImages();
                int i = 0;
                foreach (var bitmap in keyValueList)
                {
                    foreach (var bitmapItem in bitmap.Value)
                    {
                        bitmapItem.Save(folder.SelectedPath + "\\" + i + ".png", System.Drawing.Imaging.ImageFormat.Png);
                        i++;
                    }
                }

                var strFilePath = folder.SelectedPath + "\\0.png";
                CommonHelper.ShowFileBrowser(strFilePath);
            }
        }

        private void AddImg()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "png|*.png;|Image|*.gif;*.jpg;*.jpeg;*.bmp;*.jfif;*.png;";
            openFileDialog.Multiselect = true;
            if ((bool)openFileDialog.ShowDialog())
            {
                if (string.IsNullOrEmpty(openFileDialog.FileName) == false)
                {
                    PDFViewer.SetPDFEditCreateType(ComPDFKit.PDFPage.CPDFEditType.EditImage);
                    PDFViewer.AddPDFEditImage(openFileDialog.FileName);
                }
            }
        }

        private void ReplaceImg()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "png|*.png;|Image|*.gif;*.jpg;*.jpeg;*.bmp;*.jfif;*.png;";
            openFileDialog.Multiselect = true;
            if ((bool)openFileDialog.ShowDialog())
            {
                if (string.IsNullOrEmpty(openFileDialog.FileName) == false)
                {
                    PDFViewer.SetPDFEditCreateType(ComPDFKit.PDFPage.CPDFEditType.EditImage);
                    TextEditEvent.ReplaceImagePath = openFileDialog.FileName;
                    TextEditEvent.UpdatePDFEditByEventArgs();
                }
            }
        }

        private void CropMode()
        {
            IsCrop = true;
            if (TextEditEvent != null)
            {
                TextEditEvent.ClipImage = true;
                TextEditEvent.UpdatePDFEditByEventArgs();
            }
        }

        private void Clockwise()
        {
            ImgRoateAngle(90);
        }

        private void AntiClockwise()
        {
            ImgRoateAngle(-90);
        }

        private void ImgRoateAngle(int angle)
        {
            if (IsMultiSelectImage)
            {
                foreach (var item in TextEditEventList)
                {
                    item.Rotate = item.Rotate + angle;
                    item.UpdatePDFEditByEventArgs();
                }
            }
            else
            {
                TextEditEvent.Rotate = TextEditEvent.Rotate + angle;
                TextEditEvent.UpdatePDFEditByEventArgs();
                GetImagePreView();
            }
        }

        #endregion

        #region 布局处理
        private void ImgAlignChecked(object obj)
        {
            if (obj != null)
            {
                switch ((string)obj)
                {
                    case "AlignLeft":
                        PDFViewer.SetPDFEditAligment(AlignModes.AlignLeft);
                        break;
                    case "AlignHorizonCenter":
                        PDFViewer.SetPDFEditAligment(AlignModes.AlignHorizonCenter);
                        break;
                    case "AlignRight":
                        PDFViewer.SetPDFEditAligment(AlignModes.AlignRight);
                        break;
                    case "DistributeHorizontal":
                        PDFViewer.SetPDFEditAligment(AlignModes.DistributeHorizontal);
                        break;
                    case "AlignTop":
                        PDFViewer.SetPDFEditAligment(AlignModes.AlignTop);
                        break;
                    case "AlignVerticalCenter":
                        PDFViewer.SetPDFEditAligment(AlignModes.AlignVerticalCenter);
                        break;
                    case "AlignBottom":
                        PDFViewer.SetPDFEditAligment(AlignModes.AlignBottom);
                        break;
                    case "DistributeVertical":
                        PDFViewer.SetPDFEditAligment(AlignModes.DistributeVertical);
                        break;
                }

            }
        }

        private void ReLoadLayoutAlign(int count)
        {
            if (count >= 2)
                IsLayoutAlign = true;
            else
                IsLayoutAlign = false;

            if (count >= 3)
                IsLayoutAvgAlign = true;
            else
                IsLayoutAvgAlign = false;
        }
        #endregion
        protected List<PDFEditEvent> TextEditEventList;
        public void OnNavigatedTo(NavigationContext navigationContext)
        {

            navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
            navigationContext.Parameters.TryGetValue<List<PDFEditEvent>>(ParameterNames.AnnotEvent, out TextEditEventList);
            if (PDFViewer != null)
            {
                PDFViewer.PDFEditCommandHandler -= PDFViewer_PDFEditCommandHandler;
                PDFViewer.PDFEditCommandHandler += PDFViewer_PDFEditCommandHandler;
                LoadedPDFEdit();
                isCanSave = true;
            }
        }

        private void LoadedPDFEdit()
        {
            if (TextEditEventList != null && TextEditEventList.Count > 0)
            {
                TextEditEvent = TextEditEventList[0];
                if (TextEditEventList.Count > 1)
                {
                    IsMultiSelectImage = true;
                }
                else
                {
                    GetImagePreView();
                }
                if (TextEditEventList.Count == 2)
                {
                    IsLayoutAlign = true;
                    IsLayoutAvgAlign = false;
                }
                else if (TextEditEventList.Count > 2)
                {
                    IsLayoutAlign = true;
                    IsLayoutAvgAlign = true;
                }
                else
                {
                    IsLayoutAlign = false;
                    IsLayoutAvgAlign = false;
                }
                GetPDFEdit();
            }
        }
        private void GetPDFEdit()
        {
            var tranUI = (TextEditEvent.Transparent / 255.0)*100;
            var temp = Math.Round((double)tranUI, 0);
            Transpent = temp;
            OpacityUI = temp/100.0;

        }
        //点击空白处时
        private ContextMenu EmptyStateMenu(object sender)
        {
            var popMenu = App.Current.FindResource("NoneMenu") as ContextMenu;
            CustomPopMenu customMenu = new CustomPopMenu(popMenu, sender);
            //粘贴
            customMenu.SetMenuBinding(0, ApplicationCommands.Paste);
            //添加文本
            customMenu.SetMenuBinding(1, AddTextCommand);
            //添加图像
            customMenu.SetMenuBinding(2, AddImgCommand);

            return popMenu;
        }
        //选中图像时
        private ContextMenu SelectImgPDFEdit(object sender)
        {
            var popMenu = App.Current.FindResource("SelectImgMenu") as ContextMenu;
            CustomPopMenu customMenu = new CustomPopMenu(popMenu,sender);
            //复制
            customMenu.SetMenuBinding(0, ApplicationCommands.Copy);
            //剪切
            customMenu.SetMenuBinding(1, ApplicationCommands.Cut);
            //粘贴
            customMenu.SetMenuBinding(2, ApplicationCommands.Paste);
            //删除
            customMenu.SetMenuBinding(3, ApplicationCommands.Delete);
            //裁剪
            customMenu.SetMenuBinding(4, CropModeCommand);
            //替换
            customMenu.SetMenuBinding(5, ReplaceImgCommand);
            //导出
            customMenu.SetMenuBinding(6, ExportImgCommand);
            return popMenu;
        }

        private void PDFViewer_PDFEditCommandHandler(object sender, PDFEditCommand e)
        {

            if (e == null)
                return;

            switch (e.CommandType)
            {
                case CommandType.Context:

                    if (e.EditType == ComPDFKit.PDFPage.CPDFEditType.None)
                    {
                        e.PopupMenu = EmptyStateMenu(sender);

                    }
                    else if (e.EditType == ComPDFKit.PDFPage.CPDFEditType.EditImage)
                    {
                        e.PopupMenu = SelectImgPDFEdit(sender);
                    }
                    break;

                default:
                    e.DoCommand();
                    break;

            }
            if (e.PopupMenu != null)
            {
                e.Handle = true;
            }
        }

        private void GetImagePreView()
        {
            try
            {
                var list = PDFViewer.GetSelectedImages();
                if (list != null && list.Count > 0)
                {
                    System.Drawing.Bitmap bitmap = null;
                    foreach (var item in list)
                    {
                        if (item.Value.Count > 0)
                        {
                            bitmap = item.Value[0];
                            break;
                        }
                    }

                    if (bitmap != null)
                    {
                        IntPtr ip = bitmap.GetHbitmap();
                        System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                        CurrentImg = bitmapSource;
                    }

                }
            }
            catch
            {

            }
         
        }
        #region 全局

        #endregion
        public bool IsNavigationTarget(NavigationContext navigationContext) { return true; }


        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            isCanSave = false;
            IsMultiSelectImage = false;
            TextEditEvent = null;
            ClearCheckedAglin?.Invoke(null, null);
            PDFViewer.PDFEditCommandHandler -= PDFViewer_PDFEditCommandHandler;
        }
    }
}