using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QMAPP.FJC.Entity.EnergyManage;
using QMFrameWork.Data;
using QMAPP.Entity;
using System.Data;

namespace QMAPP.FJC.DAL.EnergyManage
{
    /// <summary>
    /// 模块名称:能源仪表
    /// 作    者:张鹏
    /// 编写日期:2017年10月16日
    /// </summary>
    public class MeterDAL
    {

        #region 获取信息
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="">条件</param>
        /// <returns>*信息</returns>
        public Meter Get(Meter info)
        {
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //获取信息
                    info = session.Get<Meter>(info);
                }
                return info;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public MeterReadings GetMaxMeterReadings(MeterReadings info)
        {
            List<DataParameter> parameters = new List<DataParameter>();
            try
            {
                var sql =
                    "SELECT * FROM T_EM_METER_READINGS where READ_TIME=(select max(READ_TIME) from T_EM_METER_READINGS where METER_PID='"+info.METER_PID+"' and READ_RESULT='"+info.READ_RESULT+"')";
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //获取信息
                    info = session.Get<MeterReadings>(sql, parameters.ToArray());
                }
                return info;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public MeterReadings GetMeterReadings(MeterReadings info)
        {
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //获取信息
                    info = session.Get<MeterReadings>(info);
                }
                return info;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取列表
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataPage GetList(Meter condition, DataPage page)
        {
            string sql = null;
            List<DataParameter> parameters = new List<DataParameter>();
            try
            {
                sql = this.GetQuerySql(condition, ref parameters);
                //分页关键字段及排序
                page.KeyName = "PID";
                if (string.IsNullOrEmpty(page.SortExpression))
                    page.SortExpression = "METER_CODE";
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    page = session.GetDataPage<Meter>(sql, parameters.ToArray(), page);
                }
                return page;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取电表读数列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataPage MeterReadingsConfigList(MeterReadings condition, DataPage page)
        {
            string sql = null;
            List<DataParameter> parameters = new List<DataParameter>();
            try
            {
                sql = this.GetQuerySqlMeterReadings(condition, ref parameters);
                //分页关键字段及排序
                page.KeyName = "PID";
                if (string.IsNullOrEmpty(page.SortExpression))
                    page.SortExpression = "READ_TIME desc";
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    page = session.GetDataPage<MeterReadings>(sql, parameters.ToArray(), page);
                }
                return page;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public List<Meter> GetList(Meter condition)
        {
            string sql = null;
            List<DataParameter> parameters = new List<DataParameter>();
            try
            {
                sql = this.GetQuerySql(condition, ref parameters);
                
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    return session.GetList<Meter>(sql, parameters.ToArray()).ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region 获取查询语句
        /// <summary>
        /// 获取查询语句
        /// </summary>
        /// <param name="user">查询条件</param>
        /// <param name="parameters">参数</param>
        /// <returns>查询语句</returns>
        private string GetQuerySql(Meter condition, ref List<DataParameter> parameters)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            StringBuilder whereBuilder = new StringBuilder();
            try
            {
                //构成查询语句
                sqlBuilder.Append("SELECT T.PID,T.METER_CODE,T.METER_NAME,T.METER_TYPE,T.NET_ADDR,T.NET_ID,T.STATE,T.FACTORY_CODE,T.EQPT_CODE,T.RATIO,M.MACHINENAME ");
                sqlBuilder.Append("FROM T_EM_METER T ");
                sqlBuilder.Append("LEFT JOIN T_BD_MACHINEINFO M ON  M.MACHINECODDE=T.EQPT_CODE	 ");
                //whereBuilder.Append(" AND FLGDEL<> '1' ");
                //查询条件
                //设备号

                if (string.IsNullOrEmpty(condition.METER_CODE) == false)
                {
                    whereBuilder.Append(" AND T.METER_CODE LIKE  '%'+" + "@METER_CODE" + "+'%'");
                    parameters.Add(new DataParameter { ParameterName = "METER_CODE", DataType = DbType.String, Value = condition.METER_CODE });
                }
                if (string.IsNullOrEmpty(condition.EQPT_CODE) == false)
                {
                    whereBuilder.Append(" AND T.EQPT_CODE LIKE  '%'+" + "@EQPT_CODE" + "+'%'");
                    parameters.Add(new DataParameter { ParameterName = "EQPT_CODE", DataType = DbType.String, Value = condition.EQPT_CODE });
                }
                //状态 0 作废 1 自动 2 手动
                if (string.IsNullOrEmpty(condition.STATE) == false)
                {
                    whereBuilder.Append(" AND T.STATE= @STATE");
                    parameters.Add(new DataParameter { ParameterName = "STATE", DataType = DbType.String, Value = condition.STATE });
                }

                if (whereBuilder.Length > 0)
                {
                    sqlBuilder.Append(" WHERE " + whereBuilder.ToString().Substring(4));
                }
                return sqlBuilder.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private string GetQuerySqlMeterReadings(MeterReadings condition, ref List<DataParameter> parameters)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            StringBuilder whereBuilder = new StringBuilder();
            try
            {
                //构成查询语句
                sqlBuilder.Append("select T.*,M.METER_CODE,M.METER_NAME,M.METER_TYPE from T_EM_METER_READINGS T ");
                sqlBuilder.Append("LEFT JOIN T_EM_METER M ON  M.PID=T.METER_PID	 ");
                //sqlBuilder.Append("FROM T_EM_METER ");
                //whereBuilder.Append(" AND FLGDEL<> '1' ");
                //查询条件
                //设备号
                if (string.IsNullOrEmpty(condition.METER_PID) == false)
                {
                    whereBuilder.Append(" AND METER_PID= @METER_PID");
                    parameters.Add(new DataParameter { ParameterName = "METER_PID", DataType = DbType.String, Value = condition.METER_PID });
                }
                if (string.IsNullOrEmpty(condition.START_DATE) == false)
                {
                    whereBuilder.Append(" AND READ_TIME >= @START_DATE");
                    parameters.Add(new DataParameter { ParameterName = "START_DATE", DataType = DbType.String, Value = condition.START_DATE });
                }
                if (string.IsNullOrEmpty(condition.END_DATE) == false)
                {
                    whereBuilder.Append(" AND READ_TIME <= @END_DATE");
                    parameters.Add(new DataParameter { ParameterName = "END_DATE", DataType = DbType.String, Value = condition.END_DATE });
                }

                if (whereBuilder.Length > 0)
                {
                    sqlBuilder.Append(" WHERE " + whereBuilder.ToString().Substring(4));
                }
                return sqlBuilder.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 获取导出的数据
        /// <summary>
        /// 获取导出的数据
        /// </summary>
        /// <param name="user">查询条件</param>
        /// <returns>数据</returns>
        public DataTable GetExportData(Meter info)
        {
            DataTable dt = null;
            string sql = null;
            List<DataParameter> parameters = new List<DataParameter>();
            try
            {
                //构成查询语句
                sql = this.GetQuerySql(info, ref parameters);
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    dt = session.GetTable(sql, parameters.ToArray());
                    dt.TableName = "Meter";
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 信息是否重复
        /// <summary>
        /// 判断名称是否存在
        /// </summary>
        /// <param name="info"></param>
        /// <returns>true:已存在;fasel:不存在。</returns>
        public bool Exists(Meter info)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            StringBuilder whereBuilder = new StringBuilder();
            List<DataParameter> parameters = new List<DataParameter>();
            int count = 0;
            try
            {
                sqlBuilder.Append("SELECT COUNT(0) FROM T_EM_METER");
                if (info.PID == null)
                {
                    info.PID = "";
                }
                whereBuilder.Append(" AND PID <> @PID ");
                parameters.Add(new DataParameter { ParameterName = "PID", DataType = DbType.String, Value = info.PID });

                //添加进行无重复字段判断代码

                if (whereBuilder.Length > 0)
                {
                    sqlBuilder.Append(" WHERE " + whereBuilder.ToString().Substring(4));
                }
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    count = Convert.ToInt32(session.ExecuteSqlScalar(sqlBuilder.ToString(), parameters.ToArray()));
                }
                return count > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool ExistsEqptCode(Meter info)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            StringBuilder whereBuilder = new StringBuilder();
            List<DataParameter> parameters = new List<DataParameter>();
            int count = 0;
            try
            {
                sqlBuilder.Append("SELECT COUNT(0) FROM T_EM_METER WHERE METER_TYPE='" + info.METER_TYPE + "' and ( METER_CODE = '" + info.METER_CODE + "'  or EQPT_CODE = '" + info.EQPT_CODE + "' )");
                //if (string.IsNullOrEmpty(info.METER_CODE) == false)
                //{
                //    whereBuilder.Append(" or METER_CODE = @METER_CODE ");
                //    parameters.Add(new DataParameter { ParameterName = "METER_CODE", DataType = DbType.String, Value = info.METER_CODE });
                //}
                //if (string.IsNullOrEmpty(info.EQPT_CODE) == false)
                //{
                //    whereBuilder.Append(" or EQPT_CODE = @EQPT_CODE ");
                //    parameters.Add(new DataParameter { ParameterName = "EQPT_CODE", DataType = DbType.String, Value = info.EQPT_CODE });
                //}

                ////添加进行无重复字段判断代码

                //if (whereBuilder.Length > 0)
                //{
                //    sqlBuilder.Append(" WHERE " + whereBuilder.ToString().Substring(4));
                //}
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    count = Convert.ToInt32(session.ExecuteSqlScalar(sqlBuilder.ToString(), parameters.ToArray()));
                }
                return count > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 插入信息
        /// <summary>
        /// 插入信息(单表)
        /// </summary>
        /// <param name="">信息</param>
        /// <returns>插入行数</returns>
        public int Insert(Meter info)
        {
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //插入基本信息
                    count = session.Insert<Meter>(info);
                }
                return count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public int InsertMeterReadings(MeterReadings info)
        {
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //插入基本信息
                    count = session.Insert<MeterReadings>(info);
                }
                return count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 更新信息
        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name=""></param>
        /// <returns>更新行数</returns>
        public int Update(Meter info)
        {
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //更新基本信息
                    count = session.Update<Meter>(info);
                }
                return count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public int UpdateMeterReadings(MeterReadings info)
        {
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //更新基本信息
                    count = session.Update<MeterReadings>(info);
                }
                return count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 逻辑删除
        /// <summary>
        /// 逻辑删除信息
        /// </summary>
        /// <param name=""></param>
        /// <returns>删除个数</returns>
        public int Delete(Meter info)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            List<DataParameter> parameters = new List<DataParameter>();
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //删除基本信息
                    sqlBuilder.Append("delete T_EM_METER ");
                    //sqlBuilder.Append("SET    FLGDEL = '1' ");
                    sqlBuilder.Append("WHERE  PID = @PID ");
                    parameters.Add(new DataParameter { ParameterName = "PID", DataType = DbType.String, Value = info.PID });
                    count = session.ExecuteSql(sqlBuilder.ToString(), parameters.ToArray());
                    if (count>0)
                    {
                        //删除电量信息。
                        var sql = "delete T_EM_METER_READINGS WHERE  METER_PID = '" + info.PID + "'";
                        session.ExecuteSql(sql, parameters.ToArray());
                    }
                }
                return count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public int DeleteMeterReadings(MeterReadings info)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            List<DataParameter> parameters = new List<DataParameter>();
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //删除基本信息
                    sqlBuilder.Append("delete T_EM_METER_READINGS ");
                    //sqlBuilder.Append("SET    FLGDEL = '1' ");
                    sqlBuilder.Append("WHERE  PID = @PID ");
                    parameters.Add(new DataParameter { ParameterName = "PID", DataType = DbType.String, Value = info.PID });
                    count = session.ExecuteSql(sqlBuilder.ToString(), parameters.ToArray());
                }
                return count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 导入
        public ImportMessage GetImportData(List<Meter> list)
        {
            ImportMessage em = new ImportMessage();
            List<DataParameter> parameters = new List<DataParameter>();
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //设置祖先对象数据会话
                    session.OpenTs();
                    foreach (Meter info in list)
                    {
                        if (info.IsNewInfo)
                        {
                            //插入信息
                            int count = session.Insert<Meter>(info);
                            em.insertNum++;
                        }
                        else
                        {
                            //更新信息
                            int count = session.Update<Meter>(info);
                            em.updateNum++;
                        }
                    }
                    session.CommitTs();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return em;
        }
        #endregion

        /// <summary>
        /// 保存电表读数
        /// </summary>
        /// <param name="meter"></param>
        /// <param name="reading"></param>
        /// <param name="result"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public int SaveReading(Meter meter, double reading,bool result,string error)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            List<DataParameter> parameters = new List<DataParameter>();
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    sqlBuilder.AppendLine("INSERT INTO [T_EM_METER_READINGS] ");
                    sqlBuilder.AppendLine("           ([PID] ");
                    sqlBuilder.AppendLine("           ,[METER_PID] ");
                    sqlBuilder.AppendLine("           ,[READING] ");
                    sqlBuilder.AppendLine("           ,[READ_TIME] ");
                    sqlBuilder.AppendLine("           ,[DIFF_WITH_LAST] ");
                    sqlBuilder.AppendLine("           ,[READ_RESULT] ");
                    sqlBuilder.AppendLine("           ,[ERROR]) ");
                    sqlBuilder.AppendLine("     SELECT NEWID() ");
                    sqlBuilder.AppendLine("           ,@meterid");
                    sqlBuilder.AppendLine("           ,@reading ");
                    sqlBuilder.AppendLine("           ,GETDATE() ");
                    if (result)
                    {
                        sqlBuilder.AppendLine("           ,@reading-ISNULL((SELECT TOP 1 R.READING ");
                        sqlBuilder.AppendLine("                               FROM T_EM_METER_READINGS AS R  ");
                        sqlBuilder.AppendLine("                              WHERE R.METER_PID=@meterid ");
                        sqlBuilder.AppendLine("                                AND R.READ_RESULT='1' ");
                        sqlBuilder.AppendLine("                              ORDER BY R.READ_TIME DESC),0) ");
                    }
                    else
                    {
                        sqlBuilder.AppendLine("           ,0 ");
                    }
                    sqlBuilder.AppendLine("           ,@result ");
                    sqlBuilder.AppendLine("           ,@error ");

                    parameters.Add(new DataParameter("meterid", meter.PID));
                    parameters.Add(new DataParameter("reading", reading));
                    parameters.Add(new DataParameter("result", result ? "1" : "0"));
                    parameters.Add(new DataParameter("error", error));
                    count = session.ExecuteSql(sqlBuilder.ToString(), parameters.ToArray());
                }
                return count;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}