using Common;
using DeviceLibrary;
using DeviceLibrary.Context;
using LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UserFromControl;

namespace LiftController
{
    public partial class FrmIO : Form
    {
        public FrmIO(LineConfig config)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            groupBox4.Enabled = false;
            LoadIOList(config);
            string[] lifts = Common.AppConfigHelper.GetValue(Common.SettingString.Lift_Ids, "LIFT_D2,LIFT_C1").Split(',');
            comboBox1.Items.AddRange(lifts);
            if (comboBox1.Items.Count > 0)
                comboBox1.SelectedIndex = 0;
        }
        Dictionary<string, IOTextControl> DIControlList = new Dictionary<string, IOTextControl>();
        Dictionary<string, IOTextControl> DOControlList = new Dictionary<string, IOTextControl>();
        private void LoadIOList(LineConfig config)
        {
            this.tableLayoutPanel2.RowStyles.Clear();
            this.tableLayoutPanel2.RowCount = config.DIList.Count;
            int roleindex = 0;
            foreach (ConfigIO ioValue in config.DIList.Values)
            {
                IOTextControl control = new IOTextControl(ioValue.ElectricalDefinition + "_" + ioValue.Explain, ioValue.ProName);
                this.tableLayoutPanel2.RowStyles.Add(new RowStyle(SizeType.Absolute, 28));
                this.tableLayoutPanel2.Controls.Add(control, 0, roleindex);
                roleindex++;
                DIControlList.Add(ioValue.ProName, control);
            }

            tableLayoutPanel3.RowStyles.Clear();
            this.tableLayoutPanel3.RowCount = config.DOList.Count;
            roleindex = 0;
            foreach (ConfigIO ioValue in config.DOList.Values)
            {
                IOTextControl control = new IOTextControl(ioValue.ElectricalDefinition + "_" + ioValue.Explain, ioValue.ProName);
                control.Click += Control_Click;

                this.tableLayoutPanel3.RowStyles.Add(new RowStyle(SizeType.Absolute, 28));
                this.tableLayoutPanel3.Controls.Add(control, 0, roleindex);

                roleindex++;
                DOControlList.Add(ioValue.ProName, control);
            }
            this.SuspendLayout();    //此处为不闪屏,一定要有的! 

            cmbWriteIO.DataSource = new List<ConfigIO>(config.DOList.Values);
            cmbWriteIO.ValueMember = "ProName";
            cmbWriteIO.DisplayMember = "DisplayStr";

        }
        private void Control_Click(object sender, EventArgs e)
        {
            IOTextControl control = (IOTextControl)sender;
            string name = control.Name.Substring(3, control.Name.Length - 3);
            List<string> keyList = new List<string>(DOControlList.Keys);
            int index = keyList.IndexOf(name);
            if (index >= 0)
            {
                cmbWriteIO.SelectedIndex = index;
            }
        }
        bool inRead = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            // if (this.Visible)
            if (inRead)
                return;
            try
            {
                inRead = true;
                ReadIOList();
            }
            catch { }
            finally { inRead = false; }
        }
        private void ReadIOList()
        {
            foreach (string key in DIControlList.Keys)
            {
                IOTextControl control = DIControlList[key];
                int iov = (int)IOManager.IOValue(key);
                if (iov != control.IOValue)
                {
                    control.IOValue = iov;
                    control.ShowData();
                }
            }
            foreach (string key in this.DOControlList.Keys)
            {
                IOTextControl control = DOControlList[key];
                int iov = (int)IOManager.DOValue(key);
                if (iov != control.IOValue)
                {
                    control.IOValue = iov;
                    control.ShowData();
                }
            }
        }

        private void FrmIO_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (this.timer1.Enabled)
                {
                    this.timer1.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, "Exception(异常)", MessageBoxButtons.OK, MessageBoxIcon.Error);
                LogUtil.error("", ex);
            }
        }
        private ConfigIO GetSelectDO()
        {
            string text = cmbWriteIO.SelectedValue.ToString();
            if (LineManager.Config.DOList.ContainsKey(text))
            {
                ConfigIO io = LineManager.Config.DOList[text];
                return io;
            }
            return null;
        }
        IOTextControl selectControl = null;
        private void WriteDO(IO_VALUE value)
        {
            string deviceName = txtDoName.Text;
            int.TryParse(txtDOIndex.Text, out int index);
             int.TryParse(txtWriteTime.Text,out int time);

            if (time > 0)
            {
                IOManager.instance.WriteSingleDO(deviceName, (byte)0, (ushort)index, value, time);         
            }
            else
            {
                IOManager.instance.WriteSingleDO(deviceName, (byte)0, (ushort)index, value);
            }
            LogUtil.info($"手动写入DO:{deviceName},{index},{value},{time}");
        }

        private void cmbWriteIO_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbWriteIO.SelectedIndex >= 0)
            {
                ConfigIO io = GetSelectDO();
                if (io != null)
                {
                    // txtIp.Text = io.DeviceName;
                    txtDOIndex.Text = io.GetIOAddr().ToString();
                    txtDoName.Text = io.IO_IP;
                    IOTextControl newControl = DOControlList[io.ProName];
                    if (selectControl != null) { selectControl.BackColor = Color.White; }
                    newControl.BackColor = Color.SkyBlue;
                    selectControl = newControl;

                }
            }
        }

        private void btnWriteSingleDO_Click(object sender, EventArgs e)
        {
            WriteDO(IO_VALUE.HIGH);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WriteDO(IO_VALUE.LOW);
        }
        private void cmbWriteIO_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
            {
                return;
            }
            e.DrawBackground();
            e.DrawFocusRectangle();
            if (cmbWriteIO.Items.Count > e.Index)
            {
                ConfigIO io = (ConfigIO)cmbWriteIO.Items[e.Index];
                e.Graphics.DrawString(io.DisplayStr, e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3);
            }
        }
        private void FrmIOStatus_Shown(object sender, EventArgs e)
        {
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            bool chked=checkBox1.Checked;
            groupBox4.Enabled=chked;
            LogUtil.info($"IO调试状态:{chked}");
        }

        private void FrmIO_Load(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex > -1)
            {
                string liftId = comboBox1.SelectedItem.ToString();
                DialogResult dialogResult = MessageBox.Show($"确定删除电梯{liftId}的缓存信息?", "提示", MessageBoxButtons.YesNo);
                if (dialogResult.Equals(DialogResult.Yes))
                {
                    LiftContext.Clear(comboBox1.SelectedItem.ToString());
                    LogUtil.info($"手动清除电梯{liftId}缓存");
                }
            }
        }
    }
}