using Pms.Common.SystemEnum;
using Pms.View.Config;
using Pms.View.Models;
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;

namespace Pms.View
{
    public partial class MainForm : Form
    {
        DataTable _MainTable;
        bool CanUpdateDgvFlag = true;

        private Color DgvForceColor = Color.White;
        private Color DgvBackColor = Color.Black;
        private Color MenuForceColor = Color.Black;
        private Color MenuBackColor = Color.Black;
        private Color MainBackColor = Color.Black;

        public MainForm()
        {
            InitializeComponent();
            InitConfig();
        }

        private void InitConfig()
        {
            CViewConfigManager.Init();

            if( CViewConfigManager.gs_ViewData.PmsColorList != null && CViewConfigManager.gs_ViewData.PmsColorList.Count > 0)
            {
                foreach(PmsColor sPmsColor in CViewConfigManager.gs_ViewData.PmsColorList)
                {
                    if (sPmsColor.Elem == EDisplayElem.DgvForceColor.ToString())
                    {
                        DgvForceColor = Color.FromArgb(sPmsColor.R, sPmsColor.G, sPmsColor.B);
                    }
                    else if (sPmsColor.Elem == EDisplayElem.DgvBackColor.ToString())
                    {
                        DgvBackColor = Color.FromArgb(sPmsColor.R, sPmsColor.G, sPmsColor.B);
                    }
                    else if (sPmsColor.Elem == EDisplayElem.MainBackColor.ToString())
                    {
                        MainBackColor = Color.FromArgb(sPmsColor.R, sPmsColor.G, sPmsColor.B);
                    }
                    else if (sPmsColor.Elem == EDisplayElem.DgvBackColor.ToString())
                    {
                        DgvBackColor = Color.FromArgb(sPmsColor.R, sPmsColor.G, sPmsColor.B);
                    }
                    else if (sPmsColor.Elem == EDisplayElem.MenuBackColor.ToString())
                    {
                        MenuBackColor = Color.FromArgb(sPmsColor.R, sPmsColor.G, sPmsColor.B);
                    }
                    else if (sPmsColor.Elem == EDisplayElem.MenuForceColor.ToString())
                    {
                        MenuForceColor = Color.FromArgb(sPmsColor.R, sPmsColor.G, sPmsColor.B);
                    }
                }
            }
            else
            {
                DefaultColor();
            }
        }

        private void InitColor()
        {
            LbTime.BackColor = MenuBackColor;
            LbTime.ForeColor = DgvForceColor;

            mainMenu.BackColor = MenuBackColor;
            mainMenu.ForeColor = MenuForceColor;

            this.BackColor = MainBackColor;


            MainDisplayDGV.GridColor = DgvBackColor;
            MainDisplayDGV.ForeColor = DgvForceColor;
            MainDisplayDGV.BackgroundColor = DgvBackColor;

            DataGridViewCellStyle newStyle = new DataGridViewCellStyle();
            newStyle.ForeColor = DgvForceColor;
            newStyle.BackColor = DgvBackColor;
            foreach (DataGridViewColumn col in this.MainDisplayDGV.Columns)
            {
                col.HeaderCell.Style = newStyle;
                col.SortMode = DataGridViewColumnSortMode.Programmatic;
            }
        }

        private void DefaultColor()
        {
            PmsColor sPmsColor = new PmsColor();
            sPmsColor.Elem = EDisplayElem.DgvForceColor.ToString();
            sPmsColor.R = DgvForceColor.R;
            sPmsColor.G = DgvForceColor.G;
            sPmsColor.B = DgvForceColor.B;

            CViewConfigManager.gs_ViewData.PmsColorList.Add(sPmsColor);

            sPmsColor = new PmsColor();
            sPmsColor.Elem = EDisplayElem.DgvBackColor.ToString();
            sPmsColor.R = DgvBackColor.R;
            sPmsColor.G = DgvBackColor.G;
            sPmsColor.B = DgvBackColor.B;
            CViewConfigManager.gs_ViewData.PmsColorList.Add(sPmsColor);

            sPmsColor = new PmsColor();
            sPmsColor.Elem = EDisplayElem.MainBackColor.ToString();
            sPmsColor.R = MainBackColor.R;
            sPmsColor.G = MainBackColor.G;
            sPmsColor.B = MainBackColor.B;
            CViewConfigManager.gs_ViewData.PmsColorList.Add(sPmsColor);

            sPmsColor = new PmsColor();
            sPmsColor.Elem = EDisplayElem.MenuBackColor.ToString();
            sPmsColor.R = MenuBackColor.R;
            sPmsColor.G = MenuBackColor.G;
            sPmsColor.B = MenuBackColor.B;
            CViewConfigManager.gs_ViewData.PmsColorList.Add(sPmsColor);

            sPmsColor = new PmsColor();
            sPmsColor.Elem = EDisplayElem.MenuForceColor.ToString();
            sPmsColor.R = MenuBackColor.R;
            sPmsColor.G = MenuBackColor.G;
            sPmsColor.B = MenuBackColor.B;
            CViewConfigManager.gs_ViewData.PmsColorList.Add(sPmsColor);

            CViewConfigManager.SaveViewData();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            CanUpdateDgvFlag = true;
            _MainTable = UpdateHeader();
            MainDisplayDGV.DataSource = _MainTable;

            InitDgv();
            InitColor();

            TimerUpdate.Interval = 1000;
            TimerUpdate.Enabled = true;
        }

        private void InitDgv()
        {
            MainDisplayDGV.ClearSelection();                                           //清除初始进入选项
            MainDisplayDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    //设置为选全行           

            MainDisplayDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            MainDisplayDGV.DefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;               //cell字体居中
            MainDisplayDGV.ColumnHeadersDefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;  //标括题琣字体居中
            MainDisplayDGV.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.True;

            MainDisplayDGV.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 13, FontStyle.Bold);//26
            MainDisplayDGV.DefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;               //cell字体居中
            MainDisplayDGV.ColumnHeadersDefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;  //标括题琣字体居中
            MainDisplayDGV.RowsDefaultCellStyle.Font = new Font("微软雅黑", 12, FontStyle.Bold);          //cell字体设置
            MainDisplayDGV.ScrollBars = ScrollBars.Both;

            #region 奇偶行颜色交替
            MainDisplayDGV.RowsDefaultCellStyle.BackColor = Color.LightSeaGreen;
            MainDisplayDGV.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkCyan;
            #endregion

            //MainDisplayDGV.GridColor = m_SysColor;
            #region 设置dataGridView1的列标题的背景色和字体颜色
            //DataGridViewCellStyle newStyle = new DataGridViewCellStyle();
            //newStyle.ForeColor = Color.White;
            //newStyle.BackColor = m_SysColor;
            //foreach (DataGridViewColumn col in this.MainDisplayDGV.Columns)
            //{
            //    col.HeaderCell.Style = newStyle;
            //    col.SortMode = DataGridViewColumnSortMode.Programmatic;
            //}

            this.MainDisplayDGV.EnableHeadersVisualStyles = false;

            int nWidth = MainDisplayDGV.Width;
            MainDisplayDGV.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            MainDisplayDGV.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            #endregion

            MainDisplayDGV.AllowUserToAddRows = false;
            MainDisplayDGV.AllowUserToDeleteRows = false;
            MainDisplayDGV.EnableHeadersVisualStyles = false;
            MainDisplayDGV.AllowUserToResizeRows = false;
            MainDisplayDGV.RowHeadersVisible = false;
            MainDisplayDGV.MultiSelect = false;
            MainDisplayDGV.ReadOnly = true;
        }

        #region dgv数据显示 显示MidData
        public void UpdateData(DataTable table)
        {
            if (table == null) return;

            Dictionary<string, bool> OrderIDDic = new Dictionary<string, bool>();

            DataTable dt = PmsCoreDB.DBHost.Instance.OrderData.GetList("").Tables[0];

            if (dt != null)
            {
                for (int i = table.Rows.Count - 1; i >= 0; i--)
                {
                    string OrderID = table.Rows[i][0].ToString();
                    if (OrderIDDic.ContainsKey(OrderID))
                    {
                        continue;
                    }
                    DataRow[] dwArr = dt.Select(" OrderID = '" + OrderID + "'");

                    if (dwArr.Count() > 0)
                    {
                        if ((string)table.Rows[i][EDgvColumnsName.订单号.ToString()] != dwArr[0]["OrderID"].ToString())
                        { table.Rows[i][EDgvColumnsName.订单号.ToString()] = dwArr[0]["OrderID"].ToString(); }

                        if ((DateTime)table.Rows[i][EDgvColumnsName.添加时间.ToString()] != (DateTime)dwArr[0]["CalledTime"])
                        { table.Rows[i][EDgvColumnsName.添加时间.ToString()] = (DateTime)dwArr[0]["CalledTime"]; }

                        if ((string)table.Rows[i][EDgvColumnsName.库位.ToString()] != dwArr[0]["PosArr"].ToString())
                        { table.Rows[i][EDgvColumnsName.库位.ToString()] = dwArr[0]["PosArr"].ToString(); }

                        if ((string)table.Rows[i][EDgvColumnsName.类型.ToString()] != dwArr[0]["OrderType"].ToString())
                        { table.Rows[i][EDgvColumnsName.类型.ToString()] = dwArr[0]["OrderType"].ToString(); }

                        if ((string)table.Rows[i][EDgvColumnsName.小车.ToString()] != dwArr[0]["Carrier"].ToString())
                        { table.Rows[i][EDgvColumnsName.小车.ToString()] = dwArr[0]["Carrier"].ToString(); }

                        if ((EOrderState)table.Rows[i][EDgvColumnsName.状态.ToString()] != (EOrderState)dwArr[0]["OrderState"])
                        { table.Rows[i][EDgvColumnsName.状态.ToString()] = (EOrderState)dwArr[0]["OrderState"]; }

                        if ((string)table.Rows[i][EDgvColumnsName.错误码.ToString()] != dwArr[0]["ErrorCode"].ToString())
                        { table.Rows[i][EDgvColumnsName.错误码.ToString()] = dwArr[0]["ErrorCode"].ToString(); }

                        if ((string)table.Rows[i][EDgvColumnsName.信息.ToString()] != dwArr[0]["DisplayMessage"].ToString())
                        { table.Rows[i][EDgvColumnsName.信息.ToString()] = dwArr[0]["DisplayMessage"].ToString(); }

                        OrderIDDic.Add(OrderID, true);

                        dt.Rows.Remove(dwArr[0]);
                    }
                    else
                    {
                        table.Rows.RemoveAt(i);
                    }
                }
            }

            foreach (DataRow dw in dt.Rows)
            {
                if (!OrderIDDic.ContainsKey(dw["OrderID"].ToString()))
                {
                    table.Rows.Add(
                        dw["OrderID"].ToString(),
                        dw["CalledTime"].ToString(),
                        dw["PosArr"].ToString(),
                        dw["OrderType"].ToString(),
                        dw["Carrier"].ToString(),
                        (EOrderState)dw["OrderState"],
                        dw["ErrorCode"].ToString(),
                        dw["DisplayMessage"].ToString()
                        );
                }
            }
        }

        enum EDgvColumnsName
        {
            订单号,
            添加时间,
            库位,
            类型,
            小车,
            状态,
            错误码,
            信息,
        }

        public DataTable UpdateHeader()
        {
            DataTable table = new DataTable();

            table.Columns.Add(EDgvColumnsName.订单号.ToString(), typeof(string));
            table.Columns.Add(EDgvColumnsName.添加时间.ToString(), typeof(DateTime));
            table.Columns.Add(EDgvColumnsName.库位.ToString(), typeof(string));
            table.Columns.Add(EDgvColumnsName.类型.ToString(), typeof(string));
            table.Columns.Add(EDgvColumnsName.小车.ToString(), typeof(string));
            table.Columns.Add(EDgvColumnsName.状态.ToString(), typeof(EOrderState));
            table.Columns.Add(EDgvColumnsName.错误码.ToString(), typeof(string));
            table.Columns.Add(EDgvColumnsName.信息.ToString(), typeof(string));

            return table;
        }

        /// <summary>
        /// 数据更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerUpdate_Tick(object sender, EventArgs e)
        {
            if (!CanUpdateDgvFlag)
            {
                return;
            }
            CanUpdateDgvFlag = false;
            try
            {
                LbTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                UpdateData(_MainTable);

                if (panelDgvParent.BackColor != Color.Transparent)
                {
                    panelDgvParent.BackColor = Color.Transparent;

                    string strLog = "数据显示恢复！";
                }
            }
            catch (Exception ex)
            {
                panelDgvParent.BackColor = Color.Red;
                string strLog = "数据显示异常" + ex.Message + "\r\n" + ex.StackTrace;
            }
            CanUpdateDgvFlag = true;
        }

        #endregion

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 颜色设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ColorSet colorSet = new ColorSet();
            //this.
        }

        private void 全屏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
        }

        private void 缩小ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.WindowState = FormWindowState.Normal;
        }
    }
}
