using Common.system;
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using XHWK.Model;

namespace XHWK.WKTool
{
    /// <summary>
    /// 录屏画板
    /// </summary>
    public partial class PracticeWindow
    {
        //声明一个 DrawingAttributes 类型的变量
        private DrawingAttributes _drawingAttributes;

        private DrawingAttributes _drawing;
        private ViewModel _viewModel;

        /// <summary>
        /// 0 画笔 1 矩形 2 圆形
        /// </summary>
#pragma warning disable CS0414
        private int _flg;
#pragma warning restore CS0414

        /// <summary>
        /// 当前画笔颜色
        /// </summary>
        private Color _colour = Colors.Red;

        /// <summary>
        /// 当前画笔宽
        /// </summary>
        private int _wit = 2;

        /// <summary>
        /// 当前画笔高
        /// </summary>
        private int _hei = 2;

        public PracticeWindow()
        {
            InitializeComponent();

            InitTqlpPen();
        }

        public void Initialize(string imgPath = null)
        {
            _flg = 0;
            blackboard_canvas.Strokes.Clear();
            blackboard_canvas.UseCustomCursor = true;
            //blackboard_canvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
            //加背景 废弃更利于讲解ppt
            //if (File.Exists(_imgPath))
            //{
            //    imgCanvas.Source = new BitmapImage(new Uri(_imgPath));
            //}

            //创建 DrawingAttributes 类的一个实例
            _drawingAttributes = new DrawingAttributes();

            //drawingAttributes.StylusTip = StylusTip.Rectangle;
            //drawingAttributes.IsHighlighter = false;
            //drawingAttributes.IgnorePressure = true;

            ////将 InkCanvas 的 DefaultDrawingAttributes 属性的值赋成创建的 DrawingAttributes 类的对象的引用
            ////InkCanvas 通过 DefaultDrawingAttributes 属性来获取墨迹的各种设置，该属性的类型为 DrawingAttributes 型
            blackboard_canvas.DefaultDrawingAttributes = _drawingAttributes;
            Pen();
            //blackboard_canvas.Cursor = Cursors.Pen;

            //Cursor cus = new Cursor(@"G:\06.cur");

            //blackboard_canvas.Cursor = cus;

            _viewModel = new ViewModel
            {
                InkStrokes = new StrokeCollection(),
            };

            DataContext = _viewModel;
            //APP.W_ScreenRecordingToolbarWindow.Owner = this;
            //APP.W_ScreenRecordingToolbarWindow.Topmost = true;
        }

        /// <summary>
        /// 画笔颜色事件 白色
        /// </summary>
        public void White()
        {
            //flg = 0;
            _drawingAttributes.Color = Colors.White;
            _colour = Colors.White;
        }

        /// <summary>
        /// 画笔颜色事件 红色
        /// </summary>
        public void Red()
        {
            _drawingAttributes.Color = Colors.Red;
            _colour = Colors.Red;
        }

        /// <summary>
        /// 画笔颜色事件 黑色
        /// </summary>
        public void Gray()
        {
            //flg = 0;
            _drawingAttributes.Color = Colors.Black;
            _colour = Colors.Black;
        }

        /// <summary>
        /// 画笔颜色事件 青色
        /// </summary>
        public void CyanBlue()
        {
            //flg = 0;
            _drawingAttributes.Color = Colors.LimeGreen;
            _colour = Colors.LimeGreen;
        }

        /// <summary>
        /// 画笔颜色事件 黄色
        /// </summary>
        public void Yellow()
        {
            //flg = 0;
            _drawingAttributes.Color = Colors.Gold;
            _colour = Colors.Gold;
        }

        /// <summary>
        /// 画笔颜色事件 蓝色
        /// </summary>
        public void Blue()
        {
            //flg = 0;
            _drawingAttributes.Color = Colors.DeepSkyBlue;
            _colour = Colors.DeepSkyBlue;
        }

        /// <summary>
        /// 画笔粗细事件 细
        /// </summary>
        public void Fine()
        {
            //flg = 0;
            _drawingAttributes.Width = 1;
            _drawingAttributes.Height = 1;
            _wit = 1;
            _hei = 1;
        }

        /// <summary>
        /// 画笔粗细事件 中
        /// </summary>
        public void In()
        {
            //flg = 0;
            _drawingAttributes.Width = 3;
            _drawingAttributes.Height = 3;
            _wit = 3;
            _hei = 3;
        }

        /// <summary>
        /// 画笔粗细事件 粗
        /// </summary>
        public void Crude()
        {
            //flg = 0;
            _drawingAttributes.Width = 5;
            _drawingAttributes.Height = 5;
            _wit = 5;
            _hei = 5;
        }

        /// <summary>
        /// 橡皮
        /// </summary>
        public void Eraser()
        {
            _flg = 0;
            //this.type = ZPenType.Erase;
            blackboard_canvas.UseCustomCursor = false;
            blackboard_canvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
            blackboard_canvas.EraserShape = new EllipseStylusShape(64, 64, 0);
        }

        /// <summary>
        /// 画笔
        /// </summary>
        public void Pen()
        {
            _flg = 0;
            blackboard_canvas.EditingMode = InkCanvasEditingMode.Ink;
            blackboard_canvas.UseCustomCursor = true;
            _drawingAttributes.FitToCurve = true;
            _drawingAttributes.IgnorePressure = false;

            blackboard_canvas.Cursor = Cursors.Pen;
        }

        /// <summary>
        /// 圆
        /// </summary>
        public void Round()
        {
            _flg = 2;
            _drawingAttributes = new DrawingAttributes
            {
                Color = _colour,
                Width = _wit,
                Height = _hei,
                StylusTip = StylusTip.Rectangle,
                //FitToCurve = true,
                IsHighlighter = false,
                IgnorePressure = true,
            };
            blackboard_canvas.DefaultDrawingAttributes = _drawingAttributes;
            blackboard_canvas.EditingMode = InkCanvasEditingMode.None;
            blackboard_canvas.Cursor = Cursors.Cross;
        }

        /// <summary>
        /// 矩形
        /// </summary>
        public void Rectangle()
        {
            _flg = 1;
            _drawingAttributes = new DrawingAttributes
            {
                Color = _colour,
                Width = _wit,
                Height = _hei,
                StylusTip = StylusTip.Rectangle,
                //FitToCurve = true,
                IsHighlighter = false,
                IgnorePressure = true,
            };
            blackboard_canvas.DefaultDrawingAttributes = _drawingAttributes;
            blackboard_canvas.EditingMode = InkCanvasEditingMode.None;
            blackboard_canvas.Cursor = Cursors.Cross;
        }

        /// <summary>
        /// 鼠标中键点击
        /// </summary>
        private void SwitchPages()
        {
            try
            {
                new Thread(() =>
                {
                    Thread.Sleep(500);
                    MouseEventCommon.MouseMiddleClickEvent(0);
                }).Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void blackboard_canvas_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (App.W_ScreenRecordingToolbarWindow.flg == 10)
            {
                App.W_ScreenRecordingToolbarWindow.flg = 0;
            }
            else
            {
                App.W_ScreenRecordingToolbarWindow.flg = 1;
            }

            ReturnPractice();
            //模拟切到ppt
            SwitchPages();
            //Hide();
        }

        /// <summary>
        /// 退出批注并清空画板
        /// </summary>
        public void ReturnPractice()
        {
            blackboard_canvas.Strokes.Clear();
            new Thread(() =>
            {
                Dispatcher.Invoke(() => { App.W_ScreenRecordingToolbarWindow.ModifyState(); });
                _flg = 0;
                Thread.Sleep(500);
                Dispatcher.Invoke(() =>
                {
                    Owner = null;
                    App.W_PracticeWindow.Hide();
                });
            }).Start();
        }

        #region 点阵笔相关

        #region 值初始化

        // 不同尺寸点阵纸点阵宽高尺寸计算方法为：纸张物理尺寸（毫米）/0.3 *8,详见 开发必读.pdf 文档

        ///// <summary>
        ///// 画板
        ///// </summary>
        //private Graphics graphics;

        #endregion 值初始化

        private bool _isFirst = true;
        private StylusPointCollection _stylusPoints = new StylusPointCollection();
        private StylusPoint _stylusPoint;
        private Stroke _strokes;

        /// <summary>
        /// 引用user32.dll动态链接库（windows api），
        /// 使用库中定义 API：SetCursorPos
        /// 设置光标位置
        /// </summary>
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern int SetCursorPos(int x, int y);

        #endregion 点阵笔相关

        #region 腾千里手写笔

        /// <summary>
        /// 是否在书写
        /// </summary>
        private bool _isTqlPenDown;

        /// <summary>
        /// TQL点阵笔宽高
        /// </summary>
//static float TQLA4_WIDTH = (float)1075 / (float)150 * (float)25.4 / (float)1.524; //OID4
//static float TQLA4_HEIGHT = (float)1512 / (float)150 * (float)25.4 / (float)1.524;
        private const float Tqla4Width = 2480 / (float)300 * (float)25.4 / (float)1.524;

        private const float Tqla4Height = 3509 / (float)300 * (float)25.4 / (float)1.524;

        /// <summary>
        /// 初始化
        /// </summary>
        public void InitTqlpPen()
        {
            if (App.TQLPenevents == null)
            {
                App.TQLPenevents = new PenEvents(2);
            }
            else
            {
                App.TQLPenevents.InToType = 2;
            }
        }

        /// <summary>
        /// 笔落下
        /// </summary>
        public void TqlDown()
        {
            _isTqlPenDown = true;
            App.W_ScreenRecordingToolbarWindow.PenPractice();
            if (_strokes != null && _strokes.StylusPoints.Count > 1)
            {
                _isFirst = true;
            }

            _stylusPoints = new StylusPointCollection();
            _stylusPoint = new StylusPoint();
            _strokes = null;
        }

        /// <summary>
        /// 笔抬起
        /// </summary>
        public void TqlUp()
        {
            _isTqlPenDown = false;

            if (_strokes != null && _strokes.StylusPoints.Count > 1)
            {
                _isFirst = true;
            }

            _stylusPoints = new StylusPointCollection();
            _stylusPoint = new StylusPoint();
            _strokes = null;
        }

        /// <summary>
        /// 笔书写
        /// </summary>
        /// <param name="cx"></param>
        /// <param name="cy"></param>
        /// <param name="force"></param>
        public void TqlPenWrite(double cx, double cy, int force)
        {
            if (this.Visibility == Visibility.Visible)
            {
                //判断是否是落笔后输出的坐标，在设置悬浮模式下，落笔前的悬浮坐标不绘制
                if (!_isTqlPenDown)
                {
                    return;
                }

                double propW = blackboard_canvas.ActualWidth / Tqla4Height;
                double propH = blackboard_canvas.ActualHeight / Tqla4Width;

                double tempX = cy * propW;
                double tempY = (Tqla4Width - cx) * propH;
                Dispatcher.Invoke(() =>
                {
                    //0~1023,亦即有 1024 阶供应用软件后续应用之用，如笔锋笔触，暂无用
                    //添加笔画
                    if (_isFirst)
                    {
                        _stylusPoint.X = tempX;
                        _stylusPoint.Y = tempY;
                        _stylusPoints.Add(_stylusPoint);
                        if (_stylusPoints.Count > 1)
                        {
                            _drawing = new DrawingAttributes
                            {
                                Color = _colour,
                                Width = _wit * 4.5,
                                Height = _wit * 4.5,
                                FitToCurve = true,
                                IgnorePressure = false
                            };

                            _strokes = new Stroke(_stylusPoints);

                            _strokes.DrawingAttributes = _drawing;

                            blackboard_canvas.Strokes.Add(_strokes);
                            _isFirst = false;
                        }
                    }
                    else
                    {
                        if (blackboard_canvas.Strokes.Count > 0)
                        {
                            _stylusPoint.X = tempX;
                            _stylusPoint.Y = tempY;
                            _stylusPoints.Add(_stylusPoint);
                            _strokes = new Stroke(_stylusPoints);
                            _drawing = new DrawingAttributes
                            {
                                Color = _colour,
                                Width = _wit * 4.5,
                                Height = _wit * 4.5,
                                FitToCurve = true,
                                IgnorePressure = false
                            };
                            _strokes.DrawingAttributes = _drawing;

                            //viewModel.InkStrokes.Add(strokes);
                            blackboard_canvas.Strokes[blackboard_canvas.Strokes.Count - 1] = _strokes;
                        }
                    }

                    //设置鼠标位置
                    if (tempX > 0 && tempY > 0)
                    {
                        //System.Windows.Point getP = scroMain.PointToScreen(new System.Windows.Point(testX, testY - scroMain.VerticalOffset));
                        SetCursorPos((int)((float)tempX * (PrimaryScreen.DpiX / 96f)),
                            (int)((float)tempY * (PrimaryScreen.DpiY / 96f)));
                    }
                });
            }
        }

        #endregion 腾千里手写笔
    }
}
