using Advantech.Motion;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ProductionControl.Device;
using ProductionControl.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static ProductionControl.Device.AxisDev; 

namespace ProductionControl.UI
{
    /// <summary>
    /// 非设备，无调试功能，仅做为工序配置用
    /// </summary>
    public partial class UIAxisDevTag : UserControl
    {
        SynchronizationContext SyncContext = null;
         
        public Action<string> GetParamsEvent;
        //
        private AxisDevTagProp prop = new AxisDevTagProp();
        //private AxisDev dev; 
        
        public UIAxisDevTag()
        {
            InitializeComponent();
            propertyGrid1.PropertyValueChanged += propertyGrid1_PropertyValueChanged;
            //refreshUIState();
            //获取UI线程同步上下文
            SyncContext = SynchronizationContext.Current;
            //init(); 
        }
        //private void refreshUIState()
        //{
        //    foreach (ToolStripItem item in this.toolStrip1.Items)
        //    {
        //        if (item.Text == "打开设备")
        //            item.Visible = (dev == null || !dev.IsInit);
        //        else
        //            this.propertyGrid1.Enabled=item.Enabled = !(dev == null || !dev.IsInit);
        //    }
        //}
        public string getParamsData()
        {
            return prop.serialize();
        }
         
        public void setParamsData(string json)
        {
            if (json == "") return;
            prop.deserialize(json);
            this.propertyGrid1.Refresh();
        }
        public void init()
        {
            this.propertyGrid1.SelectedObject = prop;
           

            //refreshAxisVelParam();
            //refreshUIState(); 
        }
        private void refreshUI()
        {
            SyncContext.Post(m =>
            {
                var result = m as string;
                propertyGrid1.Refresh(); 
            }, "异步操作完成结果"); 
        }
        //private void refreshAxisVelParam()
        //{
        //    int axisIndex = (int)prop.AxisIndex; 
        //    //prop.HomeMode = (AxitHomeMode)Config.Axis_HomeMode[axisIndex];

        //    var values = dev.getAxisVelParam(axisIndex);
        //    prop.VelLow = dev.tomm(values[0], Config.Axis_MM2PulseNum[axisIndex]);
        //    prop.VelHigh = dev.tomm(values[1], Config.Axis_MM2PulseNum[axisIndex]);
        //    prop.Acc = dev.tomm(values[2], Config.Axis_MM2PulseNum[axisIndex]);
        //    prop.Dec = dev.tomm(values[3], Config.Axis_MM2PulseNum[axisIndex]);
        //} 

        protected override void OnHandleDestroyed(EventArgs e) 
        {
            base.OnHandleDestroyed(e);
            // 在此添加需要手动释放资源的代码
            //this.closeDev();
        }

        private void tbtnRun_Click(object sender, EventArgs e)
        {
            try
            {  
                //running...
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } 
        }

        private void tbtnExport_Click(object sender, EventArgs e)
        {
            string filePath = FileUtil.saveAsFile($"AxisSize_{prop.SizeTag}配置.json", "JSON|*.json");
            if (filePath != "")
            {
                string jsonText = prop.serialize();
                File.WriteAllText(filePath, jsonText);
                MessageBox.Show("保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void tbtnImport_Click(object sender, EventArgs e)
        {
            string filePath = FileUtil.selectFile("JSON|*.json");
            if (filePath != "")
            {
                string jsonText = File.ReadAllText(filePath);
                prop.deserialize(jsonText);
                this.propertyGrid1.Refresh();
            }
        } 

        private void tbtnStop_Click(object sender, EventArgs e)
        { 
        }
 

        private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            //其中包含了两个重要的属性：OldValue和ChangeItem。
            //ChangeItem是“PropertyDescriptorGridEntry”类型。一般可以通过ChangeItem.PropertyDescriptor.ComponentType查找到属性的实际类型。 
            //而通过ChangeItem的Label，则可以查看到当前在属性编辑输入框中显示的值。  

            string className = e.ChangedItem.PropertyDescriptor.ComponentType.Name;
            string propertyName = e.ChangedItem.PropertyDescriptor.Name;
            var oldValue = e.OldValue;
            var newValue = e.ChangedItem.Value;
            switch (propertyName)
            {
                 
            }
        }

        private void tbtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (prop.SizeTag.Trim() == "")
                    throw new Exception("请设置尺寸测量引用标识！");

                GetParamsEvent?.Invoke(prop.serialize());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbtnOpenDev_Click(object sender, EventArgs e)
        {
            this.init();
        }
    }
}
