using CowainHmi.Properties;
using PCHMI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Resources;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;

namespace CowainHmi
{

    public partial class DlgAxisPosData : Form
    {
        private class PosData : INotifyPropertyChanged
        {
            private string setPos;
            private string setVel;
            private bool inPos;
            private bool safe;
            private bool safeLock;

            public string PosName { get; set; }
            public string SetPos
            {
                get => setPos;
                set
                {
                    setPos = value;
                    OnPropertyChanged("SetPos");
                }
            }
            public string SetVel
            {
                get => setVel;
                set
                {
                    setVel = value;
                    OnPropertyChanged("SetVel");
                }
            }
            public bool InPos
            {
                get => inPos;
                set
                {
                    inPos = value;
                    OnPropertyChanged("InPos");
                }
            }

            public bool Safe
            {
                get => safe;
                set
                {
                    safe = value;
                    OnPropertyChanged("Safe");
                }
            }

            public bool SafeLock
            {
                get => safeLock;
                set
                {
                    safeLock = value;
                    OnPropertyChanged("SafeLock");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;

            protected virtual void OnPropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private enum UnitType
        {
            mm,
            cm,
            m,
            deg,
            rad
        }
        private BindingList<PosData> list = new BindingList<PosData>();
        private int id;
        private int unit;
        private string posAddr;
        private string dataAddr;
        private List<string> posNames;
        public DlgAxisPosData(List<string> posNames, string posAddr, string dataAddr, int id, int unit)
        {
            InitializeComponent();
            this.id = id;
            this.posAddr = posAddr;
            this.dataAddr = dataAddr;
            this.posNames = posNames;
            this.unit = unit;
            for (int i = 0; i < posNames.Count; i++)
            {
                PosData data = new PosData { PosName = posNames[i] };
                list.Add(data);
            }
            this.dgvAxisPos.AutoGenerateColumns = false;
            this.dgvAxisPos.DataSource = list;

        }

        private async void DlgAxisPosData_Load(object sender, EventArgs e)
        {
            await GetPosData();
        }

        private async Task GetPosData()
        {
            for (int i = 0; i < list.Count; i++)
            {
                var pos = PCHMI.VL.GET_INT32(0, $"{posAddr}.{id * 384 + i * 12}");
                var vel = PCHMI.VL.GET_INT32(0, $"{posAddr}.{id * 384 + i * 12 + 8}");
                var inPos = PCHMI.VL.GET_BIT(0, $"{dataAddr}.{id * 60 + 56 + i / 8}.{i % 8}");
                var safe = PCHMI.VL.GET_BIT(0, $"{dataAddr}.{id * 60 + 10 + i / 8}.{i % 8}");
                var safeLock = PCHMI.VL.GET_BIT(0, $"{dataAddr}.{id * 60 + 6 + i / 8}.{i % 8}");
            }
            await Task.Delay(300);
            for (int i = 0; i < list.Count; i++)
            {
                var pos = PCHMI.VL.GET_INT32(0, $"{posAddr}.{id * 384 + i * 12}");
                var vel = PCHMI.VL.GET_INT32(0, $"{posAddr}.{id * 384 + i * 12 + 8}");
                var inPos = PCHMI.VL.GET_BIT(0, $"{dataAddr}.{id * 60 + 56 + i / 8}.{i % 8}");
                var safe = PCHMI.VL.GET_BIT(0, $"{dataAddr}.{id * 60 + 10 + i / 8}.{i % 8}");
                var safeLock = PCHMI.VL.GET_BIT(0, $"{dataAddr}.{id * 60 + 6 + i / 8}.{i % 8}");
                list[i].SetPos = $"{((double)pos / 100.0).ToString("F2")} {(UnitType)unit}";
                list[i].SetVel = $"{vel} {(UnitType)unit}/s";
                list[i].InPos = inPos > 0 ? true : false;
                list[i].Safe = safe > 0 ? true : false;
                list[i].SafeLock = safeLock > 0 ? true : false;
            }
        }


        private async void dgvAxisPos_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((e.ColumnIndex == this.dgvAxisPos.Columns["Edit"].Index || e.ColumnIndex == this.dgvAxisPos.Columns["SetPos"].Index || e.ColumnIndex == this.dgvAxisPos.Columns["SetVel"].Index) && e.RowIndex >= 0)
            {
                DlgPosEdit dlg = new DlgPosEdit(posNames[e.RowIndex], posAddr, id, e.RowIndex, unit);
                var result = dlg.ShowDialog();
                if (result == DialogResult.OK)
                {
                    await GetPosData();
                }
            }
            else if (e.ColumnIndex == this.dgvAxisPos.Columns["Teach"].Index && e.RowIndex >= 0)
            {
                //按下示教按钮,将轴当前位置设置为目标位置
                var actPos = PCHMI.VL.GET_INT32(0, $"{dataAddr}.{id * 60 + 24}");
                PCHMI.RT.SEND_INT32(0, $"{posAddr}.{id * 384 + e.RowIndex * 12}", actPos);
                PCHMI.OPTLOG.WLOG($"手动按下了点位示教按钮，Axis{id}，点位号：{e.RowIndex},原位置:{list[e.RowIndex].SetPos},新位置:{actPos}");
                await GetPosData();
            }
            else if (e.ColumnIndex == this.dgvAxisPos.Columns["Goto"].Index && e.RowIndex >= 0)
            {
                //按下Goto按钮
                PCHMI.RT.SEND_INT16(0, $"{dataAddr}.{id * 60 + 4}", 0);
                await Task.Delay(200);
                var actPos = PCHMI.VL.GET_INT32(0, $"{dataAddr}.{id * 60 + 24}");
                PCHMI.RT.SEND_INT16(0, $"{dataAddr}.{id * 60 + 4}", (short)(100 + e.RowIndex));
                PCHMI.OPTLOG.WLOG($"手动触发了定位按钮，Axis{id},点位号：{e.RowIndex}，定位前位置:{actPos},目标位置:{list[e.RowIndex].SetPos}");
            }
            else if (e.ColumnIndex == this.dgvAxisPos.Columns["Safe"].Index && e.RowIndex >= 0)
            {
                //按下解锁按钮
                bool isChecked = PCHMI.VL.GET_BIT(0, $"{dataAddr}.{id * 60 + 10 + e.RowIndex / 8}.{e.RowIndex % 8}") > 0 ? true : false;
                //DataGridViewCheckBoxCell chkBoxCell = (DataGridViewCheckBoxCell)dgvAxisPos.Rows[e.RowIndex].Cells[e.ColumnIndex];
                //bool isChecked = (bool)chkBoxCell.Value;
                if (isChecked)
                {
                    PCHMI.RT.SEND_BIT(0, $"{dataAddr}.{id * 60 + 10 + e.RowIndex / 8}.{e.RowIndex % 8}", 0);
                }
                else
                {
                    PCHMI.OPTLOG.WLOG($"手动触发解除安全，Axis{id},点位{e.RowIndex}");
                    PCHMI.RT.SEND_BIT(0, $"{dataAddr}.{id * 60 + 10 + e.RowIndex / 8}.{e.RowIndex % 8}", 1);
                }
                await GetPosData();

            }
        }

        private void dgvAxisPos_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            new DataGridViewStyle().DgvRowPostPaint(dgvAxisPos, e);
        }

        private void dgvAxisPos_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == this.dgvAxisPos.Columns["InPos"].Index && e.Value != null)
            {
                bool inPos = (bool)e.Value;
                if (inPos) // 根据条件判断
                {
                    e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    e.Value = global::CowainHmi.Properties.Resources.有效;
                    e.FormattingApplied = true;
                }
                else
                {
                    e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    e.Value = global::CowainHmi.Properties.Resources.无效;
                    e.FormattingApplied = true;
                }
            }
            else if (e.ColumnIndex == this.dgvAxisPos.Columns["SafeLock"].Index && e.Value != null)
            {
                bool safeLock = (bool)e.Value;
                if (safeLock) // 根据条件判断
                {
                    e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    e.Value = global::CowainHmi.Properties.Resources.无效;
                    e.FormattingApplied = true;
                }
                else
                {
                    e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    e.Value = global::CowainHmi.Properties.Resources.有效;
                    e.FormattingApplied = true;
                }
            }
        }


    }
}
