using DBUtility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FiveScreen
{
    public partial class FrmInjection2 : Form
    {
        bool isMouseDown = false; // 窗体是否移动
        Point currentFormLocation = new Point(); // 当前窗体位置
        Point currentMouseOffset = new Point(); // 当前鼠标的按下位置
        public FrmInjection2()
        {
            InitializeComponent();
            panel1.MouseDown += FrmInjection1_MouseDown;
            panel1.MouseMove += FrmInjection1_MouseMove;
            panel1.MouseUp += FrmInjection1_MouseUp;
            this.WindowState = FormWindowState.Maximized;
        }

        private void panel1_DoubleClick(object sender, EventArgs e)
        {
            //Application.Exit();
            if(this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
            
        }

        private void FrmInjection2_Load(object sender, EventArgs e)
        {
            LoadDeviceState();
        }
        void LoadDeviceState()
        {
            DataTable dt = new DataTable();
            try
            {
                #region 第一阶段内容
                Label[] labUse = { labUse1, labUse2, labUse3, labUse4, labUse5, labUse6 };
                Label[] labPass = { labPass1, labPass2, labPass3, labPass4, labPass5, labPass6 };
                Label[] labState = { labState1, labState2, labState3, labState4, labState5, labState6 };

                #region sql
                string sql = @" 
                                    SELECT * INTO #temp
                                    FROM
                                    (
                                    SELECT * from
                                    (SELECT TOP 1 StationID, StationNo, [UseRate], [PassRate]
                                    FROM tb_Report_FiveScreenLast
                                    WHERE stationNo = 'IM01'
                                    ORDER BY CreateTime DESC) a
                                    UNION ALL
                                    SELECT * from
                                    (SELECT TOP 1 StationID, StationNo, [UseRate], [PassRate]
                                    FROM tb_Report_FiveScreenLast
                                    WHERE stationNo = 'IM02'
                                    ORDER BY CreateTime DESC) b
                                    UNION ALL
                                    SELECT * from
                                    (SELECT TOP 1 StationID, StationNo, [UseRate], [PassRate]
                                    FROM tb_Report_FiveScreenLast
                                    WHERE stationNo = 'IM03'
                                    ORDER BY CreateTime DESC) c
                                    UNION ALL
                                    SELECT * from
                                    (SELECT TOP 1 StationID, StationNo, [UseRate], [PassRate]
                                    FROM tb_Report_FiveScreenLast
                                    WHERE stationNo = 'IM04'
                                    ORDER BY CreateTime DESC) d
                                    UNION ALL
                                    SELECT * from
                                    (SELECT TOP 1 StationID, StationNo, [UseRate], [PassRate]
                                    FROM tb_Report_FiveScreenLast
                                    WHERE stationNo = 'IM05'
                                    ORDER BY CreateTime DESC) e
                                    UNION ALL
                                    SELECT * from
                                    (SELECT TOP 1 StationID, StationNo, [UseRate], [PassRate]
                                    FROM tb_Report_FiveScreenLast
                                    WHERE stationNo = 'IM06'
                                    ORDER BY CreateTime DESC) f
                                    ) aa

                                    SELECT #temp.StationID, #temp.StationNo,#temp.UseRate,#temp.PassRate,StartTime,EndTime,(CASE WHEN (starttime is not null and EndTime IS NULL) OR EndTime = '' THEN '停机' ELSE '运行' END) [State] INTO #tmp FROM #temp
                                    LEFT JOIN tb_Injection_DownRecord 
                                    ON tb_Injection_DownRecord.StationID = #temp.StationID
                                    ORDER BY StartTime DESC

                                    SELECT * FROM (
                                    SELECT TOP 1 *
                                    FROM #tmp
                                    WHERE stationNo = 'IM01'
                                    ORDER BY StartTime DESC) a
                                    UNION ALL
                                    SELECT * FROM (
                                    SELECT TOP 1 *
                                    FROM #tmp
                                    WHERE stationNo = 'IM02'
                                    ORDER BY StartTime DESC) b
                                    UNION ALL
                                    SELECT * FROM (
                                    SELECT TOP 1 *
                                    FROM #tmp
                                    WHERE stationNo = 'IM03'
                                    ORDER BY StartTime DESC) c
                                    UNION ALL
                                    SELECT * FROM (
                                    SELECT TOP 1 *
                                    FROM #tmp
                                    WHERE stationNo = 'IM04'
                                    ORDER BY StartTime DESC) d
                                    UNION ALL
                                    SELECT * FROM (
                                    SELECT TOP 1 *
                                    FROM #tmp
                                    WHERE stationNo = 'IM05'
                                    ORDER BY StartTime DESC) e
                                    UNION ALL
                                    SELECT * FROM (
                                    SELECT TOP 1 *
                                    FROM #tmp
                                    WHERE stationNo = 'IM06'
                                    ORDER BY StartTime DESC) f


                                    DROP TABLE #temp;
                                    DROP TABLE #tmp;
                            ";
                #endregion
                dt = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql, null);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        labUse[i].Text = dt.Rows[i]["UseRate"].ToString();
                        //labPass[i].Text = dt.Rows[i]["PassRate"].ToString();
                        labState[i].Text = dt.Rows[i]["State"].ToString();
                    }
                }
                #endregion

                #region 第二阶段内容

                Label[] labPro = new Label[6];
                Label[] labProNum = new Label[6];
                for (int i = 0; i < 6; i++)
                {
                    labPro[i] = new Label();
                    labPro[i].Name = "labPro" + i.ToString();
                    labPro[i].BackColor = Color.Transparent;
                    labPro[i].ForeColor = Color.White;
                    labPro[i].Font = new System.Drawing.Font("微软雅黑", 30F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    labPro[i].TextAlign = ContentAlignment.MiddleCenter;
                    labPro[i].Size = new System.Drawing.Size(269, 119);
                    labPro[i].Location = new System.Drawing.Point(353, 298 + i * 122);
                    //labPro[i].Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)| System.Windows.Forms.AnchorStyles.Left)| System.Windows.Forms.AnchorStyles.Right)));
                    panel1.Controls.Add(labPro[i]);

                    labProNum[i] = new Label();
                    labProNum[i].Name = "labProNum" + i.ToString();
                    labProNum[i].BackColor = Color.Transparent;
                    labProNum[i].ForeColor = Color.White;
                    labProNum[i].Font = new System.Drawing.Font("微软雅黑", 30F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    labProNum[i].TextAlign = ContentAlignment.MiddleCenter;
                    labProNum[i].Size = new System.Drawing.Size(295, 111);
                    labProNum[i].Location = new System.Drawing.Point(1273, 300 + i * 123);
                    //labProNum[i].Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)| System.Windows.Forms.AnchorStyles.Left)| System.Windows.Forms.AnchorStyles.Right)));
                    panel1.Controls.Add(labProNum[i]);
                }

                GetLabContent();

                #endregion

                timer1.Enabled = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString(), "注塑六设备大屏");
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                LoadDeviceState();
                //GetLabContent();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }
        }

        private void GetLabContent()
        {
            try
            {
                #region 产品名称

                for (int i = 0; i < 6; i++)
                {
                    string sql_pro = @"
                                select top 1 ProductName as [Plan] from tb_Product WITH (NOLOCK) where StockNo = (
                                select top 1 StockNo from tb_InjectionPlan WITH (NOLOCK) where StationID = ( 
                                        select StationID from tb_Station WITH (NOLOCK) where StationNo = '" + "IM0" + (i + 1).ToString() + @"' ) 
										AND (IsFinish is null or IsFinish = 0) 
										ORDER BY BeginTime ASC
										)
                                or PartNo = (
                                        select top 1 PartNo from tb_InjectionPlan WITH (NOLOCK) where StationID = ( 
                                        select StationID from tb_Station WITH (NOLOCK) where StationNo = '" + "IM0" + (i + 1).ToString() + @"' ) 
										AND (IsFinish is null or IsFinish = 0) 
										ORDER BY BeginTime ASC
										)
                            ";
                    object aa = SqlHelper.ExecuteScalar(SqlHelper.SqlConnString, CommandType.Text, sql_pro, null);
                    if (aa != null)
                    {
                        this.panel1.Controls.Find("labPro" + i.ToString(), true)[0].Text = aa.ToString();
                    }
                    else
                    {
                        this.panel1.Controls.Find("labPro" + i.ToString(), true)[0].Text = "";
                    }
                }

                #endregion

                #region 生产数

                for (int i = 0; i < 6; i++)
                {
                    string date = DateTime.Now.ToString("yyyy-MM-dd");
                    if (DateTime.Now.Hour >= 0 && DateTime.Now.Hour < 8)
                    {
                        date = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                    }
                    string sql_num = @"
                                        SELECT TOP 1 isnull(ProductCount,0) ProductCount, isnull(BadCount,0) BadCount
                                        FROM tb_Product_Injection a WITH (NOLOCK)
                                        WHERE a.StationID = ( SELECT StationID from tb_Station WITH (NOLOCK) where StationNo = '" + "IM0" + (i + 1).ToString() + @"' )
                                        AND (a.StockNo = (
	                                    select top 1 StockNo from tb_InjectionPlan WITH (NOLOCK) where StationID = ( select StationID from tb_Station where StationNo = '" + "IM0" + (i + 1).ToString() + @"')
	                                    AND (IsFinish is null or IsFinish = 0) 
	                                    ORDER BY BeginTime ASC
				                                        )
                                        OR a.PartNo = (
	                                    select top 1 PartNo from tb_InjectionPlan WITH (NOLOCK) where StationID = ( select StationID from tb_Station where StationNo = '" + "IM0" + (i + 1).ToString() + @"')
	                                    AND (IsFinish is null or IsFinish = 0) 
	                                    ORDER BY BeginTime ASC
                                        ))
                                        and a.PlanID = (
                                        select top 1 InjectionPlanID from tb_InjectionPlan WITH (NOLOCK) where StationID = ( select StationID from tb_Station where StationNo = '" + "IM0" + (i + 1).ToString() + @"')
	                                    AND (IsFinish is null or IsFinish = 0) 
	                                    ORDER BY BeginTime ASC
                                        )
                                        AND a.ProductDate = '" + date + @"'
                                        AND a.ClassName = '" + GetWorkClass() + @"'
                                ";
                    //object bb = SqlHelper.ExecuteScalar(SqlHelper.SqlConnString, CommandType.Text, sql_num, null);
                    //if (bb != null)
                    //{
                    //    this.panel1.Controls.Find("labProNum" + i.ToString(), true)[0].Text = bb.ToString();
                    //}
                    //else
                    //{
                    //    this.panel1.Controls.Find("labProNum" + i.ToString(), true)[0].Text = "";
                    //}

                    DataTable dt = SqlHelper.GetDataDateTable(SqlHelper.SqlConnString, CommandType.Text, sql_num, null);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        this.panel1.Controls.Find("labProNum" + i.ToString(), true)[0].Text = dt.Rows[0]["ProductCount"].ToString();

                        int prc = 0; int badc = 0;
                        string PassCount = "";
                        Int32.TryParse(dt.Rows[0]["ProductCount"].ToString(), out prc);
                        Int32.TryParse(dt.Rows[0]["BadCount"].ToString(), out badc);
                        PassCount = (prc - badc).ToString();

                        int passc = 0;
                        double compc = 0.0;
                        Int32.TryParse(PassCount, out passc);
                        Double.TryParse(dt.Rows[0]["ProductCount"].ToString(), out compc);
                        if (compc == 0.0)
                        {
                            this.panel1.Controls.Find("labPass" + (i + 1).ToString(), true)[0].Text = "0.0%";
                        }
                        else
                        {
                            this.panel1.Controls.Find("labPass" + (i + 1).ToString(), true)[0].Text = (passc / compc * 100).ToString("0.00") + "%";
                        }
                    }
                    else
                    {
                        this.panel1.Controls.Find("labProNum" + i.ToString(), true)[0].Text = "0";
                        this.panel1.Controls.Find("labPass" + (i + 1).ToString(), true)[0].Text = "0.0%";
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }
        }

        /// <summary>
        /// 获取班次,规定早8至晚8为A班
        /// </summary>
        /// <returns></returns>
        public string GetWorkClass()
        {
            bool classA = IsBetweenTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "2019-06-12 08:00:00", "2019-06-12 20:00:00");
            if (classA)
            {
                return "A班";
            }
            else
            {
                return "B班";
            }
        }

        /// <summary>
        /// 判断传入时间是否在工作时间段内
        /// </summary>
        /// <param name="timeStr"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static bool IsBetweenTime(string timeStr, string startTime, string endTime)
        {
            //判断传入时间是否在工作时间段内
            try
            {
                TimeSpan startSpan = DateTime.Parse(startTime).TimeOfDay;
                TimeSpan endSpan = DateTime.Parse(endTime).TimeOfDay;

                DateTime t1 = Convert.ToDateTime(timeStr);
                TimeSpan dspNow = t1.TimeOfDay;
                if (dspNow > startSpan && dspNow < endSpan)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                return false;
            }
        }

        private void FrmInjection1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                currentFormLocation = this.Location;
                currentMouseOffset = Control.MousePosition;
            }
        }

        private void FrmInjection1_MouseMove(object sender, MouseEventArgs e)
        {
            int rangeX = 0, rangeY = 0; // 计算当前鼠标光标的位移,让窗体进行相同大小的位移
            if (isMouseDown)
            {
                Point pt = Control.MousePosition;
                rangeX = currentMouseOffset.X - pt.X;
                rangeY = currentMouseOffset.Y - pt.Y;
                this.Location = new Point(currentFormLocation.X - rangeX, currentFormLocation.Y - rangeY);
            }
        }

        private void FrmInjection1_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false; // 停止移动
        }
    }
}