using DNSD_DB;
using NDSD_Screwdriver.Entity;
using NDSD_TouchSocket;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NDSD_Screwdriver
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 输出端口操作
        /// </summary>
        private DOperate DOperate;

        /// <summary>
        /// TCP服务器
        /// </summary>
        private TcpServer server = TcpServer.Instance;

        /// <summary>
        /// 前端列表集合
        /// </summary>
        private List<MonitorEntity> monitorEntities;

        private Random rand = new Random();

        ///// <summary>
        ///// 判断是否是第一次初始化
        ///// </summary>
        //private int flag = 0;

        /// <summary>
        /// 判断现在操作哪一行
        /// </summary>
        public int NowRowIndex = 0;

        /// <summary>
        /// RFID列表
        /// </summary>
        public string[] RFIDs = new string[]
        {
            "1111222233334444",
            "2222222233334444",
            "3333222233334444",
            "4444222233334444",
            "5555222233334444"
        };

        public MainForm()
        {
            InitializeComponent();
            DOperate = new DOperate();
            if (!server.ServerOpen(MemorySetting.ServerIP, MemorySetting.ServerPort))
            {
                MessageBox.Show("服务端打开失败！");
            }

        }

        /// <summary>
        /// 打开DO测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DOTest_Click(object sender, EventArgs e)
        {
            ScrewdriverTest screwdriverTest = new ScrewdriverTest(server, DOperate);
            screwdriverTest.Show();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (server != null)
            {
                if (!server.ServerStop())
                {
                    MessageBox.Show("服务端关闭失败！");
                }
                if (!server.ServerDispose())
                {
                    MessageBox.Show("服务端释放失败！");
                }
            }
        }

        /// <summary>
        /// 列表回调函数
        /// </summary>
        /// <param name="g"></param>
        /// <param name="rowIndex"></param>
        /// <param name="colIndex"></param>
        /// <param name="rectangle"></param>
        /// <param name="value"></param>
        /// <param name="sf"></param>
        private void ScrewdriverMonitor_OnDrawCellTextEvent(Graphics g, int rowIndex, int colIndex, RectangleF rectangle, string value, StringFormat sf)
        {
            foreach (MonitorEntity entity in monitorEntities)
            {
                if (rowIndex == entity.RowIndex)
                {
                    foreach (RowEntity rowEneiey in entity.RowEntitys)
                    {
                        if (colIndex == rowEneiey.ColumnIndex)
                        {
                            g.FillRectangle(rowEneiey.Color, rectangle);
                            g.DrawString(rowEneiey.Value, this.ScrewdriverMonitor.Font, Brushes.Black, rectangle, sf);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 测试按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TestButton1_Click(object sender, EventArgs e)
        {
            if (RFIDs.Length == 0)
            {
                MessageBox.Show("没有值，请先设置。");
            }

            SetNowRowsLightState(FormUtils.TestRamColor());

            RefreshRoll();
            if (++NowRowIndex >= RFIDs.Length)
            {
                NowRowIndex = 0;
            }
        }

        private void InitButton_Click(object sender, EventArgs e)
        {
            NowRowIndex = 0;
            InitMonitirIntity();
            //var ctx = SqlLiteTool.GetDb(AppTool.GetDb());
            //var list = ctx.Query<RfidSetting>().Where(x => x.IsEnable == true).ToList();
            //RFIDs = list.Select(x => x.RfidNo).ToArray();
            SetRFIDValue(RFIDs);
        }

        /// <summary>
        /// 刷新列表
        /// </summary>
        private void RefreshRoll()
        {
            for (int i = 0; i < RFIDs.Length; i++)
            {
                ScrewdriverMonitor.AddRowTop(new string[]{
                    "",
                    "",
                    ""
                });
            }
        }

        /// <summary>
        /// 初始化整个列表
        /// </summary>
        private void InitMonitirIntity()
        {
            monitorEntities = new List<MonitorEntity>();
            for (int i = 0; i < RFIDs.Length; i++)
            {
                monitorEntities.Add(new MonitorEntity()
                {
                    RowIndex = i,
                    RowEntitys = InitRows(i)
                });
            }
            RefreshRoll();
        }

        /// <summary>
        /// 初始化一行
        /// </summary>
        /// <param name="rowNo">当前的初始化行数</param>
        /// <returns></returns>
        private List<RowEntity> InitRows(int rowNo)
        {
            List<RowEntity> rowEntities = new List<RowEntity>();
            for (int i = 0; i < 3; i++)
            {
                rowEntities.Add(new RowEntity()
                {
                    ColumnIndex = i,
                });
            }
            return rowEntities;
        }

        /// <summary>
        /// 初始化RFID数据
        /// </summary>
        /// <param name="rFIDvalue">RFID列表</param>
        private void SetRFIDValue(string[] rFIDvalue)
        {
            for (int i = 0; i < rFIDvalue.Length; i++)
            {
                monitorEntities[i].RowEntitys[1].Value = rFIDvalue[i];
            }
        }

        /// <summary>
        /// 设置当前行指示灯的状态以及工作的行
        /// </summary>
        /// <param name="lightState"></param>
        private void SetNowRowsLightState(LightState lightState)
        {
            monitorEntities[NowRowIndex].RowEntitys[2].Color = FormUtils.EnumColorToBrush(lightState);

            for (int i = 0; i < RFIDs.Length; i++)
            {
                monitorEntities[NowRowIndex].RowEntitys[0].Value = i == NowRowIndex ? "=>" : "";
            }
        }

        private void SetNowRowsLightState(Brush brush)
        {
            monitorEntities[NowRowIndex].RowEntitys[2].Color = brush;
            for (int i = 0; i < RFIDs.Length; i++)
            {
                monitorEntities[i].RowEntitys[0].Value = i == NowRowIndex ? "=>" : "";
            }
        }

        private void SettingButton_Click(object sender, EventArgs e)
        {
            FrmSetting frmSetting = new FrmSetting();
            frmSetting.Show();
        }

        private void ServerRestartButton_Click(object sender, EventArgs e)
        {
            if (server.ServerRestart(MemorySetting.ServerIP, MemorySetting.ServerPort))
            {
                MessageBox.Show("服务器重启成功！");
            }
            else
            {
                MessageBox.Show("服务器重启失败！请手动启动服务器。");
            }

        }

        private void StartServerButton_Click(object sender, EventArgs e)
        {
            if (!server.ServerOpen(MemorySetting.ServerIP, MemorySetting.ServerPort))
            {
                MessageBox.Show("服务端打开失败！");
            }
            else
            {
                MessageBox.Show("服务器启动成功");
            }
        }

        private void ServerStopButton_Click(object sender, EventArgs e)
        {
            if (server != null)
            {
                if (!server.ServerStop())
                {
                    MessageBox.Show("服务端关闭失败！");
                }
                if (!server.ServerDispose())
                {
                    MessageBox.Show("服务端释放失败！");
                }
            }
        }
    }
}
