using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using SlMesDbIterface;
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using static System.Configuration.ConfigurationManager;

namespace MES_SIGNAL_CONF
{
    public partial class MES_CONF : Form
    {

        static int tagAid = 0;
        public MES_CONF()
        {
            InitializeComponent();
            label_ReadExcel.Text = $"读取位置：{MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile}";
            label_WriteSql.Text = $"写入位置：{MisDataSaveDate.MesServerMisDataFun.ConnectionString_MES}";
        }

        private void btn_ConfigToSql_Click(object sender, EventArgs e)
        {
            WriteLog("正在操作中...");
            LoadOpcData();
            WriteLog("");
        }

        public void WriteLog(string msg)
        {
            txt_Msg.Text = txt_Msg.Text + $"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}]{msg}\r\n";
        }

        private void LoadOpcData()
        {
            DataTable dt_Tag = null;

            Select_Station(out DataTable dt_Station);
            DataTable dt_Tag_Mes = null;
            var dr_Tag_Mes = NPOITest.ExeclHelper.ExcelToDataTable(MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile, "MES_基本变量原始数据", true).Select($"是否启用='1'");
            if (dr_Tag_Mes.Length > 0)
            {
                dt_Tag_Mes = dr_Tag_Mes.CopyToDataTable();
            }
            var dt_Tag_Model = NPOITest.ExeclHelper.ExcelToDataTable(MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile, "MES_信号表模板", true).Select($"是否启用='1'").CopyToDataTable();
            var dt_Tag_Model_DX = NPOITest.ExeclHelper.ExcelToDataTable(MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile, "MES_信号表模板(电芯)", true).Select($"是否启用='1'").CopyToDataTable();
            var dt_Device = NPOITest.ExeclHelper.ExcelToDataTable(MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile, "设备类型对应表", true).Select($"是否启用='1'").CopyToDataTable();

            dt_Tag = dt_Tag_Model.Clone();

            for (int i = 0; i < dt_Station.Rows.Count; i++)
            {
                //[工位号],[工位名称],[PLC],[工位起始DB号],[PX],[PY],[PX_T],[PY_T],[控件启用]
                var dr = dt_Station.Rows[i];
                var 工位代码 = dr["工位代码"].ToString();
                var 工位名称 = dr["工位名称"].ToString();
                var PLC = dr["PLC"].ToString();
                var stationName = dr["工位号"].ToString();
                var PLC代码 = dr["PLC代码"].ToString();
                var 线体类型 = dr["线体类型"].ToString();

                DataTable dt_Tag_Model_Copy = null;
                switch (线体类型)
                {
                    case "1":
                        dt_Tag_Model_Copy = dt_Tag_Model_DX.Copy();
                        break;
                    default:
                        dt_Tag_Model_Copy = dt_Tag_Model.Copy();
                        break;
                }
                UpdateOpTable(dt_Tag_Model_Copy, 工位代码, stationName, 工位名称, PLC, PLC代码);
                dt_Tag.Merge(dt_Tag_Model_Copy);

            }

            dt_Tag.Merge(dt_Tag_Mes);
            //var dt_QC_OP170 = MakeQC();
            //dt_Tag.Merge(dt_QC_OP170);

            dt_Tag.TableName = "MES_基本变量_原始数据";
            SqlOperation.ExecuteSql($"truncate table {dt_Tag.TableName}", out string err1);
            WriteLog($"清空了数据库表：{dt_Tag.TableName}");
            SqlOperation.SqlbulkcopyInsert(dt_Tag, out string err2);
            WriteLog($"写入数据库表：{dt_Tag.TableName}");


            dt_Device.TableName = "MES_基本变量设备类型对应表";
            SqlOperation.ExecuteSql($"truncate table {dt_Device.TableName}", out string err11);
            WriteLog($"清空了数据库表：{dt_Device.TableName}");
            SqlOperation.SqlbulkcopyInsert(dt_Device, out string err22);
            WriteLog($"写入数据库表：{dt_Device.TableName}");

        }


        private void UpdateOpTable(DataTable dt, string 工位代码, string opName, string opNameName, string ip, string dbName)
        {
            foreach (DataRow row in dt.Rows)
            {
                //TagID		TagName   工位号	数据来源	IP	DbName  变量特点  变量类型代码

                var TagID = row["TagID"].ToString();

                row["TagID"] = TagID.Replace("****", 工位代码.PadLeft(4, '0'));
                //row["TagID"] = Guid.NewGuid().ToString ().ToUpper ();
                row["工位号"] = opName;
                row["数据来源"] = opNameName;
                row["IP"] = ip;
                row["DbName"] = dbName;

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


            }
        }


        private void UpdateOpTable(DataRow row, string 工位代码, string opName, string opNameName, string ip, string dbName
            , int startAddr, string tagName, int 列位置)
        {

            tagAid++;
            //TagID	TagName	工位号	数据来源	IP	TagTypeID	TagLong	DbName	变量类型	变量地址	变量其它	
            //演示偏移	列位置	测量位置	测量项目	测量单位	变量类型代码	变量类型名称	机体类型	
            //线体类型	TagAdr	TagAdrDemo	是否启用	监控组	监控时间间隔	OpcServer_OPNAME	变量特点	
            //是否监控	变量排序	工序能力	监控属性代码	测量位置短	上限值	下限值	理论值	IsGoodBad	
            //IsSaveToSql	IsWebSocket	连接名称	OpcServer_MIS	type	序号	高亮

            var 测量项目 = row["测量项目"].ToString();
            if (测量项目.Length > 0)
            {
                测量项目 = $"_{测量项目}";
            }

            row["TagID"] = $"7{工位代码.PadLeft(4, '0')}{tagAid.ToString().PadLeft(4, '0')}";
            row["工位号"] = opName;
            row["数据来源"] = opNameName;
            row["IP"] = ip;
            row["DbName"] = dbName;
            row["监控组"] = $"Group_QC_{opName}";

            row["变量地址"] = $"{startAddr}";
            row["TagName"] = $"{tagName}{测量项目}";
            row["测量位置"] = $"{tagName}{测量项目}";
            row["测量项目"] = $"{tagName}{测量项目}";
            row["变量类型名称"] = $"{tagName}{测量项目}";
            row["列位置"] = 列位置;
        }

        public static void Select_Station(out DataTable dt)
        {
            var sql =
             $" SELECT *" +
             $" FROM [MES_计划BOM_工位与名称] WHERE [工位类型] = 0" +
             $" ORDER BY [工位号]";
            SqlOperation.ExecuteSql(sql, out dt, out string error);
        }


        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void btn_OpenExcel_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile);
        }

        private void btn_MakeData_OP170_Click(object sender, EventArgs e)
        {
            var dt = MakeQC();
        }


        public DataTable MakeQC()
        {
            tagAid = 0;

            DataTable dt_Tag = null;

            Select_Station(out DataTable dt_Station);
            dt_Station = dt_Station.Copy().Select($"工位号='OP170'").CopyToDataTable();

            var dt_Tag_Model = NPOITest.ExeclHelper.ExcelToDataTable(MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile, "MES_质量数据模板", true).Select($"是否启用='1'").CopyToDataTable();
            var dt_Qd_Conf = NPOITest.ExeclHelper.ExcelToDataTable(MisDataSaveDate.MesServerMisDataFun.BasicDataTableFile, "质量数据清单", true).Select($"是否启用='1'").CopyToDataTable();
            dt_Tag = dt_Tag_Model.Clone();

            for (int i = 0; i < dt_Station.Rows.Count; i++)
            {
                //[工位号],[工位名称],[PLC],[工位起始DB号],[PX],[PY],[PX_T],[PY_T],[控件启用]
                var dr = dt_Station.Rows[i];
                var 工位代码 = dr["工位代码"].ToString();
                var 工位名称 = dr["工位名称"].ToString();
                var PLC = dr["PLC"].ToString();
                var stationName = dr["工位号"].ToString();
                var PLC代码 = dr["PLC代码"].ToString();
                var 线体类型 = dr["线体类型"].ToString();

                var 起始地址 = 0;

                for (int k = 0; k < 40; k++)
                {
                    for (int j = 0; j < dt_Qd_Conf.Rows.Count; j++)
                    {
                        //工位号	变量名称	起始地址	长度	类型	是否启用

                        var dr2 = dt_Qd_Conf.Rows[j];
                        var 工位号 = dr2["工位号"].ToString();
                        var 变量名称 = dr2["变量名称"].ToString();
                        if (起始地址 == 0)
                        {
                            起始地址 = Convert.ToInt32(dr2["起始地址"].ToString());
                        }
                        var 长度 = Convert.ToInt32(dr2["长度"].ToString());
                        var 类型 = dr2["类型"].ToString();

                        var 列位置 = j + 1;

                        var dt_Tag_Model_Copy = dt_Tag_Model.Copy();
                        var tagName = $"焊点{k + 1}_{变量名称}";

                        UpdateOpTable(dt_Tag_Model_Copy.Rows[0], 工位代码, stationName, 工位名称, PLC, PLC代码, 起始地址 = 起始地址, tagName, 列位置);
                        UpdateOpTable(dt_Tag_Model_Copy.Rows[1], 工位代码, stationName, 工位名称, PLC, PLC代码, 起始地址 = 起始地址 + 2, tagName, 列位置);
                        UpdateOpTable(dt_Tag_Model_Copy.Rows[2], 工位代码, stationName, 工位名称, PLC, PLC代码, 起始地址 = 起始地址 + 4, tagName, 列位置);
                        UpdateOpTable(dt_Tag_Model_Copy.Rows[3], 工位代码, stationName, 工位名称, PLC, PLC代码, 起始地址 = 起始地址 + 4, tagName, 列位置);
                        起始地址 = 起始地址 + 4;

                        dt_Tag.Merge(dt_Tag_Model_Copy);
                    }
                }

            }
            return dt_Tag;
        }


    }
}
