using Highway.Assemble.common;
using Mesnac.Codd.Session;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace Highway.Assemble.Sql
{
    public class DbHandler : ISql
    {
        public static readonly log4net.ILog LogInfo = log4net.LogManager.GetLogger("RollingLogFileAppender"); //Logging 名字要在 App.config 中能找到
        public DbHelper dbHelper;
        public string constr;//= Common.Unity.Instance.sqlstring;//数据库访问字符串

        public DbHandler(string str)
        {
            constr = str;
            initDB();
        }
        /// <summary>
        /// 函数初始化
        /// </summary>
        private void initDB()
        {
            DbSession dbsession = new DbSession(SqlClientFactory.Instance, constr);
            dbHelper = new DbHelper(dbsession);
        }

        /// <summary>
        /// 获取设备信息列表
        /// 对应[dbo].[base_device_info]表
        /// </summary>
        /// <returns>设备信息</returns>
        public List<Equip> GetEquipList(string collectid)
        {

            if (dbHelper == null)
            {
                return null;
            }
            try
            {
                List<Equip> equiplist = new List<Equip>();
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                dbHelper.CommandText = "";
                //string sql = "select * from dbo.base_device_info where adapterid ='"+ adapterId + "'and deleteflag !='1'";
                // 
                string sql = "select dbo.base_device_info.* , dbo.base_device_connectmode.ConnectModeName from dbo.base_device_info left join dbo.base_device_connectmode on dbo.base_device_info.connectmode=dbo.base_device_connectmode.ConnectModeID where collectid ='" + collectid + "'and dbo.base_device_info.deleteflag !='1'";//"select dbo.base_device_info.* , dbo.base_device_connectmode.ConnectModeName from dbo.base_device_info left join dbo.base_device_connectmode on dbo.base_device_info.connectmode=dbo.base_device_connectmode.ConnectModeID where objid ='" + huijiID + "'and dbo.base_device_info.deleteflag !='1'";
                dbHelper.CommandText = sql;

                DataTable dt = dbHelper.ToDataTable();

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        Equip equipcode = new Equip();
                        equipcode.deviceId = row["deviceid"].ToString().Trim();
                        equipcode.deviceName = row["name"].ToString().Trim();
                        equipcode.connectstr = row["connectstr"].ToString().Trim();
                        equipcode.connectModeName = row["connectModeName"].ToString().Trim();
                        equipcode.connectmode = row["connectmode"].ToString().Trim();
                        equipcode.deviceType = row["devicetype"].ToString().Trim();
                        equipcode.collectid = row["collectid"].ToString().Trim();
                        equipcode.addr = row["addr"].ToString().Trim();
                        equiplist.Add(equipcode);
                    }
                    return equiplist;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogInfo.Fatal("获取设备信息失败" + ex.ToString());
                return null;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }


        /// <summary>
        /// 获取传感器信息
        /// 对应[dbo].[base_sensor_info]表
        /// </summary>
        /// <param name="deviceId">设备编号</param>
        /// <returns>传感器信息</returns>
        public List<Sensor> GetSensorList(string deviceId)
        {

            if (dbHelper == null)
            {
                return null;
            }
            try
            {
                List<Sensor> sensorlist = new List<Sensor>();
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                dbHelper.CommandText = "";
                string sql = "select dbo.base_sensor_info.* , dbo.base_sensortype_info.SensorTypeName from dbo.base_sensor_info left join dbo.base_sensortype_info on dbo.base_sensor_info.sensortypeid = dbo.base_sensortype_info.sensortypeid where deviceid = '" + deviceId + "'and dbo.base_sensor_info.deleteflag != '1'";
                dbHelper.CommandText = sql;

                DataTable dt = dbHelper.ToDataTable();

                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        Sensor sensorcode = new Sensor();
                        sensorcode.sensorid = row["sensorid"].ToString().Trim();
                        sensorcode.combineid = row["combineid"].ToString().Trim();
                        sensorcode.sensortypeid = row["sensortypeid"].ToString().Trim();
                        sensorcode.sensorName = row["name"].ToString().Trim();
                        sensorcode.sensorser = row["sensorser"].ToString().Trim();
                        sensorcode.sensorTypeName = row["sensortypename"].ToString().Trim();
                        sensorcode.deviceId = row["deviceid"].ToString().Trim();
                        sensorcode.readInterval = row["readinterval"].ToString().Trim();
                        sensorcode.multData = row["multdata"].ToString().Trim();
                        sensorcode.timeout = row["timedout"].ToString().Trim();
                        sensorcode.returnImm = row["returnimm"].ToString().Trim();
                        sensorcode.CallAdapter = Convert.ToInt16(row["calladapter"]);
                        //sensorcode.CallAdapterid = row["calladapterid"].ToString().Trim();
                        sensorcode.CallCombineID = row["callcombineid"].ToString().Trim();
                        // sensorcode.DelayTime = TryToInt(row["DelayTime"].ToString());
                        sensorcode.mesID = row["MesID"].ToString().Trim();
                        sensorcode.DelayTime = TryToInt(row["DelayTime"].ToString().Trim());
                        sensorcode.ReadCounts = TryToInt(row["ReadCounts"].ToString().Trim());
                        sensorlist.Add(sensorcode);
                    }
                    return sensorlist;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogInfo.Fatal("获取传感器信息失败" + ex.ToString());
                return null;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }
        /// <summary>
        /// 获取汇集软件信息
        /// 对应[dbo].[base_collect_info]表
        /// </summary>
        /// <param name="collectid">汇集软件编号</param>
        /// <returns>汇集软件信息</returns>
        public Collect GetCollectInfo(string collectid)
        {

            Collect collect = new Collect();
            if (dbHelper == null)
            {
                return collect;
            }
            try
            {
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                dbHelper.CommandText = "";
                string sql = "select * from dbo.base_collect_info where collectId='" + collectid + "'";
                dbHelper.CommandText = sql;

                DataTable dt = dbHelper.ToDataTable();

                if (dt != null)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        collect.collectID = dt.Rows[i]["collectId"].ToString();
                        collect.collectName = dt.Rows[i]["collectName"].ToString();
                        collect.Ip = dt.Rows[i]["ip"].ToString();
                        collect.Port = TryToInt(dt.Rows[0]["port"].ToString());
                        return collect;
                    }
                    return collect;
                }
                else
                {
                    return collect;
                }
            }
            catch (Exception ex)
            {
                LogInfo.Fatal("获取服务器Ip错误" + ex.ToString());
                return collect;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }
        /// <summary>
        /// 获取mes设备信息
        /// 对应[dbo].[base_mes_info]表
        /// </summary>
        /// <param name="collectid">汇集软件ID</param>
        /// <returns>mes设备信息</returns>
        public List<mesSoft> GetMesEquipList(string collectid)
        {
            List<mesSoft> mesList = new List<mesSoft>();

            if (dbHelper == null)
            {
                return mesList;
            }
            try
            {
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;//adapterid ="+mesID+"
                dbHelper.CommandText = "";
                string sql = "select * from  dbo.base_mes_info where  deleteflag != '1' and collectid= '" + collectid + "'";
                dbHelper.CommandText = sql;

                DataTable dt = dbHelper.ToDataTable();

                if (dt != null)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        mesSoft mes = new mesSoft();
                        mes.mesid = dt.Rows[i]["mesid"].ToString();
                        mes.adapterName = dt.Rows[i]["name"].ToString();
                        mes.AdatperIP = dt.Rows[i]["ip"].ToString();
                        mes.AdapterPort = dt.Rows[0]["port"].ToString();
                        mesList.Add(mes);
                    }

                    //
                    return mesList;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogInfo.Fatal("获取服务器Ip错误" + ex.ToString());
                return null;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }

        /// <summary>
        /// 插入数据
        /// 对应[dbo].[real_workdata]表
        /// </summary>
        /// <param name="CombID">合并编号</param>
        /// <param name="data">数据</param>
        /// <param name="type">上传数据类型</param>
        /// <returns></returns>
        public bool InsertReadData(string CombID, string data, int type)
        {
            if (dbHelper == null)
            {
                return false;
            }
            try
            {

                var Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                dbHelper.CommandText = "";
                string sql = "INSERT INTO [dbo].[real_workdata]([combineid], [data], [reportmode],[tm]) VALUES ('" + CombID + "','" + data + "','" + type + "','" + Time + "')";
                dbHelper.CommandText = sql;
                dbHelper.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                LogInfo.Fatal("插入数据失败" + ex.ToString());
                return false;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }
        /// <summary>
        /// 设配软件状态
        /// </summary>
        /// 对应[dbo].[base_soft_state]表
        /// <param name="ID">设配软件ID</param>
        /// <param name="Time">获取状态时间</param>
        /// <param name="state">设配软件状态 </param>
        public bool InsertSoftState(string ID, int state)
        {
            try
            {
                var Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                dbHelper.CommandText = "";
                string sql = "INSERT INTO [dbo].[base_soft_state]([softId], [softState], [softTime]) VALUES ('" + ID + "','" + state + "','" + Time + "')";
                dbHelper.CommandText = sql;
                dbHelper.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                LogInfo.Fatal("适配软件状态插入失败" + ex.ToString());
                return false;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }

        /// <summary>
        /// 设备软件状态
        /// </summary>
        /// 对应[dbo].[base_device_state]表
        /// <param name="ID">设备编号</param>
        /// <param name="Time">状态时间</param>
        /// <param name="state">设备状态</param>
        public bool InsertEquipState(string ID, int state)
        {
            try
            {
                var Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                dbHelper.CommandText = "";
                string sql = "INSERT INTO [dbo].[base_device_state]([deviceId], [deviceState], [deviceTime]) VALUES ('" + ID + "','" + state + "','" + Time + "')";
                dbHelper.CommandText = sql;
                dbHelper.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                //LogInfo.Fatal("设备软件状态插入失败" + ex.ToString());
                return false;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }
        /// <summary>
        /// 汇集软件状态
        /// 对应[dbo].[base_collect_state]表
        /// </summary>
        /// <param name="ID">汇集编号</param>
        /// <param name="state">设备状态</param>
        public bool InsertCollectState(string ID, int state)
        {
            if (string.IsNullOrEmpty(ID))
            {
                return false;
            }
            try
            {
                var Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;
                dbHelper.CommandText = "";
                string sql = "INSERT INTO [dbo].[base_collect_state]([collectId],[collectState],[collectTime]) VALUES ('" + ID + "','" + state + "','" + Time + "')";
                dbHelper.CommandText = sql;
                dbHelper.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                LogInfo.Fatal("设备软件状态插入失败" + ex.ToString());
                return false;
            }
            finally
            {
                //dbHelper.CloseConnection();
            }
        }

        private int TryToInt(string str)
        {
            int returnInt = 0;

            if (str == null || str.Trim().Length < 1)
            {
                return returnInt;
            }

            if (int.TryParse(str, out returnInt))
            {
                return returnInt;
            }
            else
            {
                return 0;
            }
        }
    }
}
