using FLY.ControlLibrary;
using FLY.Thick.BulkDataModule;
using FLY.UI.Module;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
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 ThickTcpUiInWindow.UIModule
{
    /// <summary>
    /// ScanGraph.xaml 的交互逻辑
    /// </summary>
    public partial class ScanGraph : Page
    {
        ScanGraphItemParam graphparam;
        public ScanGraph()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        public void Init(int id)
        {
            //查找参数
            graphparam = ScanGraphParams.Current.Items.Find(p => p.ID == id);
            if (graphparam == null)
            {
                graphparam = new ScanGraphItemParam() { ID = id };
                ScanGraphParams.Current.Items.Add(graphparam);
                ScanGraphParams.Current.Save();
            }

            //获取设备
            TDGage gage = Application.Current.Properties["Gage"] as TDGage;


            GraphScan graph = graphscan;
            Misc.BindingOperations.SetBinding(graphparam, "ChartType", () =>
            {
                if (graphparam.ChartType == "Line")
                    graph.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                else
                    graph.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
            });

            graph.DataContext = graphparam;
            //graph.SetValue(GraphScan.MarginProperty, new Thickness(5));
            graph.SetBinding(GraphScan.TitleProperty, new Binding("Title"));
            graph.SetBinding(Grid.ColumnProperty, new Binding("Column"));
            graph.SetBinding(Grid.RowProperty, new Binding("Row"));
            graph.SetBinding(Grid.ColumnSpanProperty, new Binding("ColumnSpan"));
            graph.SetBinding(Grid.RowSpanProperty, new Binding("RowSpan"));
            graph.SetBinding(GraphScan.IsAutoTargetProperty, new Binding("IsAutoTarget"));
            graph.SetBinding(GraphScan.IsPercentProperty, new Binding("IsPercent"));
            graph.SetBinding(GraphScan.YRangePercentProperty, new Binding("YRangePercent"));

            graph.SetBinding(GraphScan.IsReversedProperty, new Binding("IsReversed") { Source = ScanGraphParams.Current });
            graph.SetBinding(GraphScan.LeftRightIsVisableProperty, new Binding("LRIsVisable") { Source = ScanGraphParams.Current });
            graph.SetBinding(GraphScan.LeftRightIsReversedProperty, new Binding("LRIsReversed") { Source = ScanGraphParams.Current });



            //报警线
            {
                graph.SetBinding(GraphScan.HasCtrlLineProperty, new Binding("Enable") { Source = gage.mScanWarningService });
                Binding b0 = new Binding("Alarm") { Source = gage.mDynAreaService.mDynArea };
                Binding b1 = new Binding("AlarmLine") { Source = gage.mScanWarningService };
                {
                    MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay, Converter = new CtrlLineConverter() };
                    mb.Bindings.Add(b0);
                    mb.Bindings.Add(b1);
                    graph.SetBinding(GraphScan.CtrlLineProperty, mb);
                }
            }

            {
                graph.SetBinding(GraphScan.FirstBoltNoProperty, new Binding("FirstBoltNo") { Source = gage.mDynAreaService.mDynArea });

                //graph.SetValue(GraphScan.FirstIndexProperty, 0);
                //graph.SetBinding(GraphScan.LastIndexProperty, new Binding("NBolts") { Source = gage.mDynArea });

                Binding b0 = new Binding("FirstBoltNo") { Source = gage.mDynAreaService.mDynArea };
                Binding b1 = new Binding("DataBoltNoBegin") { Source = gage.mDynAreaService.mDynArea };
                Binding b2 = new Binding("DataBoltNoEnd") { Source = gage.mDynAreaService.mDynArea };
                Binding b3 = new Binding("ScanBoltNoBegin") { Source = gage.mDynAreaService.mDynArea };
                Binding b4 = new Binding("ScanBoltNoEnd") { Source = gage.mDynAreaService.mDynArea };

                {
                    MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay, Converter = new ThickTcpUiInWindow.Converter.BoltNo2BoltIndexConverter() };
                    mb.Bindings.Add(b0);
                    mb.Bindings.Add(b1);
                    graph.SetBinding(GraphScan.DataFirstProperty, mb);
                }

                {
                    MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay, Converter = new ThickTcpUiInWindow.Converter.BoltNo2BoltIndexConverter() };
                    mb.Bindings.Add(b0);
                    mb.Bindings.Add(b2);
                    graph.SetBinding(GraphScan.DataLastProperty, mb);
                }

                {
                    MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay, Converter = new ThickTcpUiInWindow.Converter.BoltNo2BoltIndexConverter() };
                    mb.Bindings.Add(b0);
                    mb.Bindings.Add(b3);
                    graph.SetBinding(GraphScan.FirstIndexProperty, mb);
                }

                {
                    MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay, Converter = new ThickTcpUiInWindow.Converter.BoltNo2BoltIndexConverter() };
                    mb.Bindings.Add(b0);
                    mb.Bindings.Add(b4);
                    graph.SetBinding(GraphScan.LastIndexProperty, mb);
                }
            }

            graph.SetBinding(GraphScan.TargetProperty, new Binding("Target") { Source = gage.mDynAreaService.mDynArea });
            graph.SetBinding(GraphScan.AlarmProperty, new Binding("Alarm") { Source = gage.mDynAreaService.mDynArea });


            //bulkdata 数据绑定!!!
            BulkDataServiceClientAdv.BulkDataGraphFrame bulkdata_client = new BulkDataServiceClientAdv.BulkDataGraphFrame();
            //graphparam 绑定到 bulkdataclient
            Misc.BindingOperations.SetBinding(graphparam, "BM", bulkdata_client, "BM");
            Misc.BindingOperations.SetBinding(graphparam, "Mix", bulkdata_client, "Mix");


            graph.SetBinding(GraphScan.Title2Property, new Binding("Info") { Source = bulkdata_client });
            graph.SetBinding(GraphScan.IsValidProperty, new Binding("Type") { Source = bulkdata_client, Converter = new IsValidConverter() });
            graph.DataSource = bulkdata_client.Frame;


            graph.ShowSettingDialogEvent += new EventHandler(delegate (object sender, EventArgs e)
            {
                ScanGraphConfig window = new ScanGraphConfig();
                window.Init((sender as GraphScan).DataContext as ScanGraphItemParam);
                window.Owner = FLY.ControlLibrary.COMMON.GetWindow(graph);
                window.ShowDialog();
            });

            //BulkDataServiceClientAdv mBulkDataClient;
            //if(mBulkDataClients.ContainsKey(graphparam.BulkData))
            //    mBulkDataClient = mBulkDataClients[graphparam.BulkData];
            //else
            //    mBulkDataClient = mBulkDataClients.First().Value;

            gage.mBulkDataClient.Add(bulkdata_client);
        }
    }
    /// <summary>
    /// 扫描图的参数
    /// </summary>
    public class ScanGraphItemParam : UIModuleParam
    {

        private string _charttype = "Column";
        /// <summary>
        /// 曲线类型
        /// </summary>
        public string ChartType
        {
            get
            {
                return _charttype;
            }
            set
            {
                _charttype = value;

                NotifyPropertyChanged("ChartType");
            }
        }
        private int bm = 0;
        /// <summary>
        /// 记录点
        /// </summary>
        public int BM
        {
            get
            {
                return bm;
            }
            set
            {
                if (bm != value)
                {
                    bm = value;
                    NotifyPropertyChanged("BM");
                }
            }
        }

        private double _yrangepercent = 3;
        /// <summary>
        /// Y轴比例
        /// </summary>
        public double YRangePercent
        {
            get
            {
                return _yrangepercent;
            }
            set
            {
                _yrangepercent = value;
                NotifyPropertyChanged("YRangePercent");
            }
        }

        private string title = "扫描图";
        /// <summary>
        /// 标题
        /// </summary>
        public string Title
        {
            get { return title; }
            set
            {
                if (title != value)
                {
                    title = value;
                    NotifyPropertyChanged("Title");
                }
            }
        }

        private int mix = 1;
        /// <summary>
        /// 混合图
        /// </summary>
        public int Mix
        {
            get
            {
                return mix;
            }
            set
            {
                if (mix != value)
                {
                    mix = value;
                    NotifyPropertyChanged("Mix");
                }
            }
        }


        private bool isautotarget = false;
        /// <summary>
        /// 自动目标值
        /// </summary>
        public bool IsAutoTarget
        {
            get
            {
                return isautotarget;
            }
            set
            {
                if (isautotarget != value)
                {
                    isautotarget = value;
                    NotifyPropertyChanged("IsAutoTarget");
                }
            }
        }

        private bool ispercent = false;
        /// <summary>
        /// % 显示
        /// </summary>
        public bool IsPercent
        {
            get
            {
                return ispercent;
            }
            set
            {
                if (ispercent != value)
                {
                    ispercent = value;
                    NotifyPropertyChanged("IsPercent");
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string[] GetSavePropertyNames()
        {
            List<string> names = new List<string>(base.GetSavePropertyNames());
            names.AddRange(new string[]{
                "Title",
                "ChartType",
                "BM",
                "Mix",
                "YRangePercent",
                "IsAutoTarget",
                "IsPercent"
            });
            return names.ToArray();
        }
    }
    /// <summary>
    /// 全部扫描图的参数
    /// </summary>
    public class ScanGraphParams : UIModuleParams<ScanGraphItemParam>
    {
        bool isreverserd = false;
        /// <summary>
        /// 主界面反向 
        /// </summary>
        public bool IsReversed
        {
            get { return isreverserd; }
            set
            {

                if (isreverserd != value)
                {
                    isreverserd = value;
                    NotifyPropertyChanged("IsReversed");
                }
            }
        }

        bool lrisvisable = false;
        /// <summary>
        /// 显示 左右标示
        /// </summary>
        public bool LRIsVisable
        {
            get { return lrisvisable; }
            set
            {

                if (lrisvisable != value)
                {
                    lrisvisable = value;
                    NotifyPropertyChanged("LRIsVisable");
                }
            }
        }

        bool lrisreverserd = false;
        /// <summary>
        /// 左右标示 反向
        /// </summary>
        public bool LRIsReversed
        {
            get { return lrisreverserd; }
            set
            {

                if (lrisreverserd != value)
                {
                    lrisreverserd = value;
                    NotifyPropertyChanged("LRIsReversed");
                }
            }
        }

        private int xInterval = 10;
        /// <summary>
        /// 扫描图轴间隔 ,单位分区
        /// </summary>
        public int XInterval
        {
            get { return xInterval; }
            set
            {

                if (xInterval != value)
                {
                    xInterval = value;
                    NotifyPropertyChanged("XInterval");
                }
            }
        }
        static ScanGraphParams()
        {
            Misc.SaveToXmlHepler.Regist(typeof(ScanGraphParams));
        }
        public ScanGraphParams()
        {
            string path = System.IO.Path.Combine(FLYLayout.BasePath, "scangraph.xml");
            FilePath = path;
        }

        static ScanGraphParams current = null;
        public static ScanGraphParams Current
        {
            get
            {
                if (current == null)
                {
                    current = new ScanGraphParams();
                    current.Load();
                }
                return current;
            }
        }


        public override string[] GetSavePropertyNames()
        {
            List<string> names = new List<string>(base.GetSavePropertyNames());
            names.AddRange(new string[]{
                "IsReversed",
                "LRIsVisable",
                "LRIsReversed",
                "XInterval"
            });
            return names.ToArray();
        }
    }


    /// <summary>
    /// 扫描图控件模块
    /// </summary>
    public class UIModule_ScanGraph : IUIModule
    {

        /// <summary>
        /// 控件标题
        /// 它的值取决于culture
        /// </summary>
        public string Title
        {
            get
            {
                return Application.Current.FindResource("strScanGraph") as string;
            }
        }

        /// <summary>
        /// 控件
        /// 创建时,需要给它唯一ID,让加载自己的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FrameworkElement GetComponent(int id)
        {
            ScanGraph graph = new ScanGraph();
            graph.Init(id);
            return graph;
        }

        /// <summary>
        /// 控件缩略图,用于编辑界面时,大致看看
        /// 创建时,需要给它唯一ID,让加载自己的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FrameworkElement GetThumbnail(int id)
        {
            return new Grid();
        }

        /// <summary>
        /// 给出全部控件ID, 控件自行删除没有的参数
        /// </summary>
        /// <param name="IDs"></param>
        public void MatchParam(int[] IDs)
        {
            ScanGraphParams.Current.MatchParam(IDs);
        }
    }


    public class IsValidConverter : IValueConverter
    {

        #region IValueConverter 成员

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            FR_DATA_TYPE type = (FR_DATA_TYPE)value;
            if (type == FR_DATA_TYPE.VALID)
                return true;
            else
                return false;

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

    }
    public class CtrlLineConverter : IMultiValueConverter
    {


        /// <summary>
        /// values[0] = int alarm, values[1] = double alarmline
        /// </summary>
        /// <param name="values"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values.Count() != 2)
                return null;

            if ((!(values[0] is int)) || (!(values[1] is double)))
                return null;

            int alarm = (int)values[0];
            double alarmline = (double)values[1];
            return (int)(alarm * alarmline);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}