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

namespace QMAPP.DAL.Sys
{
    /// <summary>
    /// 系统锁定数据层对象
    /// 创建者:韩磊
    /// 创建日期:2014.12.17
    /// </summary>
    public class SystemLockDAL:BaseDAL
    {
        #region 获取系统锁定信息

        /// <summary>
        /// 获取系统锁定信息
        /// </summary>
        /// <param name="lockInfo">条件</param>
        /// <returns>锁定信息</returns>
        public SystemLockInfo Get(SystemLockInfo lockInfo)
        {
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    lockInfo = session.Get<SystemLockInfo>(lockInfo);
                }

                return lockInfo;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        #endregion

        #region 插入锁定信息

        /// <summary>
        /// 插入锁定信息
        /// </summary>
        /// <param name="lockInfo">锁定信息</param>
        /// <returns>插入数</returns>
        public int Insert(SystemLockInfo lockInfo)
        {
            int count = 0;

            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //插入基本信息
                    count = session.Insert<SystemLockInfo>(lockInfo);
                }
                return count;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        #endregion

        #region 更新系统锁定信息

        /// <summary>
        /// 更新系统锁定信息
        /// </summary>
        /// <param name="lockInfo">锁定信息</param>
        /// <returns>更新个数</returns>
        public int Update(SystemLockInfo lockInfo)
        {
            int count = 0;

            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //更新基本信息
                    count = session.Update<SystemLockInfo>(lockInfo);
                }
                return count;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        #endregion

        #region 删除系统锁定信息

        /// <summary>
        /// 删除系统锁定信息
        /// </summary>
        /// <param name="lockInfo">锁定信息</param>
        /// <returns>删除个数</returns>
        public int Delete(SystemLockInfo lockInfo)
        {
            int count = 0;
            try
            {
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //删除基本信息
                    count = session.Delete<SystemLockInfo>(lockInfo);
                }
                return count;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        #endregion



        #region 获取系统锁定列表

        /// <summary>
        /// 获取系统锁定列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataPage GetList(SystemLockInfo condition, DataPage page)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            StringBuilder whereBuilder = new StringBuilder();
            string sql = null;
            List<DataParameter> parameters = new List<DataParameter>();
            try
            {
                //构成查询语句
                sqlBuilder.Append(" SELECT PID, ");
                sqlBuilder.Append(" STARTTIME,ENDTIME,LOCKREASON ");
                sqlBuilder.Append(" ,CREATEUSER,CREATEDATE,UPDATEUSER,UPDATEDATE  ");
                sqlBuilder.Append(" ,(CASE WHEN VALIDFLG ='0' THEN '否' else '是' end) as VALIDFLG  ");
                sqlBuilder.Append(" FROM T_QM_LOCKINFO  ");

                //查询条件
                if (condition.StartTime != DateTime.MinValue && string.IsNullOrEmpty(condition.StartTime.ToString()) == false)
                {
                    whereBuilder.Append(" AND STARTTIME >= @STARTTIME ");
                    parameters.Add(new DataParameter { ParameterName = "STARTTIME", DataType = DbType.DateTime, Value = condition.StartTime });
                }

                if (condition.EndTime != DateTime.MinValue && string.IsNullOrEmpty(condition.EndTime.ToString()) == false)
                {
                    whereBuilder.Append(" AND ENDTIME<= @ENDTIME");
                    parameters.Add(new DataParameter { ParameterName = "ENDTIME", DataType = DbType.DateTime, Value = condition.EndTime });
                }

                if (string.IsNullOrEmpty(condition.ValidFlg) == false)
                {
                    whereBuilder.Append(" AND VALIDFLG = @VALIDFLG");
                    parameters.Add(new DataParameter { ParameterName = "VALIDFLG", DataType = DbType.String, Value = condition.ValidFlg });
                }

                if (whereBuilder.Length > 0)
                {
                    sqlBuilder.Append(" WHERE  1=1 " + whereBuilder.ToString());
                }


                //分页关键字段及排序
                page.KeyName = "PID";
                if (string.IsNullOrEmpty(page.SortExpression))
                {
                    page.SortExpression = "UPDATEDATE DESC";
                }

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    sql = this.ChangeSqlByDB(sqlBuilder.ToString(), session);
                    page = session.GetDataPage<SystemLockInfo>(sql, parameters.ToArray(), page);
                }

                return page;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        #endregion

        #region 解除锁定

        /// <summary>
        /// 解除锁定
        /// </summary>
        /// <param name="lockInfo"></param>
        public void UnLock(SystemLockInfo lockInfo)
        {
            string sql = null;
            try
            {
                sql = "UPDATE T_QM_LOCKINFO SET VALIDFLG = '0' WHERE PID = @PID";
                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    sql = this.ChangeSqlByDB(sql, session);
                    session.ExecuteSql(sql, new DataParameter("PID",lockInfo.PID));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 判断时候有生效锁定

        /// <summary>
        /// 判断时候有生效锁定
        /// </summary>
        /// <returns>true:具有有效锁定;false:不具有有效锁定</returns>
        public bool IsHaveValidLock()
        {
            int count = 0;
            string sql = null;
            try
            {
                sql = @"SELECT COUNT(*) FROM T_QM_LOCKINFO 
                        WHERE STARTTIME <= @CURRENTTIME AND  ENDTIME >= @CURRENTTIME AND VALIDFLG = '1'";

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    sql = this.ChangeSqlByDB(sql, session);
                    count = int.Parse(session.ExecuteSqlScalar(sql, new DataParameter("CURRENTTIME",DateTime.Now)).ToString());
                }

                if (count == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion
    }
}