using DC_A95;
using DC_A95.MES_A95;
using MesToMs;
using SlMesDbIterface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using SystemFramework;
using WebApi;

namespace MesWork
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Temp { }
    /// <summary>
    /// 程式启动
    /// </summary>
    public partial class MesWorkForm
    {
        InitServer initServer = null;
        /// <summary>
        /// 从这里启动
        /// </summary>
        /// <param name="e"></param>
        protected override void OnShown(EventArgs e)
        {
            //【0】基础信息检查
            SqlOperation.ExecuteSql("select getdate()", out DataTable dt, out string error);
            if (error.Length > 0)
            {
                MessageBox.Show($"数据库配置错误！请检查数据库连接！！\r\n\r\n{MesWorkForm.ConnectionString}");
                Process.GetCurrentProcess().Kill();
            }

            DataLinkMesWork.ApplicationConfig.ConnectionString_MES = MesWorkForm.ConnectionString;
            label_SqlConn.Text = MesWorkForm.ConnectionString;

            //【1】系统基本参数设定
            ThreadPool.SetMaxThreads(workerThreads, completionPortThreads);
            Never_Know.Hello_You_All_Never_Know = Hello_You_All_Never_Know;
            new ApplicationLog();

            //【2】初始化
            ReLoadStationIcon();
            Visible_SaveLyoutBtn(false);
            Hanger.Load_Station_PageShowSignal();

            //【3】创建通讯
            LoadOpcData();
            Hanger.Load_Table();
            // LoadOPCData(BasicDataTableFile, IsDemoMesServer, IsWriteMonitorLog, true);
            Thread.Sleep(200);
            StartServer();       
            Thread.Sleep(200);
            First_TagMonitor();
            //var onList = CheckDeviceOnLine();

            //【4】检查在线状态
            CommunicationCheckOnLine();

            //【5】通讯成功的初始化设备数据
            timer_OnLine_Show.Interval = 1000;
            timer_OnLine_Show.Enabled = true;
            timer_ShowStation.Interval = 1000;
            timer_ShowStation.Enabled = true;

            //【7】HashTable 加载TaskType
            Upload_TaskTypeInfo();

            var task1 = new Thread(new ThreadStart(Loop));
            task1.IsBackground = true;
            task1.Start();

            Text = Text + $"【{MesWorkForm.ProgramPartial}】";

            // 【8】 WebApi 相关
            initServer = new WebApi.InitServer(MesWorkForm.WebSvrPort);

            LogRecord.LogRecord.Insert_Log(Type_Log.Login,"", $"MES系统启动成功！");
        }


        private void Upload_TaskTypeInfo()
        {
            ht_TaskTypeInfo=new System.Collections.Hashtable();
            DataTable dt = ExecuteDB.Get_TaskTypeInfo();
            foreach (DataRow itemRow in dt.Rows)
            {
                TaskTypeInfo taskTypeInfo = new TaskTypeInfo();
                taskTypeInfo.TaskTypeID = short.Parse(itemRow["任务类型"].ToString());
                taskTypeInfo.TaskTypeName = itemRow["任务类型名称"].ToString();
                taskTypeInfo.QCDataCount = int.Parse(itemRow["质量数据数量"].ToString());
                taskTypeInfo.DataName1 = itemRow["数据名称1"].ToString();
                taskTypeInfo.DataUnit1 = itemRow["数据单位1"].ToString();
                taskTypeInfo.DataName2 = itemRow["数据名称2"].ToString();
                taskTypeInfo.DataUnit2 = itemRow["数据单位2"].ToString();
                taskTypeInfo.DataName3 = itemRow["数据名称3"].ToString();
                taskTypeInfo.DataUnit3 = itemRow["数据单位3"].ToString();
                taskTypeInfo.DataName4 = itemRow["数据名称4"].ToString();
                taskTypeInfo.DataUnit4 = itemRow["数据单位4"].ToString();
                ht_TaskTypeInfo.Add(taskTypeInfo.TaskTypeID,taskTypeInfo);
            }
        }

      
        private void LoadOpcData()
        {
            DataTable dt_Tag = null;

            ExecuteDB.Select_Station(out DataTable dt_Station);
            dt_OPNameInfo = dt_Station.Copy();
            int tableLength = NPOITest.ExeclHelper.ExcelToDataTable(BasicDataTableFile, "MES_基本变量原始数据", true).Select($"是否启用='1'").Length;
            var dt_Tag_Mes = new DataTable();
            if (tableLength > 0)
            {
                dt_Tag_Mes = NPOITest.ExeclHelper.ExcelToDataTable(BasicDataTableFile, "MES_基本变量原始数据", true).Select($"是否启用='1'").CopyToDataTable();
            }
            var dt_Tag_Model = NPOITest.ExeclHelper.ExcelToDataTable(BasicDataTableFile, "MES_信号表模板", true).Select($"是否启用='1'").CopyToDataTable();
            var dt_Device = NPOITest.ExeclHelper.ExcelToDataTable(BasicDataTableFile, "设备类型对应表", true).Select($"是否启用='1'").CopyToDataTable();
            dt_Tag = dt_Tag_Model.Clone();

            for (int i = 0; i < dt_Station.Rows.Count; i++)
            {
                //[工位号],[工位名称],[PLC],[PLC代码],[PX],[PY],[PX_T],[PY_T],[控件启用]
                var 工位名称 = dt_Station.Rows[i]["工位名称"].ToString();
                var PLC = dt_Station.Rows[i]["PLC"].ToString();
                var stationName = dt_Station.Rows[i]["工位号"].ToString();
                var DB_NAME = dt_Station.Rows[i]["PLC代码"].ToString();
                var zoneCode = dt_Station.Rows[i]["区域代码"].ToString();


                var dt_Op_QC_DATA = dt_Tag_Model.Copy().Select($"DbName='DB_NAME'").CopyToDataTable();
                UpdateOpTable(dt_Op_QC_DATA, stationName, 工位名称, PLC, DB_NAME);
                dt_Tag.Merge(dt_Op_QC_DATA);

            }

            dt_Tag.Merge(dt_Tag_Mes);

            LoadOPCData(dt_Tag, dt_Device, IsDemoMesServer, IsWriteMonitorLog, true, false, out string error);
            if (error.Length > 0)
            {
                MessageBox.Show($"加载信号产生错误,程序不能启动！！错误：{error}");
                Process.GetCurrentProcess().Kill();
            }


            var dt_Tag1 = dt_Tag.Copy();
            dt_Tag1.TableName = "MES_基本变量_原始数据";
            SqlOperation.ExecuteSql($" truncate table {dt_Tag1.TableName}", out string error1);
            SqlOperation.SqlbulkcopyInsert(dt_Tag1);

            var dt_Device1 = dt_Device.Copy();
            dt_Device1.TableName = "MES_基本变量设备类型对应表";
            SqlOperation.ExecuteSql($" truncate table {dt_Device1.TableName}", out string error2);
            SqlOperation.SqlbulkcopyInsert(dt_Device1);



        }


        private void UpdateOpTable(DataTable dt,string opName,string opNameName,string ip, string dbName)
        {

            foreach (DataRow row in dt.Rows)
            {
                //TagID		TagName   工位号	数据来源	IP	DbName  变量特点  变量类型代码

                var TagName = row["TagName"].ToString();
                var 变量类型代码 = row["变量类型代码"].ToString();
                var 变量特点 = row["变量特点"].ToString();
                var 变量排序 = row["变量排序"].ToString();
                 
                row["TagID"] = $"8{opName.Substring(opName.Length - 4, 4)}{变量排序.PadLeft(3,'0')}";
                //row["TagID"] = Guid.NewGuid().ToString ().ToUpper ();
                row["工位号"] = opName;
                row["数据来源"] = opNameName;
                row["IP"] = ip;
                row["DbName"] = dbName;

                row["监控组"] = $"{row["监控组"].ToString()}_{opName}";


            }
        }



    }
}
