using CowainHmi.UIEditor;
using PCHMI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CowainHmi
{
    public partial class AxisDebug : UserControl
    {
        private string axisIdAddr = "";
        [Category("PCHMI"), Description("轴编号地址")]
        public string AxisIdAddr
        {
            get
            {
                return axisIdAddr;
            }
            set
            {
                axisIdAddr = value;
            }
        }

        private string dataAddr = "";
        [Category("PCHMI"), Description("轴控制DB地址")]
        public string DataAddr
        {
            get
            {
                return dataAddr;
            }
            set
            {
                dataAddr = value;
            }
        }

        private string torqueAddr = "";
        [Category("PCHMI"), Description("轴扭矩DB地址")]
        public string TorqueAddr
        {
            get
            {
                return torqueAddr;
            }
            set
            {
                torqueAddr = value;
            }
        }

        private string errAddr = "";
        [Category("PCHMI"), Description("轴错误DB地址")]
        public string ErrAddr
        {
            get
            {
                return errAddr;
            }
            set
            {
                errAddr = value;
            }
        }

        private string paramAddr = "";
        [Category("PCHMI"), Description("轴参数DB地址")]
        public string ParamAddr
        {
            get
            {
                return paramAddr;
            }
            set
            {
                paramAddr = value;
            }
        }

        private string posAddr = "";
        [Category("PCHMI"), Description("点位DB地址")]
        public string PosAddr
        {
            get
            {
                return posAddr;
            }
            set
            {
                posAddr = value;
            }
        }


        private string axisConfig = "S1";

        [Browsable(true)]
        [Category("PCHMI"), Description("轴配置")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Editor(typeof(UIAxisConfigEdit), typeof(UITypeEditor))]
        public string AxisConfig
        {
            get
            {
                return axisConfig;
            }
            set
            {
                axisConfig = value;
            }
        }



        private int id = 0;
        private int posId = 0;
        private string axisName = "";
        private List<string> posNames = new List<string>();
        private DataTable table;
        public AxisDebug()
        {
            InitializeComponent();
        }

        private void SetAddress()
        {
            //id = PCHMI.VL.GET_UINT16(0, AxisIdAddr) - 1;//读轴编号
            //if (id < 0)
            //{
            //    PCHMI.RT.SEND_UINT16(0, AxisIdAddr, 1);
            //    id = 0;
            //}
            id = this.cbxAxisSel.SelectedIndex;
            axisName = $"轴{id + 1}";  //默认轴名称
            if (table != null)
            {
                DataRow row = table.Select($"轴号='{id + 1}'").FirstOrDefault();
                if (row != null)
                {
                    axisName = row["轴名称"].ToString();
                    for (int i = 0; i < 32; i++)
                    {
                        posNames[i] = row[$"位置名称{i}"].ToString();
                    }
                }
            }
            this.cbxPosSelect.DataSource = null;
            List<string> list = new List<string>();
            int idx = 0;
            foreach (var item in posNames)
            {
                list.Add($"{idx}-{item}");
                idx++;
            }
            this.cbxPosSelect.DataSource = list;
            this.btnEnable.开关功能.地址[0] = $"{DataAddr}.{id * 60}.6";
            this.btnEnable.开关功能.地址[1] = $"{DataAddr}.{id * 60 + 4}";
            this.btnEnable.开关功能.扩展[1] = "0";
            this.btnEnable.指示灯地址 = $"{DataAddr}.{id * 60}.6";
            this.btnHome.指示灯地址 = $"{DataAddr}.{id * 60}.2";
            this.lblEnable.指示灯地址 = $"{DataAddr}.{id * 60 + 36}.4";
            this.lblRef.指示灯地址 = $"{DataAddr}.{id * 60 + 36}.0";
            this.lblErr.指示灯地址 = $"{ErrAddr}.{id * 2 + 0}.2";
            this.lblAutoMode.指示灯地址 = $"{DataAddr}.{id * 60 + 37}.1";
            this.lblJogAddSafe.指示灯地址 = $"{DataAddr}.{id * 60 + 0}.7";
            this.lblJogDecSafe.指示灯地址 = $"{DataAddr}.{id * 60 + 1}.0";

            this.btnJogAdd.指示灯地址 = $"{DataAddr}.{id * 60 + 4}";
            this.btnJogDec.指示灯地址 = $"{DataAddr}.{id * 60 + 4}";

            this.btnJogSafe.开关功能.地址[0] = $"{DataAddr}.{id * 60 + 1}.1";
            this.btnJogSafe.监控地址 = $"{DataAddr}.{id * 60 + 1}.1";
            this.txtActPos.监控地址 = $"{DataAddr}.{id * 60 + 24}";
            this.txtActVel.监控地址 = $"{DataAddr}.{id * 60 + 20}";
            this.txtErrCode.监控地址 = $"{DataAddr}.{id * 60 + 42}";
            this.txtTipCode.监控地址 = $"{DataAddr}.{id * 60 + 44}";
            this.txtManualV.监控地址 = $"{ParamAddr}.{id * 38 + 6}";
            this.txtAutoV.监控地址 = $"{ParamAddr}.{id * 38 + 8}";
            this.txtAcc.监控地址 = $"{ParamAddr}.{id * 38 + 10}";
            this.txtDec.监控地址 = $"{ParamAddr}.{id * 38 + 12}";
            this.txtLockPos.监控地址 = $"{DataAddr}.{id * 60 + 28}";
            this.lblAxisLock.指示灯地址 = $"{ErrAddr}.{id * 2}.4";
            this.btnUnlock.开关功能.地址[0] = $"{DataAddr}.{id * 60 + 1}.2";
            this.btnUnlock.监控地址 = $"{DataAddr}.{id * 60 + 1}.2";

            this.btnGoLock.监控地址 = $"{DataAddr}.{id * 60 + 4}";
            this.lblInPos.指示灯地址 = $"{DataAddr}.{id * 60 + 56 + posId / 8}.{posId % 8}";  //点位到位指示
            this.txtTargetPos.监控地址 = $"{PosAddr}.{id * 384 + posId * 12}";
            this.txtTargetVel.监控地址 = $"{PosAddr}.{id * 384 + posId * 12 + 8}";
            this.lblGoSafe.指示灯地址 = $"{DataAddr}.{id * 60 + 6 + posId / 8}.{posId % 8}";  //点位安全指示
            this.btnGoSafe.开关功能.地址[0] = $"{DataAddr}.{id * 60 + 10 + posId / 8}.{posId % 8}";  //安全解锁
            this.btnGoSafe.监控地址 = $"{DataAddr}.{id * 60 + 10 + posId / 8}.{posId % 8}";

            this.btnGoto.监控地址 = $"{DataAddr}.{id * 60 + 4}";
            this.lblPosUnit1.监控地址 = $"{ParamAddr}.{id * 38 + 14}";
            this.lblPosUnit2.监控地址 = $"{ParamAddr}.{id * 38 + 14}";
            this.lblGotoUnit.监控地址 = $"{ParamAddr}.{id * 38 + 14}";
            this.lblActVelUnit.监控地址 = $"{ParamAddr}.{id * 38 + 14}";
            this.标签2.监控地址 = $"{ParamAddr}.{id * 38 + 14}";
            this.txtSetTorque.监控地址 = $"{TorqueAddr}.{id * 26 + 16}";
            this.txtActTorque.监控地址 = $"{TorqueAddr}.{id * 26 + 20}";
            this.lblTorqueLight.指示灯地址 = $"{TorqueAddr}.{id * 26 + 24}.0";

            this.lblErrBit1.指示灯地址 = $"{DataAddr}.{id * 60 + 46}.1";
            this.lblErrBit4.指示灯地址 = $"{DataAddr}.{id * 60 + 46}.4";
            this.lblErrBit5.指示灯地址 = $"{DataAddr}.{id * 60 + 46}.5";
            this.lblErrBit7.指示灯地址 = $"{DataAddr}.{id * 60 + 46}.7";
        }
        private void OpenFile(string fileName)
        {
            string text = Application.StartupPath + $"\\DATA\\{fileName}.csv";
            if (File.Exists(text))
            {
                table = CSV.OpenCSV(text);
            }
        }

        private void AxisDebug_Load(object sender, EventArgs e)
        {
            if (PCHMI.PClass.SystemRun)
            {
                for (int i = 0; i < 32; i++)
                {
                    posNames.Add($"位置{i}");
                }
                OpenFile(AxisConfig);

                id = PCHMI.VL.GET_UINT16(0, AxisIdAddr) - 1;//读轴编号
                if (id < 0)
                {
                    PCHMI.RT.SEND_UINT16(0, AxisIdAddr, 1);
                    id = 0;
                }
                if (table != null)
                {
                    List<string> list = new List<string>();
                    foreach (DataRow row in table.Rows)
                    {
                        string name = row["轴名称"].ToString();
                        list.Add(name);
                    }
                    this.cbxAxisSel.DataSource = list;
                    this.cbxAxisSel.SelectedIndex = id;
                    this.cbxAxisSel.SelectedIndexChanged += CbxAxisSel_SelectedIndexChanged;
                    SetAddress();
                    this.cbxPosSelect.SelectedIndex = -1;
                    this.cbxPosSelect.SelectedIndexChanged += CbxPosSelect_SelectedIndexChanged;
                }

            }
        }

        private void CbxAxisSel_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetAddress();
        }

        private void CbxPosSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            //更改了点位
            posId = this.cbxPosSelect.SelectedIndex;
            this.lblInPos.指示灯地址 = $"{DataAddr}.{id * 60 + 56 + posId / 8}.{posId % 8}";  //点位到位指示
            this.txtTargetPos.监控地址 = $"{PosAddr}.{id * 384 + posId * 12}";
            this.txtTargetVel.监控地址 = $"{PosAddr}.{id * 384 + posId * 12 + 8}";
            this.lblGoSafe.指示灯地址 = $"{DataAddr}.{id * 60 + 6 + posId / 8}.{posId % 8}";  //点位安全指示
            this.btnGoSafe.开关功能.地址[0] = $"{DataAddr}.{id * 60 + 10 + posId / 8}.{posId % 8}";  //安全解锁
            this.btnGoSafe.监控地址 = $"{DataAddr}.{id * 60 + 10 + posId / 8}.{posId % 8}";
            this.btnGoto.开关功能.地址[0] = $"{DataAddr}.{id * 60 + 2}";  //手动定位到目标点位
            this.btnGoto.开关功能.扩展[0] = $"{100 + posId}";  //写入100-131
            this.btnGoto.监控地址 = $"{DataAddr}.{id * 60 + 4}";
        }

        private void txtAxisId_数值改变事件(数据显示器 sender)
        {
            SetAddress();
        }

        private void btnEnable_MouseDown(object sender, MouseEventArgs e)
        {
            PCHMI.OPTLOG.WLOG($"手动按下了轴使能按钮，Axis{id}-{axisName}");
        }



        private void btnJogSafe_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.btnJogSafe.Value == 0)
            {
                PCHMI.OPTLOG.WLOG($"手动解除了轴Jog保护，可能发生安全事故，Axis{id}-{axisName}");
            }
        }



        private void btnUnlock_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.btnUnlock.Value == 0)
            {
                PCHMI.OPTLOG.WLOG($"手动解除了轴连锁（清除了手动操作记忆），可能发生安全事故，Axis{id}-{axisName}");
            }

        }
        private void btnGoSafe_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.btnGoSafe.Value == 0)
            {
                PCHMI.OPTLOG.WLOG($"手动解除定位安全，Axis{id}-{axisName}，点位：{posId}");
            }

        }




        private void txtTargetPos_Enter(object sender, EventArgs e)
        {
            MessageBox.Show("不可以修改位置，请通过点位选择", "提示");
        }

        private void btnAxisPoss_MouseDown(object sender, MouseEventArgs e)
        {
            PCHMI.RT.SEND_UINT16(0, AxisIdAddr, (ushort)(id + 1));
            DlgAxisPosData dlg = new DlgAxisPosData(posNames, PosAddr, DataAddr, id, (int)this.lblPosUnit1.Value);
            dlg.ShowDialog();
        }
        #region JogAdd
        private async void btnJogAdd_MouseDown(object sender, MouseEventArgs e)
        {
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
            await Task.Delay(100);
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 1);
        }

        private async void btnJogAdd_MouseUp(object sender, MouseEventArgs e)
        {
            await Task.Delay(300);
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
        }
        #endregion

        #region JogDec
        private async void btnJogDec_MouseDown(object sender, MouseEventArgs e)
        {
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
            await Task.Delay(100);
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 2);
        }

        private async void btnJogDec_MouseUp(object sender, MouseEventArgs e)
        {
            await Task.Delay(300);
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
        }
        #endregion

        #region Home
        private async void btnHome_MouseDown(object sender, MouseEventArgs e)
        {
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
            await Task.Delay(200);
            PCHMI.OPTLOG.WLOG($"手动按下了轴回原点按钮，Axis{id}-{axisName}");
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 3);
        }

        private async void btnHome_MouseUp(object sender, MouseEventArgs e)
        {
            await Task.Delay(500);
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
        }
        #endregion
        #region Goto

        private async void btnGoto_MouseDown(object sender, MouseEventArgs e)
        {
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
            await Task.Delay(200);
            PCHMI.OPTLOG.WLOG($"手动触发了定位，定位目标点={posId + 1}，目标位置:{this.txtTargetPos.Value}，Axis{id}-{axisName}");
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", (short)(100 + posId));
        }
        private void btnGoto_MouseUp(object sender, MouseEventArgs e)
        {
            //PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
        }
        #endregion
        #region GotoLock

        private async void btnGoLock_MouseDown(object sender, MouseEventArgs e)
        {
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
            await Task.Delay(200);
            PCHMI.OPTLOG.WLOG($"手动触发了去连锁位置，Axis{id}-{axisName},连锁位置：{this.txtLockPos.Value}");
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 10);
        }
        private async void btnGoLock_MouseUp(object sender, MouseEventArgs e)
        {
            await Task.Delay(500);
            PCHMI.RT.SET_INT16(0, $"{DataAddr}.{id * 60 + 4}", 0);
        }
        #endregion

      


    }
}
