using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Transactions;
using RFrameGenerate.Model; 
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Common;
using RFramework.SQLQuery;
using RFramework.SQLServer;
using RFramework.SQLServer.Enums;

namespace RFrameGenerate.DAL.SQLServer
{
    internal class T_BAS_ProductsDAL : IQuery<T_BAS_Products>
    {
        /// <summary>
        /// 事务处理
        /// </summary>
        public SqlRTransaction sqlRTransaction { get; set; }
        
        #region IsExist
        
        /// <summary>
        /// 判断记录是否存在，根据记录的GUID值
        /// </summary>
        /// <param name="dataGuid">待判断的记录的GUID值</param>
        /// <returns>返回判断结果，存在为True，不存在为False</returns>
        public bool IsExist(Guid dataGuid, bool isFilterMerchant = true)
        {
            return IsExist("ProductGuid", dataGuid,isFilterMerchant);
        } 
        
		/// <summary>
        /// 判断记录是否存在，根据字段名称和字段值
        /// </summary>
        /// <param name="field">字段名称</param>
        /// <param name="value">字段值</param>
        /// <returns>返回判断结果，存在为True，不存在为False</returns>
        public bool IsExist<T>(string field, T value, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = { 
                                            new SqlParameter("@iCount", SqlDbType.Int),
                                            new SqlParameter("@strField", SqlDbType.NVarChar),
                                            new SqlParameter("@strValue", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = field;
            parameters[2].Value = value.ToString();
            parameters[3].Value = CurrentManage.SMerchantGuid;
            parameters[4].Value = isFilterMerchant;
            try
            {
                SqlHelper.ExecuteNonQuery("PT_BAS_Products_IsExistGuid", CommandType.StoredProcedure, parameters, sqlRTransaction);
                return parameters[0].Value.ToString() != "0" ? true : false;
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("IsExist()参数:strField={0},strValue={1}获取数据出错,异常:{2}", field, value, ex.Message), ex);
            }
        }
         /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="conditionExpression">条件</param>
        /// <returns></returns>
        public bool IsExist(Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterNull = false, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            return IsExist(conditionString,isFilterMerchant);
        }
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="conditionString">条件</param>
        /// <returns></returns>
        public bool IsExist(string conditionString, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = { 
                                            new SqlParameter("@iCount", SqlDbType.Int),
                                            new SqlParameter("@strCondition", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = conditionString;
            parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
            try
            {
                SqlHelper.ExecuteNonQuery("PT_BAS_Products_IsExist", CommandType.StoredProcedure, parameters, sqlRTransaction);
                return parameters[0].Value.ToString() != "0" ? true : false;
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("IsExist()参数:strCondition={0}获取数据出错,异常:{1}", conditionString, ex.Message), ex);
            }
        }   
        #endregion
		
        #region GetDataByGuid
         
        /// <summary>
        /// 获取一条记录，根据记录的GUID值
        /// </summary>
        /// <param name="dataGuid">待获取的记录的GUID值</param>
        /// <returns>返回指定记录，记录不存在则返回Null</returns>
        public T_BAS_Products GetDataByGuid(Guid dataGuid, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = {
											new SqlParameter("@ProductGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit)
										};
            parameters[0].Value = dataGuid;
            parameters[1].Value = CurrentManage.SMerchantGuid;
            parameters[2].Value = isFilterMerchant;
            
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Products_GetDataByGuid", CommandType.StoredProcedure, parameters, sqlRTransaction);

            T_BAS_Products data = null;
            try
            {
                if (dataReader.Read())
                    data = LoadModel(dataReader);
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetDataByGuid()参数:dataGuid={0}获取数据出错,异常:{1}", dataGuid, ex.Message), ex);
            }        
                
            dataReader.Close();
             
            return data;
        }
        #endregion
        
        #region Add
        /// <summary>
        /// 批量更新记录集，根据dataList中各个记录的状态
        /// 记录的状态为ToBeAdd的，新增这条记录到数据库
        /// 记录的状态为ToBeDelete的，删除这条记录到数据库
        /// 记录的状态为ToBeUpdate的，更新这条记录到数据库
        /// 记录的状态为Original的，不对这条记录进行任何操作
        /// </summary>
        /// <param name="dataList">待更新的记录集</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void AddList(List<T_BAS_Products> dataList)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }

            DataTable dataListAdd = SqlHelper.GetTables("T_BAS_Products",sqlRTransaction);

            
            foreach (var data in dataList)
            {
                DataRow dr = dataListAdd.NewRow();
                if(data.ProductGuid != null)
    			    dr["ProductGuid"] = data.ProductGuid;
                else
                    dr["ProductGuid"] = DBNull.Value;
                    
                if(data.ProductCategoryGuid != null)
    			    dr["ProductCategoryGuid"] = data.ProductCategoryGuid;
                else
                    dr["ProductCategoryGuid"] = DBNull.Value;
                    
                if(data.ProductTypeGuid != null)
    			    dr["ProductTypeGuid"] = data.ProductTypeGuid;
                else
                    dr["ProductTypeGuid"] = DBNull.Value;
                    
                if(data.MerchantGuid != null)
    			    dr["MerchantGuid"] = data.MerchantGuid;
                else
                    dr["MerchantGuid"] = DBNull.Value;
                    
                if(data.ProductName != null)
    			    dr["ProductName"] = data.ProductName;
                else
                    dr["ProductName"] = DBNull.Value;
                    
                if(data.ProductUrl != null)
    			    dr["ProductUrl"] = data.ProductUrl;
                else
                    dr["ProductUrl"] = DBNull.Value;
                    
                if(data.QRCodeUrl != null)
    			    dr["QRCodeUrl"] = data.QRCodeUrl;
                else
                    dr["QRCodeUrl"] = DBNull.Value;
                    
                if(data.ProductCode != null)
    			    dr["ProductCode"] = data.ProductCode;
                else
                    dr["ProductCode"] = DBNull.Value;
                    
                if(data.MarketPrice != null)
    			    dr["MarketPrice"] = data.MarketPrice;
                else
                    dr["MarketPrice"] = DBNull.Value;
                    
                if(data.Price != null)
    			    dr["Price"] = data.Price;
                else
                    dr["Price"] = DBNull.Value;
                    
                if(data.MinPrice != null)
    			    dr["MinPrice"] = data.MinPrice;
                else
                    dr["MinPrice"] = DBNull.Value;
                    
                if(data.MaxPrice != null)
    			    dr["MaxPrice"] = data.MaxPrice;
                else
                    dr["MaxPrice"] = DBNull.Value;
                    
                if(data.IsAgentsProduct != null)
    			    dr["IsAgentsProduct"] = data.IsAgentsProduct;
                else
                    dr["IsAgentsProduct"] = DBNull.Value;
                    
                if(data.Inventory != null)
    			    dr["Inventory"] = data.Inventory;
                else
                    dr["Inventory"] = DBNull.Value;
                    
                if(data.Weight != null)
    			    dr["Weight"] = data.Weight;
                else
                    dr["Weight"] = DBNull.Value;
                    
                if(data.SalesVolume != null)
    			    dr["SalesVolume"] = data.SalesVolume;
                else
                    dr["SalesVolume"] = DBNull.Value;
                    
                if(data.BaseSalesVolume != null)
    			    dr["BaseSalesVolume"] = data.BaseSalesVolume;
                else
                    dr["BaseSalesVolume"] = DBNull.Value;
                    
                if(data.ProductImage != null)
    			    dr["ProductImage"] = data.ProductImage;
                else
                    dr["ProductImage"] = DBNull.Value;
                    
                if(data.ProductImage1 != null)
    			    dr["ProductImage1"] = data.ProductImage1;
                else
                    dr["ProductImage1"] = DBNull.Value;
                    
                if(data.ProductImage2 != null)
    			    dr["ProductImage2"] = data.ProductImage2;
                else
                    dr["ProductImage2"] = DBNull.Value;
                    
                if(data.ProductImage3 != null)
    			    dr["ProductImage3"] = data.ProductImage3;
                else
                    dr["ProductImage3"] = DBNull.Value;
                    
                if(data.ProductImage4 != null)
    			    dr["ProductImage4"] = data.ProductImage4;
                else
                    dr["ProductImage4"] = DBNull.Value;
                    
                if(data.ProductImage5 != null)
    			    dr["ProductImage5"] = data.ProductImage5;
                else
                    dr["ProductImage5"] = DBNull.Value;
                    
                if(data.FirstCommission != null)
    			    dr["FirstCommission"] = data.FirstCommission;
                else
                    dr["FirstCommission"] = DBNull.Value;
                    
                if(data.SecondCommission != null)
    			    dr["SecondCommission"] = data.SecondCommission;
                else
                    dr["SecondCommission"] = DBNull.Value;
                    
                if(data.ThirdCommission != null)
    			    dr["ThirdCommission"] = data.ThirdCommission;
                else
                    dr["ThirdCommission"] = DBNull.Value;
                    
                if(data.IsDefault != null)
    			    dr["IsDefault"] = data.IsDefault;
                else
                    dr["IsDefault"] = DBNull.Value;
                    
                if(data.Description != null)
    			    dr["Description"] = data.Description;
                else
                    dr["Description"] = DBNull.Value;
                    
                if(data.InventoryWay != null)
    			    dr["InventoryWay"] = data.InventoryWay;
                else
                    dr["InventoryWay"] = DBNull.Value;
                    
                if(data.Recommend != null)
    			    dr["Recommend"] = data.Recommend;
                else
                    dr["Recommend"] = DBNull.Value;
                    
                if(data.Quota != null)
    			    dr["Quota"] = data.Quota;
                else
                    dr["Quota"] = DBNull.Value;
                    
                if(data.IsPutaway != null)
    			    dr["IsPutaway"] = data.IsPutaway;
                else
                    dr["IsPutaway"] = DBNull.Value;
                    
                if(data.Sort != null)
    			    dr["Sort"] = data.Sort;
                else
                    dr["Sort"] = DBNull.Value;
                    
                if(data.IsProperty != null)
    			    dr["IsProperty"] = data.IsProperty;
                else
                    dr["IsProperty"] = DBNull.Value;
                    
                if(data.IsStandards != null)
    			    dr["IsStandards"] = data.IsStandards;
                else
                    dr["IsStandards"] = DBNull.Value;
                    
                if(data.PutawayDate != null)
    			    dr["PutawayDate"] = data.PutawayDate;
                else
                    dr["PutawayDate"] = DBNull.Value;
                    
                if(data.OriginalProductGuid != null)
    			    dr["OriginalProductGuid"] = data.OriginalProductGuid;
                else
                    dr["OriginalProductGuid"] = DBNull.Value;
                    
                if(data.AgentsIsPutaway != null)
    			    dr["AgentsIsPutaway"] = data.AgentsIsPutaway;
                else
                    dr["AgentsIsPutaway"] = DBNull.Value;
                    
                if(data.TemplatesGuid != null)
    			    dr["TemplatesGuid"] = data.TemplatesGuid;
                else
                    dr["TemplatesGuid"] = DBNull.Value;
                    
                if(data.CommissionType != null)
    			    dr["CommissionType"] = data.CommissionType;
                else
                    dr["CommissionType"] = DBNull.Value;
                    
                if(data.FirstCommissionAmount != null)
    			    dr["FirstCommissionAmount"] = data.FirstCommissionAmount;
                else
                    dr["FirstCommissionAmount"] = DBNull.Value;
                    
                if(data.SecondCommissionAmount != null)
    			    dr["SecondCommissionAmount"] = data.SecondCommissionAmount;
                else
                    dr["SecondCommissionAmount"] = DBNull.Value;
                    
                if(data.ThirdCommissionAmount != null)
    			    dr["ThirdCommissionAmount"] = data.ThirdCommissionAmount;
                else
                    dr["ThirdCommissionAmount"] = DBNull.Value;
                    
                if(data.NoDelivery != null)
    			    dr["NoDelivery"] = data.NoDelivery;
                else
                    dr["NoDelivery"] = DBNull.Value;
                    
                if(data.NoReceive != null)
    			    dr["NoReceive"] = data.NoReceive;
                else
                    dr["NoReceive"] = DBNull.Value;
                    
                if(data.CategoryCode != null)
    			    dr["CategoryCode"] = data.CategoryCode;
                else
                    dr["CategoryCode"] = DBNull.Value;
                    
                if(data.ProductClassify != null)
    			    dr["ProductClassify"] = data.ProductClassify;
                else
                    dr["ProductClassify"] = DBNull.Value;
                    
                if(data.AgentPrice != null)
    			    dr["AgentPrice"] = data.AgentPrice;
                else
                    dr["AgentPrice"] = DBNull.Value;
                    
                dr["SCreateDate"] = DateTime.Now;
                dr["SCreateUserName"] = CurrentManage.UserName;
                if (data.SMerchantGuid != null && data.SMerchantGuid != Guid.Empty)
                    dr["SMerchantGuid"] = data.SMerchantGuid;
                else
                    dr["SMerchantGuid"] = CurrentManage.SMerchantGuid;
                dataListAdd.Rows.Add(dr);
            }
            
            #region 更新到数据库
            if (dataListAdd.Rows.Count>0)
            { 
            //添加
            SqlHelper.BatchAddData(new DataTable[] { dataListAdd }, sqlRTransaction);
            }
            #endregion

            if (istran == true)
                sqlRTransaction.Commit();

            dataListAdd.Clear();
        }
        /// <summary>
        /// 新增一条记录
        /// </summary>
        /// <param name="data">待新增的记录</param>
        /// <returns>返回新增结果，成功为True，失败为False</returns>
        public void Add(T_BAS_Products data)
        {
            SqlParameter[] parameters = {
                                            new SqlParameter("@SCreateDate", SqlDbType.DateTime),
                                            new SqlParameter("@SCreateUserName", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@ProductGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@ProductCategoryGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@ProductTypeGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@ProductName", SqlDbType.NVarChar),
											new SqlParameter("@ProductUrl", SqlDbType.NVarChar),
											new SqlParameter("@QRCodeUrl", SqlDbType.NVarChar),
											new SqlParameter("@ProductCode", SqlDbType.NVarChar),
											new SqlParameter("@MarketPrice", SqlDbType.Decimal),
											new SqlParameter("@Price", SqlDbType.Decimal),
											new SqlParameter("@MinPrice", SqlDbType.Decimal),
											new SqlParameter("@MaxPrice", SqlDbType.Decimal),
											new SqlParameter("@IsAgentsProduct", SqlDbType.Bit),
											new SqlParameter("@Inventory", SqlDbType.Int),
											new SqlParameter("@Weight", SqlDbType.Int),
											new SqlParameter("@SalesVolume", SqlDbType.Decimal),
											new SqlParameter("@BaseSalesVolume", SqlDbType.Decimal),
											new SqlParameter("@ProductImage", SqlDbType.Xml),
											new SqlParameter("@ProductImage1", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage2", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage3", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage4", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage5", SqlDbType.NVarChar),
											new SqlParameter("@FirstCommission", SqlDbType.Decimal),
											new SqlParameter("@SecondCommission", SqlDbType.Decimal),
											new SqlParameter("@ThirdCommission", SqlDbType.Decimal),
											new SqlParameter("@IsDefault", SqlDbType.Bit),
											new SqlParameter("@Description", SqlDbType.NVarChar),
											new SqlParameter("@InventoryWay", SqlDbType.Int),
											new SqlParameter("@Recommend", SqlDbType.Bit),
											new SqlParameter("@Quota", SqlDbType.Int),
											new SqlParameter("@IsPutaway", SqlDbType.Bit),
											new SqlParameter("@Sort", SqlDbType.Int),
											new SqlParameter("@IsProperty", SqlDbType.Bit),
											new SqlParameter("@IsStandards", SqlDbType.Bit),
											new SqlParameter("@PutawayDate", SqlDbType.DateTime),
											new SqlParameter("@OriginalProductGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@AgentsIsPutaway", SqlDbType.Bit),
											new SqlParameter("@TemplatesGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@CommissionType", SqlDbType.Int),
											new SqlParameter("@FirstCommissionAmount", SqlDbType.Decimal),
											new SqlParameter("@SecondCommissionAmount", SqlDbType.Decimal),
											new SqlParameter("@ThirdCommissionAmount", SqlDbType.Decimal),
											new SqlParameter("@NoDelivery", SqlDbType.Bit),
											new SqlParameter("@NoReceive", SqlDbType.Bit),
											new SqlParameter("@CategoryCode", SqlDbType.VarChar),
											new SqlParameter("@ProductClassify", SqlDbType.Int),
											new SqlParameter("@AgentPrice", SqlDbType.Decimal),
										};
            
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = CurrentManage.UserName;
            if (data.SMerchantGuid != null && data.SMerchantGuid != Guid.Empty)
                parameters[2].Value = data.SMerchantGuid;
            else
                parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = data.ProductGuid;
            parameters[4].Value = data.ProductCategoryGuid;
            parameters[5].Value = data.ProductTypeGuid;
            parameters[6].Value = data.MerchantGuid;
            parameters[7].Value = data.ProductName;
            parameters[8].Value = data.ProductUrl;
            parameters[9].Value = data.QRCodeUrl;
            parameters[10].Value = data.ProductCode;
            parameters[11].Value = data.MarketPrice;
            parameters[12].Value = data.Price;
            parameters[13].Value = data.MinPrice;
            parameters[14].Value = data.MaxPrice;
            parameters[15].Value = data.IsAgentsProduct;
            parameters[16].Value = data.Inventory;
            parameters[17].Value = data.Weight;
            parameters[18].Value = data.SalesVolume;
            parameters[19].Value = data.BaseSalesVolume;
            parameters[20].Value = data.ProductImage;
            parameters[21].Value = data.ProductImage1;
            parameters[22].Value = data.ProductImage2;
            parameters[23].Value = data.ProductImage3;
            parameters[24].Value = data.ProductImage4;
            parameters[25].Value = data.ProductImage5;
            parameters[26].Value = data.FirstCommission;
            parameters[27].Value = data.SecondCommission;
            parameters[28].Value = data.ThirdCommission;
            parameters[29].Value = data.IsDefault;
            parameters[30].Value = data.Description;
            parameters[31].Value = data.InventoryWay;
            parameters[32].Value = data.Recommend;
            parameters[33].Value = data.Quota;
            parameters[34].Value = data.IsPutaway;
            parameters[35].Value = data.Sort;
            parameters[36].Value = data.IsProperty;
            parameters[37].Value = data.IsStandards;
            parameters[38].Value = data.PutawayDate;
            parameters[39].Value = data.OriginalProductGuid;
            parameters[40].Value = data.AgentsIsPutaway;
            parameters[41].Value = data.TemplatesGuid;
            parameters[42].Value = data.CommissionType;
            parameters[43].Value = data.FirstCommissionAmount;
            parameters[44].Value = data.SecondCommissionAmount;
            parameters[45].Value = data.ThirdCommissionAmount;
            parameters[46].Value = data.NoDelivery;
            parameters[47].Value = data.NoReceive;
            parameters[48].Value = data.CategoryCode;
            parameters[49].Value = data.ProductClassify;
            parameters[50].Value = data.AgentPrice;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Products_Add", CommandType.StoredProcedure, parameters, sqlRTransaction);
                bool result = rowsAffected != -1 ? true : false;
                if(result == false)
                    throw new Exception("新增数据失败");
            }
            catch(Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Add()参数:data={0}添加数据出错,异常:{1}", data.ToString(), ex.Message), ex);
            }
        }
        #endregion
        
        #region Top
        /// <summary>
        /// 获取前Top，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_Products>  GetTopData(string top, Expression<Func<T_BAS_Products , bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Products , object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default, LockType flag = LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();

            return GetTopData(top,conditionString, orderString, orderMethod, flag,isFilterMerchant);
        }

        /// <summary>
        /// 获取Top，根据查询条件及排序字段、排序方法
        /// </summary>
        /// <param name="top"></param>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的第一条记录，记录不存在则返回Null</returns>
        public List<T_BAS_Products> GetTopData(string top,string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default, LockType flag = LockType.Default, bool isFilterMerchant = true)
        {
            if (string.IsNullOrEmpty(top) == true)
            {
                throw new Exception("top不能为空,例:top=6或top=10%");
            }
            if (top.Contains("%"))
            {
                top = string.Format(" top {0} percent ", top.Replace("%",string.Empty));
            }
            else
            {
                top = string.Format(" top {0} ", top);
            }

            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
            SqlParameter[] parameters = {
								            new SqlParameter("@top", SqlDbType.NVarChar), 
								            new SqlParameter("@strCondition", SqlDbType.NVarChar), 
								            new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Value = top.Trim();
            parameters[1].Value = conditionString.Trim();
            parameters[2].Value = orderString.Trim();
            parameters[3].Value = flag.ToSqlLock();
            parameters[4].Value = CurrentManage.SMerchantGuid;
            if (orderString.Trim() != string.Empty)
                parameters[2].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";
            parameters[5].Value = isFilterMerchant;

             List<T_BAS_Products> dataList = new List<T_BAS_Products>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Products_GetTopData",CommandType.StoredProcedure, parameters, sqlRTransaction);

			try
            {
                while (dataReader.Read())
                {
                    dataList.Add(LoadModel(dataReader));
                }
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetTopData获取数据出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
    						
            return dataList;             
        }

        #endregion
		
        #region GetFirstData
        
		/// <summary>
        /// 获取第一条记录，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public T_BAS_Products GetFirstData(Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Products, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            
            return GetFirstData(conditionString, orderString, orderMethod, flag,isFilterMerchant);        
        }

        /// <summary>
        /// 获取第一条记录，根据查询条件及排序字段、排序方法
        /// </summary>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的第一条记录，记录不存在则返回Null</returns>
        public T_BAS_Products GetFirstData(string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
            SqlParameter[] parameters = {
								            new SqlParameter("@strCondition", SqlDbType.NVarChar), 
								            new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Value = conditionString.Trim();
            parameters[1].Value = orderString.Trim();
            parameters[2].Value = flag.ToSqlLock();
            parameters[3].Value = CurrentManage.SMerchantGuid;
            if (orderString.Trim() != string.Empty)
                parameters[1].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";
            parameters[4].Value = isFilterMerchant;
                
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Products_GetFirstData", CommandType.StoredProcedure, parameters, sqlRTransaction);

            T_BAS_Products data = null;
            try
            {
                if (dataReader.Read())
                    data = LoadModel(dataReader);
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetFirstData()参数:conditionString={0}获取数据出错,异常:{1}", conditionString, ex.Message), ex);
            }         
            dataReader.Close();
            
            return data;
        }
        #endregion

        #region Update
        /// 更新一条记录
        /// </summary>
        /// <param name="valueExpression">待更新的记录</param>
        /// <param name="conditionExpression">要更新的条件</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void Update(Expression<Func<T_BAS_Products, object[]>> valueExpression, Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterMerchant = true)
        {            
            QueryTranslator query = new QueryTranslator();
            string value = query.Translate(valueExpression).Replace(")(", ",").Substring(1);
            value = value.Substring(0, value.Length - 1);
            string condition = query.Translate(conditionExpression);
            if (condition == string.Empty)
                throw new Exception("删除条件不能为null或空");


            SqlParameter[] parameters = {
                                            new SqlParameter("@value", SqlDbType.NVarChar),
                                            new SqlParameter("@strCondition", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
										};

            parameters[0].Value = value;
            parameters[1].Value = condition;
			parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
            try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Products_SingleUpdate", CommandType.StoredProcedure, parameters, sqlRTransaction);
                bool result = rowsAffected != -1 ? true : false;

                if (result == false)
                    throw new Exception("更新数据失败");
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Update()参数:conditionString={0}更新数据失败,异常:{1}", condition, ex.Message), ex);
            }
        }
        /// <summary>
        /// 更新一条记录
        /// </summary>
        /// <param name="data">待更新的记录</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>
        public void Update(T_BAS_Products data, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = {
                                            new SqlParameter("@SUpdateDate", SqlDbType.DateTime),
                                            new SqlParameter("@SUpdateUserName", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
											new SqlParameter("@ProductGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@ProductCategoryGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@ProductTypeGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@ProductName", SqlDbType.NVarChar),
											new SqlParameter("@ProductUrl", SqlDbType.NVarChar),
											new SqlParameter("@QRCodeUrl", SqlDbType.NVarChar),
											new SqlParameter("@ProductCode", SqlDbType.NVarChar),
											new SqlParameter("@MarketPrice", SqlDbType.Decimal),
											new SqlParameter("@Price", SqlDbType.Decimal),
											new SqlParameter("@MinPrice", SqlDbType.Decimal),
											new SqlParameter("@MaxPrice", SqlDbType.Decimal),
											new SqlParameter("@IsAgentsProduct", SqlDbType.Bit),
											new SqlParameter("@Inventory", SqlDbType.Int),
											new SqlParameter("@Weight", SqlDbType.Int),
											new SqlParameter("@SalesVolume", SqlDbType.Decimal),
											new SqlParameter("@BaseSalesVolume", SqlDbType.Decimal),
											new SqlParameter("@ProductImage", SqlDbType.Xml),
											new SqlParameter("@ProductImage1", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage2", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage3", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage4", SqlDbType.NVarChar),
											new SqlParameter("@ProductImage5", SqlDbType.NVarChar),
											new SqlParameter("@FirstCommission", SqlDbType.Decimal),
											new SqlParameter("@SecondCommission", SqlDbType.Decimal),
											new SqlParameter("@ThirdCommission", SqlDbType.Decimal),
											new SqlParameter("@IsDefault", SqlDbType.Bit),
											new SqlParameter("@Description", SqlDbType.NVarChar),
											new SqlParameter("@InventoryWay", SqlDbType.Int),
											new SqlParameter("@Recommend", SqlDbType.Bit),
											new SqlParameter("@Quota", SqlDbType.Int),
											new SqlParameter("@IsPutaway", SqlDbType.Bit),
											new SqlParameter("@Sort", SqlDbType.Int),
											new SqlParameter("@IsProperty", SqlDbType.Bit),
											new SqlParameter("@IsStandards", SqlDbType.Bit),
											new SqlParameter("@PutawayDate", SqlDbType.DateTime),
											new SqlParameter("@OriginalProductGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@AgentsIsPutaway", SqlDbType.Bit),
											new SqlParameter("@TemplatesGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@CommissionType", SqlDbType.Int),
											new SqlParameter("@FirstCommissionAmount", SqlDbType.Decimal),
											new SqlParameter("@SecondCommissionAmount", SqlDbType.Decimal),
											new SqlParameter("@ThirdCommissionAmount", SqlDbType.Decimal),
											new SqlParameter("@NoDelivery", SqlDbType.Bit),
											new SqlParameter("@NoReceive", SqlDbType.Bit),
											new SqlParameter("@CategoryCode", SqlDbType.VarChar),
											new SqlParameter("@ProductClassify", SqlDbType.Int),
											new SqlParameter("@AgentPrice", SqlDbType.Decimal),
										};										
			
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = CurrentManage.UserName;
            parameters[2].Value = data.SMerchantGuid==null ? CurrentManage.SMerchantGuid : data.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
			parameters[4].Value = data.ProductGuid;
			parameters[5].Value = data.ProductCategoryGuid;
			parameters[6].Value = data.ProductTypeGuid;
			parameters[7].Value = data.MerchantGuid;
			parameters[8].Value = data.ProductName;
			parameters[9].Value = data.ProductUrl;
			parameters[10].Value = data.QRCodeUrl;
			parameters[11].Value = data.ProductCode;
			parameters[12].Value = data.MarketPrice;
			parameters[13].Value = data.Price;
			parameters[14].Value = data.MinPrice;
			parameters[15].Value = data.MaxPrice;
			parameters[16].Value = data.IsAgentsProduct;
			parameters[17].Value = data.Inventory;
			parameters[18].Value = data.Weight;
			parameters[19].Value = data.SalesVolume;
			parameters[20].Value = data.BaseSalesVolume;
			parameters[21].Value = data.ProductImage;
			parameters[22].Value = data.ProductImage1;
			parameters[23].Value = data.ProductImage2;
			parameters[24].Value = data.ProductImage3;
			parameters[25].Value = data.ProductImage4;
			parameters[26].Value = data.ProductImage5;
			parameters[27].Value = data.FirstCommission;
			parameters[28].Value = data.SecondCommission;
			parameters[29].Value = data.ThirdCommission;
			parameters[30].Value = data.IsDefault;
			parameters[31].Value = data.Description;
			parameters[32].Value = data.InventoryWay;
			parameters[33].Value = data.Recommend;
			parameters[34].Value = data.Quota;
			parameters[35].Value = data.IsPutaway;
			parameters[36].Value = data.Sort;
			parameters[37].Value = data.IsProperty;
			parameters[38].Value = data.IsStandards;
			parameters[39].Value = data.PutawayDate;
			parameters[40].Value = data.OriginalProductGuid;
			parameters[41].Value = data.AgentsIsPutaway;
			parameters[42].Value = data.TemplatesGuid;
			parameters[43].Value = data.CommissionType;
			parameters[44].Value = data.FirstCommissionAmount;
			parameters[45].Value = data.SecondCommissionAmount;
			parameters[46].Value = data.ThirdCommissionAmount;
			parameters[47].Value = data.NoDelivery;
			parameters[48].Value = data.NoReceive;
			parameters[49].Value = data.CategoryCode;
			parameters[50].Value = data.ProductClassify;
			parameters[51].Value = data.AgentPrice;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Products_Update", CommandType.StoredProcedure, parameters, sqlRTransaction);
                bool result = rowsAffected != -1 ? true : false;
                
                if (result == false)
                    throw new Exception("更新数据失败");
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Update()参数:conditionString={0}更新数据失败,异常:{1}", data.ToString(), ex.Message), ex);
            }
        }
        
        /// <summary>
        /// 批量更新记录集，根据dataList中各个记录的状态
        /// 记录的状态为ToBeAdd的，新增这条记录到数据库
        /// 记录的状态为ToBeDelete的，删除这条记录到数据库
        /// 记录的状态为ToBeUpdate的，更新这条记录到数据库
        /// 记录的状态为Original的，不对这条记录进行任何操作
        /// </summary>
        /// <param name="dataList">待更新的记录集</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void UpdateList(List<T_BAS_Products> dataList)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }

            DataTable dataListAdd = SqlHelper.GetTables("T_BAS_Products",sqlRTransaction);

            List<T_BAS_Products> dataListUpdate = new List<T_BAS_Products>();
            List<string> dataListDelete = new List<string>();            
            StringBuilder sbDelete = new StringBuilder();
            sbDelete.Append(" ProductGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {
                switch (data.EntityState)
                {
                    case EntityStates.ToBeAdd:
                        DataRow dr = dataListAdd.NewRow();
            			dr["ProductGuid"] = data.ProductGuid;
            			dr["ProductCategoryGuid"] = data.ProductCategoryGuid;
            			dr["ProductTypeGuid"] = data.ProductTypeGuid;
            			dr["MerchantGuid"] = data.MerchantGuid;
            			dr["ProductName"] = data.ProductName;
            			dr["ProductUrl"] = data.ProductUrl;
            			dr["QRCodeUrl"] = data.QRCodeUrl;
            			dr["ProductCode"] = data.ProductCode;
            			dr["MarketPrice"] = data.MarketPrice;
            			dr["Price"] = data.Price;
            			dr["MinPrice"] = data.MinPrice;
            			dr["MaxPrice"] = data.MaxPrice;
            			dr["IsAgentsProduct"] = data.IsAgentsProduct;
            			dr["Inventory"] = data.Inventory;
            			dr["Weight"] = data.Weight;
            			dr["SalesVolume"] = data.SalesVolume;
            			dr["BaseSalesVolume"] = data.BaseSalesVolume;
            			dr["ProductImage"] = data.ProductImage;
            			dr["ProductImage1"] = data.ProductImage1;
            			dr["ProductImage2"] = data.ProductImage2;
            			dr["ProductImage3"] = data.ProductImage3;
            			dr["ProductImage4"] = data.ProductImage4;
            			dr["ProductImage5"] = data.ProductImage5;
            			dr["FirstCommission"] = data.FirstCommission;
            			dr["SecondCommission"] = data.SecondCommission;
            			dr["ThirdCommission"] = data.ThirdCommission;
            			dr["IsDefault"] = data.IsDefault;
            			dr["Description"] = data.Description;
            			dr["InventoryWay"] = data.InventoryWay;
            			dr["Recommend"] = data.Recommend;
            			dr["Quota"] = data.Quota;
            			dr["IsPutaway"] = data.IsPutaway;
            			dr["Sort"] = data.Sort;
            			dr["IsProperty"] = data.IsProperty;
            			dr["IsStandards"] = data.IsStandards;
            			dr["PutawayDate"] = data.PutawayDate;
            			dr["OriginalProductGuid"] = data.OriginalProductGuid;
            			dr["AgentsIsPutaway"] = data.AgentsIsPutaway;
            			dr["TemplatesGuid"] = data.TemplatesGuid;
            			dr["CommissionType"] = data.CommissionType;
            			dr["FirstCommissionAmount"] = data.FirstCommissionAmount;
            			dr["SecondCommissionAmount"] = data.SecondCommissionAmount;
            			dr["ThirdCommissionAmount"] = data.ThirdCommissionAmount;
            			dr["NoDelivery"] = data.NoDelivery;
            			dr["NoReceive"] = data.NoReceive;
            			dr["CategoryCode"] = data.CategoryCode;
            			dr["ProductClassify"] = data.ProductClassify;
            			dr["AgentPrice"] = data.AgentPrice;
                        dr["SCreateDate"] = DateTime.Now;
                        dr["SCreateUserName"] = CurrentManage.UserName;
                        dr["SMerchantGuid"] = CurrentManage.SMerchantGuid;
                        dataListAdd.Rows.Add(dr);
                        break;
                    case EntityStates.ToBeDelete:
                        sbDelete.AppendFormat(" '{0}',", data.ProductGuid);
                        deleteCount++;
                        if (deleteCount == 20)
                        {
                            sbDelete.Append(")");
                            deleteCount = 0;
                            strSql = sbDelete.ToString();
                            dataListDelete.Add(strSql.Replace(",)",") "));
                            sbDelete.Clear();
                            sbDelete.Append(" ProductGuid in (");
                        }
                        break;
                    case EntityStates.ToBeUpdated:
                        dataListUpdate.Add(data);
                        break;
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " ProductGuid in (")
            {
                sbDelete.Append(")");
                strSql = sbDelete.ToString();
                dataListDelete.Add(strSql.Replace(",)",") "));
                sbDelete.Clear();
            }

            #region 更新到数据库
            if (dataListAdd.Rows.Count>0)
            { 
            //添加
            SqlHelper.BatchAddData(new DataTable[] { dataListAdd }, sqlRTransaction);
            }
            //修改
            foreach(var v in dataListUpdate)
            {
                Update(v);
            }
            //删除
            foreach(var v in dataListDelete)
            {
                Delete(v);
            }
            #endregion

            if (istran == true)
                sqlRTransaction.Commit();

            dataListAdd.Clear();
            dataListUpdate.Clear();
            dataListDelete.Clear();
            dataList.ForEach(a => a.EntityState = EntityStates.Original);
        }

        #endregion
         
        #region Delete
        /// <summary>
        /// 删除一条记录，根据记录的GUID值
        /// </summary>
        /// <param name="dataGuid">待删除的记录的GUID值</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(Guid dataGuid, bool isFilterMerchant = true)
        { 
			Delete(string.Format("ProductGuid = '{0}'",dataGuid),isFilterMerchant);
        }
                
         /// <summary>
        /// 根据条件删除记录
        /// </summary>
        /// <param name="dataGuid">删除条件</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterMerchant = true)
        { 
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            Delete(conditionString,isFilterMerchant);
        }
        
        /// <summary>
        /// 批量删除数据
        /// 记录的状态为ToBeAdd的，新增这条记录到数据库
        /// 记录的状态为ToBeDelete的，删除这条记录到数据库
        /// 记录的状态为ToBeUpdate的，更新这条记录到数据库
        /// 记录的状态为Original的，不对这条记录进行任何操作
        /// </summary>
        /// <param name="dataList">待更新的记录集</param>
        /// <returns>返回更新结果，成功为True，失败为False</returns>        
        public void DeleteList(List<T_BAS_Products> dataList, bool isFilterMerchant = true)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }
            List<string> dataListDelete = new List<string>();            
            StringBuilder sbDelete = new StringBuilder();
            sbDelete.Append(" ProductGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {              
                sbDelete.AppendFormat(" '{0}',", data.ProductGuid);
                deleteCount++;
                if (deleteCount == 20)
                {
                    sbDelete.Append(")");
                    deleteCount = 0;
                    strSql = sbDelete.ToString();
                    dataListDelete.Add(strSql.Replace(",)",") "));
                    sbDelete.Clear();
                    sbDelete.Append(" ProductGuid in (");
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " ProductGuid in (")
            {
                sbDelete.Append(")");
                strSql = sbDelete.ToString();
                dataListDelete.Add(strSql.Replace(",)",") "));
                sbDelete.Clear();
            }

            #region 更新到数据库           
            //删除
            foreach(var v in dataListDelete)
            {
                Delete(v,isFilterMerchant);
            }
            #endregion

            if (istran == true)
                sqlRTransaction.Commit();

            dataListDelete.Clear();
        }
        
         /// <summary>
        /// 根据条件删除记录
        /// </summary>
        /// <param name="dataGuid">删除条件</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(string conditionString = "", bool isFilterMerchant = true)
        {
            if (conditionString == null || conditionString ==String.Empty)
                throw new Exception("删除条件不能为null或空");
            SqlParameter[] parameters =
            {
                new SqlParameter("@strCondition", SqlDbType.NVarChar),
                new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
            };
            parameters[0].Value = conditionString; 
            parameters[1].Value = CurrentManage.SMerchantGuid;
            parameters[2].Value = isFilterMerchant;
            try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Products_Delete", CommandType.StoredProcedure, parameters, sqlRTransaction);
                
                if(rowsAffected == -1)
                    throw new Exception("删除数据失败");
            }
            catch (Exception ex)
            {
                Dispose();
                throw new Exception(string.Format("Delete()参数:conditionString={0}删除数据失败,异常:{1}", conditionString, ex.Message), ex);
            }
        }
        
        #endregion
        
        #region GetList
         
		/// <summary>
        /// 获取记录集，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_Products> GetList(Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Products, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            
            return GetList(conditionString, orderString, orderMethod, flag,isFilterMerchant);
         }
        
        /// <summary>
        /// 获取记录集，根据查询条件及排序字段、排序方法
        /// </summary>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_Products> GetList(string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
			SqlParameter[] parameters = {
											new SqlParameter("@strCondition", SqlDbType.NVarChar), 
											new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
										};
            parameters[0].Value = conditionString.Trim();
            parameters[1].Value = orderString.Trim();
            parameters[2].Value = flag.ToSqlLock();
            parameters[3].Value = CurrentManage.SMerchantGuid;
            parameters[4].Value = isFilterMerchant;
			if (orderString.Trim() != string.Empty)
				parameters[1].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";
			
            List<T_BAS_Products> dataList = new List<T_BAS_Products>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Products_GetList",CommandType.StoredProcedure, parameters, sqlRTransaction);

			try
            {
                while (dataReader.Read())
                {
                    dataList.Add(LoadModel(dataReader));
                }
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetList获取数据出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
    						
            return dataList;             
        }	
        
        #endregion
        
        #region GetCount
		
		/// <summary>
        /// 获取记录数，根据查询条件Lambda表达式
        /// </summary>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <returns>返回满足条件的记录集</returns>
        public int GetCount(Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterNull = false, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
            return GetCount(conditionString,isFilterMerchant);
        }

        /// <summary>
        /// 获取记录数，根据查询条件
        /// </summary>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <returns>返回满足条件的记录数</returns>
        public int GetCount(string conditionString = "", bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty; 
            SqlParameter[] parameters = {
											new SqlParameter("@strCondition", SqlDbType.NVarChar),
                                            new SqlParameter("@iRecordCount", SqlDbType.Int),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
										};
            parameters[0].Value = conditionString.Trim();
            parameters[1].Direction = ParameterDirection.Output;
            parameters[2].Value = CurrentManage.SMerchantGuid;
            parameters[3].Value = isFilterMerchant;
            int recordCount;
            SqlDataReader dataReader =  SqlHelper.ExecuteReader("PT_BAS_Products_GetCount", CommandType.StoredProcedure, parameters, sqlRTransaction);
            try
            {
                recordCount = (int)parameters[1].Value;
            }
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetCount获取总记录出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
            
            return recordCount;
        } 
        
        #endregion
        
        #region GetPageList
		
		/// <summary>
        /// 获取记录集，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="page">页号</param>
        /// <param name="pageSize">每页的记录数</param>
        /// <param name="pageCount">返回总页数</param>
        /// <param name="recordCount">返回总记录数</param>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_Products> GetPageList(int page, int pageSize, out int pageCount, out int recordCount, Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Products, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);
            string orderString = string.Empty;
            if (orderExpression != null)
                orderString = where.Translate(orderExpression);
            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();
           
            return GetPageList(page, pageSize,out pageCount, out recordCount, conditionString, orderString, orderMethod, flag,isFilterMerchant);
        }
        /// <summary>
        /// 获取记录集，根据查询条件Lambda表达式及排序字段Lambda表达式、排序方法
        /// </summary>
        /// <param name="gridModel">查询条件</param>
        /// <param name="conditionExpression">查询条件Lambda表达式</param>
        /// <param name="orderString">排序字段Lambda表达式，字段间用“+”号连接</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集</returns>
        public List<T_BAS_Products> GetPageList(GridModel gridModel, Expression<Func<T_BAS_Products, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Products, object>> orderExpression = null, OrderMethods orderMethod = OrderMethods.Default, LockType flag = LockType.Default, bool isFilterMerchant = true)
        {
            return GetPageList(gridModel.page, gridModel.rows, out gridModel.pageCount, out gridModel.recordCount, conditionExpression,isFilterNull, orderExpression, orderMethod, flag,isFilterMerchant);
        }
        /// <summary>
        /// 获取记录集，根据查询条件及排序字段、排序方法，分页
        /// </summary>      
        /// <param name="page">页号</param>
        /// <param name="pageSize">每页的记录数</param>
        /// <param name="pageCount">返回总页数</param>
        /// <param name="recordCount">返回总记录数</param>
        /// <param name="conditionString">查询条件字符串，SQL语句中的WHERE表达式</param>
        /// <param name="orderString">排序字段字符串，SQL语句中的OrderBy表达式，字段间用“,”号隔开</param>
        /// <param name="orderMethod">排序方法，升序或降序排列</param>
        /// <returns>返回满足条件的记录集，分页</returns>
        public List<T_BAS_Products> GetPageList(int page, int pageSize, out int pageCount, out int recordCount, string conditionString = "", string orderString = "", OrderMethods orderMethod = OrderMethods.Default,LockType flag=LockType.Default, bool isFilterMerchant = true)
        { 
            if (conditionString == null)
                conditionString = string.Empty;
            if (orderString == null)
                orderString = string.Empty;
            List<T_BAS_Products> dataList = new List<T_BAS_Products>();
            SqlParameter[] parameters = {
											new SqlParameter("@iPage", SqlDbType.Int),
											new SqlParameter("@iPageSize", SqlDbType.Int),
											new SqlParameter("@iPageCount", SqlDbType.Int),
											new SqlParameter("@iRecordCount", SqlDbType.Int),
											new SqlParameter("@strCondition", SqlDbType.NVarChar),
										    new SqlParameter("@strOrder", SqlDbType.NVarChar),
                                            new SqlParameter("@strLockType", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                                            new SqlParameter("@isFilterMerchant", SqlDbType.Bit),
                                        };
            parameters[0].Value = page;
            parameters[1].Value = pageSize;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;
            parameters[4].Value = conditionString.Trim();
            parameters[5].Value = orderString.Trim();
            parameters[6].Value = flag.ToSqlLock();
            parameters[7].Value = CurrentManage.SMerchantGuid;
            parameters[8].Value = isFilterMerchant;
			if (orderString.Trim() != string.Empty)
				parameters[5].Value += orderMethod == OrderMethods.DESC ? " DESC" : " ASC";			
			
			SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Products_GetPageList",CommandType.StoredProcedure, parameters,sqlRTransaction);
            try
            {
                while (dataReader.Read())
                {
                    dataList.Add(LoadModel(dataReader));
                }
			}
            catch (Exception ex)
            {
                dataReader.Close();
                Dispose();
                throw new Exception(string.Format("GetPageList获取数据记录出错,conditionString={0},异常:{1}", conditionString, ex.Message), ex);
            }
            dataReader.Close();
			
            pageCount = (int)parameters[2].Value;
            recordCount = (int)parameters[3].Value;
			
            return dataList;
        }
        
        #endregion
   
        /// <summary>
        /// 获取记录实体，从 DataReader 的当前记录装载
        /// </summary>
        /// <param name="dataReader">DataReader 对象</param>
        /// <returns>返回 DataReader 里下一条记录，记录不存在则返回Null</returns>
        private T_BAS_Products LoadModel(SqlDataReader dataReader)
        {
            T_BAS_Products data = new T_BAS_Products();
			if (dataReader["ProductGuid"] != DBNull.Value)
				data.ProductGuid = (Guid)dataReader["ProductGuid"];
			if (dataReader["ProductCategoryGuid"] != DBNull.Value)
				data.ProductCategoryGuid = (Guid)dataReader["ProductCategoryGuid"];
			if (dataReader["ProductTypeGuid"] != DBNull.Value)
				data.ProductTypeGuid = (Guid)dataReader["ProductTypeGuid"];
			if (dataReader["MerchantGuid"] != DBNull.Value)
				data.MerchantGuid = (Guid)dataReader["MerchantGuid"];
			if (dataReader["ProductName"] != DBNull.Value)
				data.ProductName = (string)dataReader["ProductName"];
			if (dataReader["ProductUrl"] != DBNull.Value)
				data.ProductUrl = (string)dataReader["ProductUrl"];
			if (dataReader["QRCodeUrl"] != DBNull.Value)
				data.QRCodeUrl = (string)dataReader["QRCodeUrl"];
			if (dataReader["ProductCode"] != DBNull.Value)
				data.ProductCode = (string)dataReader["ProductCode"];
			if (dataReader["MarketPrice"] != DBNull.Value)
				data.MarketPrice = (decimal)dataReader["MarketPrice"];
			if (dataReader["Price"] != DBNull.Value)
				data.Price = (decimal)dataReader["Price"];
			if (dataReader["MinPrice"] != DBNull.Value)
				data.MinPrice = (decimal)dataReader["MinPrice"];
			if (dataReader["MaxPrice"] != DBNull.Value)
				data.MaxPrice = (decimal)dataReader["MaxPrice"];
			if (dataReader["IsAgentsProduct"] != DBNull.Value)
				data.IsAgentsProduct = (bool)dataReader["IsAgentsProduct"];
			if (dataReader["Inventory"] != DBNull.Value)
				data.Inventory = (int)dataReader["Inventory"];
			if (dataReader["Weight"] != DBNull.Value)
				data.Weight = (int)dataReader["Weight"];
			if (dataReader["SalesVolume"] != DBNull.Value)
				data.SalesVolume = (decimal)dataReader["SalesVolume"];
			if (dataReader["BaseSalesVolume"] != DBNull.Value)
				data.BaseSalesVolume = (decimal)dataReader["BaseSalesVolume"];
			if (dataReader["ProductImage"] != DBNull.Value)
				data.ProductImage = (string)dataReader["ProductImage"];
			if (dataReader["ProductImage1"] != DBNull.Value)
				data.ProductImage1 = (string)dataReader["ProductImage1"];
			if (dataReader["ProductImage2"] != DBNull.Value)
				data.ProductImage2 = (string)dataReader["ProductImage2"];
			if (dataReader["ProductImage3"] != DBNull.Value)
				data.ProductImage3 = (string)dataReader["ProductImage3"];
			if (dataReader["ProductImage4"] != DBNull.Value)
				data.ProductImage4 = (string)dataReader["ProductImage4"];
			if (dataReader["ProductImage5"] != DBNull.Value)
				data.ProductImage5 = (string)dataReader["ProductImage5"];
			if (dataReader["FirstCommission"] != DBNull.Value)
				data.FirstCommission = (decimal)dataReader["FirstCommission"];
			if (dataReader["SecondCommission"] != DBNull.Value)
				data.SecondCommission = (decimal)dataReader["SecondCommission"];
			if (dataReader["ThirdCommission"] != DBNull.Value)
				data.ThirdCommission = (decimal)dataReader["ThirdCommission"];
			if (dataReader["IsDefault"] != DBNull.Value)
				data.IsDefault = (bool)dataReader["IsDefault"];
			if (dataReader["Description"] != DBNull.Value)
				data.Description = (string)dataReader["Description"];
			if (dataReader["InventoryWay"] != DBNull.Value)
				data.InventoryWay = (int)dataReader["InventoryWay"];
			if (dataReader["Recommend"] != DBNull.Value)
				data.Recommend = (bool)dataReader["Recommend"];
			if (dataReader["Quota"] != DBNull.Value)
				data.Quota = (int)dataReader["Quota"];
			if (dataReader["IsPutaway"] != DBNull.Value)
				data.IsPutaway = (bool)dataReader["IsPutaway"];
			if (dataReader["Sort"] != DBNull.Value)
				data.Sort = (int)dataReader["Sort"];
			if (dataReader["IsProperty"] != DBNull.Value)
				data.IsProperty = (bool)dataReader["IsProperty"];
			if (dataReader["IsStandards"] != DBNull.Value)
				data.IsStandards = (bool)dataReader["IsStandards"];
			if (dataReader["SMerchantGuid"] != DBNull.Value)
				data.SMerchantGuid = (Guid)dataReader["SMerchantGuid"];
			if (dataReader["PutawayDate"] != DBNull.Value)
				data.PutawayDate = (DateTime)dataReader["PutawayDate"];
			if (dataReader["OriginalProductGuid"] != DBNull.Value)
				data.OriginalProductGuid = (Guid)dataReader["OriginalProductGuid"];
			if (dataReader["AgentsIsPutaway"] != DBNull.Value)
				data.AgentsIsPutaway = (bool)dataReader["AgentsIsPutaway"];
			if (dataReader["TemplatesGuid"] != DBNull.Value)
				data.TemplatesGuid = (Guid)dataReader["TemplatesGuid"];
			if (dataReader["CommissionType"] != DBNull.Value)
				data.CommissionType = (int)dataReader["CommissionType"];
			if (dataReader["FirstCommissionAmount"] != DBNull.Value)
				data.FirstCommissionAmount = (decimal)dataReader["FirstCommissionAmount"];
			if (dataReader["SecondCommissionAmount"] != DBNull.Value)
				data.SecondCommissionAmount = (decimal)dataReader["SecondCommissionAmount"];
			if (dataReader["ThirdCommissionAmount"] != DBNull.Value)
				data.ThirdCommissionAmount = (decimal)dataReader["ThirdCommissionAmount"];
			if (dataReader["NoDelivery"] != DBNull.Value)
				data.NoDelivery = (bool)dataReader["NoDelivery"];
			if (dataReader["NoReceive"] != DBNull.Value)
				data.NoReceive = (bool)dataReader["NoReceive"];
			if (dataReader["CategoryCode"] != DBNull.Value)
				data.CategoryCode = (string)dataReader["CategoryCode"];
			if (dataReader["ProductClassify"] != DBNull.Value)
				data.ProductClassify = (int)dataReader["ProductClassify"];
			if (dataReader["AgentPrice"] != DBNull.Value)
				data.AgentPrice = (decimal)dataReader["AgentPrice"];
            data.EntityState = EntityStates.Original; 
            return data;
        }
        
          #region IDisposable 成员
        /// <summary>
        /// 回收
        /// </summary>
        public void Dispose()
        {
            sqlRTransaction.Dispose();
        }

        #endregion

    }
}

