using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Winson.Framework.DBProviders;
using Winson.Framework.LogProviders;
using Winson.Framework.Utility;
using Winson.EntityOP.Base;
using Winson.EntityOP.Entity;
using Winson.EntityOP.BaseEntityOP;


namespace Winson.EntityOP
{	
	/// <summary>
    /// WType 实体操作类
    /// </summary>
	public class Wtype
    {
        #region 私有变量
        List<WtypeDS> _wtypeList;
        WtypeDS _wtypeDS;
        WtypeOP _op;
        int _count;
        string _cacheKey="WtypeCount";
        string _cacheCriteria = "WtypeCacheCriteria";
        #endregion

        #region 构造函数
        public Wtype()
        {
            _op = new  WtypeOP();
            _wtypeDS = new  WtypeDS();
            _wtypeList = new List< WtypeDS>();
        }
        #endregion

		#region 定义事件
        public event OPEventHandler<Wtype> OnAdded;
        public event OPEventHandler<Wtype> OnBatchAdded;
        public event OPEventHandler<Wtype> OnUpdated;
        public event OPEventHandler<Wtype> OnBatchUpdated;
        public event OPEventHandler<Wtype> OnDeleted;
        public event OPEventHandler<Wtype> OnBatchDeleted;
        #endregion

        #region 实体操作
        /// <summary>
        /// 获取实体
        /// </summary>
        public WtypeDS Entity
        {
            get { return _wtypeDS; }
        }
        /// <summary>
        /// 获取总记录数
        /// </summary>
        /// <returns>记录数</returns>
        public int Count()
        {
            return Count(" 1=1 ");
        }
        /// <summary>
        /// 获取条件记录数
        /// </summary>
        /// <param name="criteria">查询条件</param>
        /// <returns>记录数</returns>
        public int Count(string criteria)
        {
            object _co = CacheHelper.Get(_cacheKey);
            object _cre = CacheHelper.Get(_cacheCriteria);
            if (_co == null || (_co != null && criteria != _cre.ToString()))
            {
                NameValueCollection conditionValue = new NameValueCollection();
                conditionValue["where"] = criteria;
                _count = _op.GetList(conditionValue).Count;

                CacheHelper.Insert(_cacheKey, _count);
                CacheHelper.Insert(_cacheCriteria, criteria);
            }
            else
                _count = Convert.ToInt32(_co);

            return _count;
        }
        /// <summary>
        /// 创建新的实体
        /// </summary>
        public void CreateEntity()
        {
            _wtypeDS = new WtypeDS();
        }
        /// <summary>
        /// 追加实体到集合，以便批量操作
        /// </summary>
        public void AppendEntity()
        {
            _wtypeList.Add(_wtypeDS);
        }
        #endregion        

        #region 查询操作
        /// <summary>
        /// 获取实体集合
        /// </summary>
        /// <param name="conditionValue">
		///	条件参数，有以下3种：
		///	1.如为NULL则获取所有实体
		///	2.如键名为"sql"，则为完整的自定义sql语句
		///	3.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>实体集合</returns>
        public List<WtypeDS> GetList(NameValueCollection conditionValue) 
        {
            return _op.GetList(conditionValue);
        }
        /// <summary>
        /// 分页获取实体集合
        /// </summary>
        /// <param name="limit">每页显示记录数</param>
        /// <param name="currpage">当前页数</param>
        /// <param name="criteria">查询条件,null为查询所有</param>
        /// <param name="orderby">排序字段</param>
        /// <param name="order">排序方式，默认为 ASC</param>
        /// <returns>实体集合</returns>
        public List<WtypeDS> GetList(int limit, int currpage, string criteria, string orderby, string order)
        {            
            NameValueCollection paramValue = new NameValueCollection();
            paramValue["sql"] = _op.GeneratePagerSql("Wtype", limit, currpage, criteria, orderby, order);
            return _op.GetList(paramValue);
        }
        /// <summary>
        /// 从数据库中获取单个实体
        /// </summary>
        /// <param name="conditionValue">
		///	条件参数，有以下3种：
		///	1.如为NULL则获取最后一个新增的实体
		///	2.如键名为"sql"，则为完整的自定义sql语句
		///	3.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>实体</returns>
        public WtypeDS GetEntity(NameValueCollection conditionValue)
        {
            return _op.GetEntity(conditionValue);
        }
        /// <summary>
        /// 从实体集合中获取单个实体
        /// </summary>
        /// <param name="entityList">实体集合</param>
        /// <param name="fieldID">实体ID</param>
        /// <returns>实体</returns>
        public WtypeDS GetEntity(IList entityList, int fieldID)
        {
            return _op.GetEntity(entityList, fieldID);
        }
        /// <summary>
        /// 获取实体，返回DataSet
        /// </summary>
        /// <param name="conditionValue">条件参数，如键名为"sql"，则为自定义条件;如为NULL则获取所有实体</param>
        /// <returns>DataSet数据</returns>
        public DataSet GetDataSet(NameValueCollection conditionValue)
        {
            return _op.GetDataSet(conditionValue);
        }
        #endregion

        #region 单实体操作
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <returns>影响记录数</returns>
        public int Add()
        {
			CacheHelper.Remove(_cacheKey);
            int result = _op.Add(_wtypeDS);
			if (OnAdded != null)
            {
                if (result > 0)
                    OnAdded(this, new OPEvent(_op.GetMaxID() - 1));
                else
                    OnAdded(this, new OPEvent(0));
            }
            return result;
        }
        /// <summary>
        /// 更新实体，直接根据实体主键更新
        /// </summary>
        /// <returns>影响记录数</returns>
        public int Update()
        {
            return this.Update(null);
        }
        /// <summary>
        /// 更新实体，根据输入条件更新
        /// </summary>
        /// <param name="conditionValue">
		///	条件参数，有以下2种：
		///	1.如键名为"sql"，则为完整的自定义sql语句
		///	2.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>
        /// <returns>影响记录数</returns>
        public int Update(NameValueCollection conditionValue)
        {
            int result = _op.Update(_wtypeDS, conditionValue);
			if (OnUpdated != null)
            {
                if (result > 0)
                    OnUpdated(this, new OPEvent(_wtypeDS.Id));
                else
                    OnUpdated(this, new OPEvent(0));
            }
            return result;
        }
        /// <summary>
        /// 删除实体，直接根据实体主键删除
        /// </summary>
        /// <returns>影响记录数</returns>
        public int Delete()
        {
			int result = 0;
            if (_wtypeDS.Id > 0)
            {
				CacheHelper.Remove(_cacheKey);
                NameValueCollection conditionValue = new NameValueCollection();
                conditionValue["Id"] = _wtypeDS.Id.ToString();
                result = this.Delete(conditionValue);
            }
            if (OnDeleted != null)
            {
                if (result > 0)
                    OnDeleted(this, new OPEvent(_wtypeDS.Id));
                else
                    OnDeleted(this, new OPEvent(0));
            }
            return result; 
        }
        /// <summary>
        /// 删除实体，根据输入条件删除
        /// </summary>
        /// <param name="conditionValue">
		///	条件参数，有以下2种：
		///	1.如键名为"sql"，则为完整的自定义sql语句
		///	2.如键名为"where"，则为自定义条件（已包括where）;			
		///	</param>      
        /// <returns>影响记录数</returns>
        public int Delete(NameValueCollection conditionValue)
        {
			int result = 0;
			if (conditionValue != null)
			{
				CacheHelper.Remove(_cacheKey);
				result = _op.Delete(conditionValue);
			}
			if (OnDeleted != null)
            {
                if (result > 0)
                    OnDeleted(this, new OPEvent(_wtypeDS.Id));
                else
                    OnDeleted(this, new OPEvent(0));
            }
            return result;
        }
        #endregion

        #region 批量操作

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <returns>成功返回True 否则返回False</returns>
        public bool AddBatch()
        {
			bool result = false;
			if (_wtypeList.Count > 0)
			{
				CacheHelper.Remove(_cacheKey);
            	result = _op.AddBatch(_wtypeList);
			}
			if (OnBatchAdded != null)
            {
                if (result)
                {
                    string bid = string.Empty;
                    foreach (WtypeDS ds in _wtypeList)
                        bid += ds.Id.ToString() + ",";
                    OnBatchAdded(this, new OPEvent(bid.Substring(0, bid.Length - 1)));
                }
                else
                    OnBatchAdded(this, new OPEvent(null));
            }
            return result;
        }

        /// <summary>
        /// 批量更新实体
        /// </summary>
        /// <returns>成功返回True 否则返回False</returns>
        public bool UpdateBatch()
        {
			bool result = false;
            if (_wtypeList.Count > 0)
            {
				CacheHelper.Remove(_cacheKey);
            	result = _op.UpdateBatch(_wtypeList);
            }
			if (OnBatchUpdated != null)
            {
                if (result)
                {
                    string bid = string.Empty;
                    foreach (WtypeDS ds in _wtypeList)
                        bid += ds.Id.ToString() + ",";
                    OnBatchUpdated(this, new OPEvent(bid.Substring(0, bid.Length - 1)));
                }
                else
                    OnBatchUpdated(this, new OPEvent(null));
            }
            return result;
        }

        /// <summary>
        /// 批量删除实体
        /// </summary>
        /// <returns>成功返回True 否则返回False</returns>
        public bool DeleteBatch()
        {
			bool result = false;
            if (_wtypeList.Count > 0)
            {
				CacheHelper.Remove(_cacheKey);
            	return _op.DeleteBatch(_wtypeList);
			}
			if (OnBatchDeleted != null)
            {
                if (result)
                {
                    string bid = string.Empty;
                    foreach (WtypeDS ds in _wtypeList)
                        bid += ds.Id.ToString() + ",";
                    OnBatchDeleted(this, new OPEvent(bid.Substring(0, bid.Length - 1)));
                }
                else
                    OnBatchDeleted(this, new OPEvent(null));
            }
            return result;
        }
        #endregion
    }
}


