using Aitex.Core.Common.DeviceData;
using Aitex.Core.UI.ControlDataContext;
using Caliburn.Micro;
using MECF.Framework.UI.Client.Ctrlib.UnitControls;
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.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SicUI.Controls
{
    /// <summary>
    /// AnalogControl2.xaml 的交互逻辑
    /// </summary>
    public partial class AnalogControl2 : UserControl
    {
        public AnalogControl2()
        {
            InitializeComponent();
            
           // LabelSet = "0.0";
        }

        public event Action<string, string> clickAct;
        // define dependency properties
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
                        "Command", typeof(ICommand), typeof(AnalogControl2),
                        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));

        public static readonly DependencyProperty DeviceDataProperty = DependencyProperty.Register(
                        "DeviceData", typeof(AITMfcData), typeof(AnalogControl2),
                        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender,
                        new PropertyChangedCallback(OnDeviceDataChanged)));

        public static readonly DependencyProperty OperationNameProperty = DependencyProperty.Register(
                "OperationName", typeof(string), typeof(AnalogControl2),
                new FrameworkPropertyMetadata(AnalogDeviceOperation.Ramp, FrameworkPropertyMetadataOptions.AffectsRender));

        public static readonly DependencyProperty BackColorProperty = DependencyProperty.Register(
                        "BackColor", typeof(Brush), typeof(AnalogControl2),
                         new FrameworkPropertyMetadata(Brushes.Green, FrameworkPropertyMetadataOptions.AffectsRender));

        public static readonly DependencyProperty HideDialogProperty = DependencyProperty.Register(
                    "HideDialog", typeof(bool), typeof(AnalogControl2),
                    new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));

        public static readonly DependencyProperty LabelSetProperty = DependencyProperty.Register(
                  "LabelSet", typeof(object), typeof(AnalogControl2),
                  new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
        private static void OnDeviceDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
        }

        /// <summary>
        /// 输入值是否百分比，默认否
        /// </summary>
        public bool IsPercent { get; set; }

        public ICommand Command
        {
            get
            {
                return (ICommand)this.GetValue(CommandProperty);
            }
            set
            {
                this.SetValue(CommandProperty, value);
            }
        }

        /// <summary>
        /// set, get current progress value AnalogDeviceData
        /// </summary>
        public AITMfcData DeviceData
        {
            get
            {
                return (AITMfcData)this.GetValue(DeviceDataProperty);
            }
            set
            {
                this.SetValue(DeviceDataProperty, value);
            }
        }

        public Brush BackColor
        {
            get
            {
                return (Brush)this.GetValue(BackColorProperty);
            }
            set
            {
                this.SetValue(BackColorProperty, value);
            }
        }

        public string OperationName
        {
            get
            {
                return (string)this.GetValue(OperationNameProperty);
            }
            set
            {
                this.SetValue(OperationNameProperty, value);
            }
        }

        public bool HideDialog
        {
            get
            {
                return (bool)this.GetValue(HideDialogProperty);
            }
            set
            {
                this.SetValue(HideDialogProperty, value);
            }
        }
        public object LabelSet
        {
            get
            {
                return (object)this.GetValue(LabelSetProperty);
            }
            set
            {
                this.SetValue(LabelSetProperty, value);
            }
        }
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            //draw background color
            rectBkground.Fill = BackColor;

            if (DeviceData != null)
            {
                string format = "0.0";

                #region FeedBack

                //draw red board if mfc meets a warning
                rectBkground.Stroke = DeviceData.IsWarning ? Brushes.Orange : Brushes.Gray;
                rectBkground.Stroke = DeviceData.IsError ? Brushes.Red : Brushes.Gray;

                //draw reading value
                if (IsPercent)
                    labelValue.Text = (DeviceData.FeedBack * 100).ToString(format);
                else
                    labelValue.Text = DeviceData.FeedBack.ToString(format);
                
                labelValue.Foreground = DeviceData.IsWarning ? Brushes.Pink : Brushes.LightYellow;
                labelValue.Foreground = DeviceData.IsError ? Brushes.Red : Brushes.LightYellow;
                rectBkground.StrokeThickness = (DeviceData.IsWarning | DeviceData.IsError) ? 2 : 1;


                if (dialogBox != null)
                {
                    dialogBox.DeviceData = DeviceData;
                    dialogBox.DeviceData.InvokePropertyChanged();
                }

                #endregion

                #region SetPoint

                //draw red board if mfc meets a warning
                rectSetPoint.Stroke = DeviceData.IsWarning ? Brushes.Orange : Brushes.Gray;
                rectBkground.Stroke = DeviceData.IsError ? Brushes.Red : Brushes.Gray;

                ////draw reading value
                if (IsPercent)
                    //  LabelSet = (DeviceData.SetPoint * 100).ToString("F1");
                    labelSetPoint.Text = (DeviceData.SetPoint * 100).ToString(format);
                else
                    //LabelSet = (object)DeviceData.SetPoint.ToString("F1");
                    labelSetPoint.Text = DeviceData.SetPoint.ToString(format);

                //VerticalContentAlignment = "Center" HorizontalContentAlignment = "Center"
                labelSetPoint.Foreground = DeviceData.IsWarning ? Brushes.Pink : Brushes.LightYellow;
                labelValue.Foreground = DeviceData.IsError ? Brushes.Red : Brushes.LightYellow;
                rectSetPoint.StrokeThickness = (DeviceData.IsWarning | DeviceData.IsError) ? 2 : 1;

                switch (DeviceData.SetMode) //Normal = 0,Close = 1,Open = 2,Hold = 3
                {
                    case 0:
                        EllipseState.Fill = Brushes.Green;
                        break;
                    case 1:
                        EllipseState.Fill = Brushes.LightGray;
                        break;
                    case 2:
                        EllipseState.Fill = Brushes.LawnGreen;
                        break;
                    case 3:
                        EllipseState.Fill = Brushes.DodgerBlue;
                        break;

                    default:
                        EllipseState.Fill = Brushes.Green;
                        break;
                }

                #endregion
            }
        }

        private MfcSettingDialogViewModel dialogBox;

        public Window AnalogOwner { get; set; }

        private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
          
                if (DeviceData == null)
                    return;

                if (HideDialog)
                    return;

            if (DeviceData.ActMode != (double)MfcCtrlMode.Normal)
            {
                MessageBox.Show("Not normal mode,Click mouse right buttom to change!");
                return;
            }
            //dialogBox = new InputDialogBox
            //{
            //    CommandDelegate = Execute,
            //    DeviceName = string.Format("{0}: {1}", DeviceData.Type, DeviceData.DisplayName),
            //    DeviceId = DeviceData.DeviceSchematicId,
            //    DefaultValue = DeviceData.DefaultValue,
            //    RealValue = DeviceData.FeedBack.ToString("F1"),
            //    SetPoint = Math.Round(DeviceData.SetPoint, 1),
            //    MaxValue = DeviceData.Scale,
            //    Unit = DeviceData.Unit,
            //};

            //dialogBox.IsPercent = IsPercent;
            //if (IsPercent)
            //    dialogBox.SetPoint = Math.Round(DeviceData.SetPoint * 100.0, 1);
            //if (AnalogOwner != null)
            //    dialogBox.Owner = AnalogOwner;
            //dialogBox.Topmost = true;
            //dialogBox.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            //dialogBox.FocasAll();
            //dialogBox.ShowDialog();

            //dialogBox = null;

            dialogBox = new MfcSettingDialogViewModel($"MFC {DeviceData.DisplayName} Setting");
            dialogBox.DeviceData = DeviceData;
            dialogBox.InputSetPoint = DeviceData.SetPoint.ToString("F1");

            WindowManager wm = new WindowManager();

            Window owner = Application.Current.MainWindow;
            if (owner != null)
            {
                Mouse.Capture(owner);
                Point pointToWindow = Mouse.GetPosition(owner);
                Point pointToScreen = owner.PointToScreen(pointToWindow);
                pointToScreen.X = pointToScreen.X + 50;
                pointToScreen.Y = pointToScreen.Y - 150;
                Mouse.Capture(null);

                //wm.ShowDialog(dialogBox, pointToScreen);
                wm.ShowDialog(dialogBox);
            }
            else
            {
                wm.ShowDialog(dialogBox);
            }

        }

        #region MouseRightButton
        private void Grid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            ContextMenu mouseClickMenu = new ContextMenu();
            MenuItem item = new MenuItem();
            item.Header = "_" + DeviceData.DeviceName;
            item.IsEnabled = false;
            mouseClickMenu.Items.Add(item);
            addNormalMenu(mouseClickMenu, item);
            addCloseMenu(mouseClickMenu, item);
            addOpenMenu(mouseClickMenu, item);
            addHoldMenu(mouseClickMenu, item);

            mouseClickMenu.IsOpen = true;
        }

        void addNormalMenu(ContextMenu mouseClickMenu, MenuItem item)
        {
            item = new MenuItem();
            item.Header = "Normal";
            item.Click += NormalMode;
            item.Tag = this.Tag;
            mouseClickMenu.Items.Add(item);
        }

        private void NormalMode(object sender, RoutedEventArgs e)
        {
            SetNormalMode(MfcCtrlMode.Normal);
        }

        void addCloseMenu(ContextMenu mouseClickMenu, MenuItem item)
        {
            item = new MenuItem();
            item.Header = "Close";
            item.Click += CloseMode;
            item.Tag = this.Tag;
            mouseClickMenu.Items.Add(item);
        }

        private void CloseMode(object sender, RoutedEventArgs e)
        {
            SetCloseMode(MfcCtrlMode.Close);
        }

        void addOpenMenu(ContextMenu mouseClickMenu, MenuItem item)
        {
            item = new MenuItem();
            item.Header = "Open";
            item.Click += OpenMode;
            item.Tag = this.Tag;
            mouseClickMenu.Items.Add(item);
        }

        private void OpenMode(object sender, RoutedEventArgs e)
        {
            SetOpenMode(MfcCtrlMode.Open);
        }

        void addHoldMenu(ContextMenu mouseClickMenu, MenuItem item)
        {
            item = new MenuItem();
            item.Header = "Hold";
            item.Click += HoldMode;
            item.Tag = this.Tag;
            mouseClickMenu.Items.Add(item);
        }

        private void HoldMode(object sender, RoutedEventArgs e)
        {
            SetHoldMode(MfcCtrlMode.Hold);
        }

        private void SetNormalMode(MfcCtrlMode value)
        {

            InvokeClient.Instance.Service.DoOperation($"{DeviceData.Module}.{DeviceData.DeviceName}.SetMode", value.ToString());

        }

        private void SetCloseMode(MfcCtrlMode value)
        {
            InvokeClient.Instance.Service.DoOperation($"{DeviceData.Module}.{DeviceData.DeviceName}.SetMode", value.ToString());

        }

        private void SetOpenMode(MfcCtrlMode value)
        {
            InvokeClient.Instance.Service.DoOperation($"{DeviceData.Module}.{DeviceData.DeviceName}.SetMode", value.ToString());

        }

        private void SetHoldMode(MfcCtrlMode value)
        {
            InvokeClient.Instance.Service.DoOperation($"{DeviceData.Module}.{DeviceData.DeviceName}.SetMode", value.ToString());

        }
        #endregion


        private void Execute(double value)
        {
            Command.Execute(new object[] {DeviceData.UniqueName, OperationName, value });
        }


        private void Grid_MouseEnter(object sender, MouseEventArgs e)
        {
            string format = "0.0";
            if (DeviceData != null)
            {
                string tooltipValue =
                    string.Format("{0}：{1}\r\n\r\nID：{2}\r\nScale：{3} {4}\r\nSetPoint：{5} {4} \r\nFeedback：{6} {4}\r\nTolerance：{7}%\r\nStatus：{8}",
                        DeviceData.Type,
                        DeviceData.DisplayName,
                        DeviceData.DeviceSchematicId,
                        DeviceData.Scale,
                        DeviceData.Unit,
                        IsPercent ? (DeviceData.SetPoint * 100).ToString(format) + "%" : DeviceData.SetPoint.ToString(format),
                        IsPercent ? (DeviceData.FeedBack * 100).ToString(format) + "%" : DeviceData.FeedBack.ToString(format),
                        DeviceData.Scale > 0 ? ((DeviceData.FeedBack - DeviceData.SetPoint) / DeviceData.Scale * 100).ToString(format) : "0",
                        DeviceData.IsWarning ? "Tolerance Warning" : "Normal") ;

                ToolTip = tooltipValue;
            }

            if (DeviceData != null)
            {
                string tooltipValue =
                    $"{DeviceData.Type}：{DeviceData.DisplayName}\r\n\r\nID：{DeviceData.DeviceSchematicId}\r\nScale：{DeviceData.Scale} {DeviceData.Unit}\r\nSetPoint：{DeviceData.SetPoint.ToString(format)} {DeviceData.Unit} \r\nFeedback：{DeviceData.FeedBack.ToString(format)} {DeviceData.Unit}";

                ToolTip = tooltipValue;
            }
        }
    }
}
