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 数据记录 : UserControl
    {
        public enum TrigerType
        {
            为1时触发,
            变化时触发,
            定时触发
        }


        private TrigerType trigType;

        [Category("PCHMI"), DisplayName("触发方式")]
        public TrigerType TrigType
        {
            get
            {
                return this.trigType;
            }
            set
            {
                this.trigType = value;
            }
        }

        private uint PlcId = 0;

        [Category("PCHMI"), DisplayName("PLC编号")]
        public uint PLC
        {
            get
            {
                return this.PlcId;
            }
            set
            {
                this.PlcId = value;
            }
        }
        private string trigger_bit;
        [Category("PCHMI"), DisplayName("触发位地址")]
        [Editor(typeof(StringText), typeof(UITypeEditor))]
        public string HDADDR
        {
            get
            {
                return this.trigger_bit;
            }
            set
            {
                this.trigger_bit = value;
            }
        }

        private Column[] _columns;
        [Category("PCHMI"), DisplayName("列设置")]
        public Column[] Columns
        {
            get
            {
                return this._columns;
            }
            set
            {
                this._columns = value;
            }
        }

        private uint dtim = 2000;
        [Category("PCHMI"), DisplayName("间隔触发时间")]
        public uint Dtime
        {
            get
            {
                return this.dtim;
            }
            set
            {
                this.dtim = value;
            }
        }

        private string filePath;
        [Category("PCHMI"), DisplayName("文件夹")]
        public string FilePath
        {
            get
            {
                return this.filePath;
            }
            set
            {
                this.filePath = value;
            }
        }

        public 数据记录()
        {
            InitializeComponent();
        }
        private void ucDataRecord_Load(object sender, EventArgs e)
        {
            this.dgvData.AllowUserToAddRows = false;
            this.dgvData.AllowUserToDeleteRows = false;
            this.timer1.Enabled = true;
        }
        private ushort trigValueLast;
        private int tickCount;
        private bool firstRead = true;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (PClass.IsPlcLink((int)PLC) && !string.IsNullOrEmpty(HDADDR))
            {
                ushort num = PCHMI.VL.GET_BIT((int)this.PLC, this.HDADDR);
                if (firstRead)
                {
                    this.Columns.Select(x => GetPlcData(x)).ToList();
                    firstRead = false;
                }
                if (this.TrigType == TrigerType.为1时触发)
                {
                    if (num > 0 && trigValueLast == 0)
                    {
                        WriteCsv();
                        PCHMI.RT.SEND_BIT((int)this.PLC, this.HDADDR, 0);
                    }

                }
                else if (this.TrigType == TrigerType.变化时触发)
                {
                    if (num != trigValueLast)
                    {
                        WriteCsv();
                        PCHMI.RT.SEND_BIT((int)this.PLC, this.HDADDR, 0);
                    }
                }
                else
                {
                    //定时触发
                    this.tickCount += 200;
                    if (this.tickCount >= Dtime)
                    {
                        this.tickCount = 0;
                        WriteCsv();
                    }
                }
                trigValueLast = num;
            }
        }
        private object lockObj = new object();
        private void btnQuery_Click(object sender, EventArgs e)
        {
            string fileName = string.Format($"{FilePath}\\{this.dtpDate.Value.ToString("yyyyMMdd")}.csv");
            QueryData(fileName);
        }

        private void QueryData(string fileName)
        {
            this.dgvData.Columns.Clear();
            this.dgvData.AllowUserToAddRows = false;
            this.dgvData.AllowUserToDeleteRows = false;
            //索引电脑上是否有对应名称的文件 如果没有 则以变量fileName创建一个csv文件 并填好表头
            lock (lockObj)
            {

                if (!System.IO.File.Exists(fileName))
                {
                    MessageBox.Show("没有记录", "提示");
                    return;
                }
            }
            foreach (var item in this.Columns)
            {
                var dgvc = new DataGridViewTextBoxColumn();
                dgvc.HeaderText = item.名称;
                dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
                //dgvc.Width = item.显示宽度;
                dgvc.ReadOnly = true;
            }
            this.dgvData.DataSource = CsvHelper.CsvToDataTable(fileName);

        }

        private void WriteCsv()
        {
            #region 
            //根据日期生成文件名
            string fileName = string.Format($"{filePath}\\{DateTime.Now.ToString("yyyyMMdd")}.csv");
            lock (lockObj)
            {
                //索引电脑上是否有对应名称的文件 如果没有 则以变量fileName创建一个csv文件 并填好表头
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                if (!System.IO.File.Exists(fileName))
                {
                    //写标题
                    var names = this.Columns.Select(x => x.名称).ToList();
                    CsvHelper.WriteLine(fileName, names);
                }
                var datas = this.Columns.Select(x => GetPlcData(x)).ToList();
                CsvHelper.WriteLine(fileName, datas);

            }
            QueryData(fileName);
            #endregion

        }


        private string GetPlcData(Column column)
        {
            if (column.类型 == 字段.DatType.String)
            {
                return PCHMI.VL.GET_STRING((int)column.PLC, column.ACT, column.字符串长度);
            }
            else if (column.类型 == 字段.DatType.SIEMENS_String)
            {
                return PCHMI.VL.GET_SIEMENS_STRING((int)column.PLC, column.ACT, column.字符串长度);
            }
            else if (column.类型 == 字段.DatType.DateTime)
            {
                return DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if (column.类型 == 字段.DatType.BIT)
            {
                return PCHMI.VL.GET_BIT((int)column.PLC, column.ACT).ToString();
            }
            else if (column.类型 == 字段.DatType.INT32)
            {
                return new PClass().UuValue((ulong)PCHMI.VL.GET_INT32((int)column.PLC, column.ACT), (uint)column.小数位数, column.类型.ToString());
            }
            else if (column.类型 == 字段.DatType.UINT32)
            {
                return new PClass().UuValue((ulong)PCHMI.VL.GET_UINT32((int)column.PLC, column.ACT), (uint)column.小数位数, column.类型.ToString());
            }
            else if (column.类型 == 字段.DatType.INT16)
            {
                return new PClass().UuValue((ulong)PCHMI.VL.GET_INT16((int)column.PLC, column.ACT), (uint)column.小数位数, column.类型.ToString());
            }
            else if (column.类型 == 字段.DatType.UINT16)
            {
                return new PClass().UuValue((ulong)PCHMI.VL.GET_UINT16((int)column.PLC, column.ACT), (uint)column.小数位数, column.类型.ToString());
            }
            //else if (column.类型 == 字段.DatType.F32)
            //{
            //    return new PClass().UuValue((ulong)PCHMI.VL.GET_F32((int)column.PLC, column.ACT), (uint)column.小数位数, column.类型.ToString());
            //}
            else if (column.类型 == 字段.DatType.F32)
            {
                return PCHMI.VL.GET_F32((int)column.PLC, column.ACT).ToString();
            }

            else
            {
                return "Err Data Type";
            }
        }

        private void dgvData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            new DataGridViewStyle().DgvRowPostPaint(this.dgvData, e);
        }


    }
}
