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_MerchantsDAL : IQuery<T_BAS_Merchants>
    {
        /// <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("MerchantGuid", 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_Merchants_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_Merchants, 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_Merchants_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_Merchants GetDataByGuid(Guid dataGuid, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = {
											new SqlParameter("@MerchantGuid", 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_Merchants_GetDataByGuid", CommandType.StoredProcedure, parameters, sqlRTransaction);

            T_BAS_Merchants 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_Merchants> dataList)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }

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

            
            foreach (var data in dataList)
            {
                DataRow dr = dataListAdd.NewRow();
                if(data.MerchantGuid != null)
    			    dr["MerchantGuid"] = data.MerchantGuid;
                else
                    dr["MerchantGuid"] = DBNull.Value;
                    
                if(data.WeChatGuid != null)
    			    dr["WeChatGuid"] = data.WeChatGuid;
                else
                    dr["WeChatGuid"] = DBNull.Value;
                    
                if(data.WeChatMenuGuid != null)
    			    dr["WeChatMenuGuid"] = data.WeChatMenuGuid;
                else
                    dr["WeChatMenuGuid"] = DBNull.Value;
                    
                if(data.UserID != null)
    			    dr["UserID"] = data.UserID;
                else
                    dr["UserID"] = DBNull.Value;
                    
                if(data.Password != null)
    			    dr["Password"] = data.Password;
                else
                    dr["Password"] = DBNull.Value;
                    
                if(data.StoreTitle != null)
    			    dr["StoreTitle"] = data.StoreTitle;
                else
                    dr["StoreTitle"] = DBNull.Value;
                    
                if(data.StoreUrl != null)
    			    dr["StoreUrl"] = data.StoreUrl;
                else
                    dr["StoreUrl"] = DBNull.Value;
                    
                if(data.StoreDescription != null)
    			    dr["StoreDescription"] = data.StoreDescription;
                else
                    dr["StoreDescription"] = DBNull.Value;
                    
                if(data.StoreSubtitle != null)
    			    dr["StoreSubtitle"] = data.StoreSubtitle;
                else
                    dr["StoreSubtitle"] = DBNull.Value;
                    
                if(data.StoreIntroduceUrl != null)
    			    dr["StoreIntroduceUrl"] = data.StoreIntroduceUrl;
                else
                    dr["StoreIntroduceUrl"] = DBNull.Value;
                    
                if(data.StoreLogo != null)
    			    dr["StoreLogo"] = data.StoreLogo;
                else
                    dr["StoreLogo"] = DBNull.Value;
                    
                if(data.ButtomLogo != null)
    			    dr["ButtomLogo"] = data.ButtomLogo;
                else
                    dr["ButtomLogo"] = DBNull.Value;
                    
                if(data.ShareImage != null)
    			    dr["ShareImage"] = data.ShareImage;
                else
                    dr["ShareImage"] = DBNull.Value;
                    
                if(data.DistributionBackgroundImgae != null)
    			    dr["DistributionBackgroundImgae"] = data.DistributionBackgroundImgae;
                else
                    dr["DistributionBackgroundImgae"] = DBNull.Value;
                    
                if(data.BusinessIntroduceImage != null)
    			    dr["BusinessIntroduceImage"] = data.BusinessIntroduceImage;
                else
                    dr["BusinessIntroduceImage"] = DBNull.Value;
                    
                if(data.Country != null)
    			    dr["Country"] = data.Country;
                else
                    dr["Country"] = DBNull.Value;
                    
                if(data.Province != null)
    			    dr["Province"] = data.Province;
                else
                    dr["Province"] = DBNull.Value;
                    
                if(data.City != null)
    			    dr["City"] = data.City;
                else
                    dr["City"] = DBNull.Value;
                    
                if(data.Area != null)
    			    dr["Area"] = data.Area;
                else
                    dr["Area"] = DBNull.Value;
                    
                if(data.Address != null)
    			    dr["Address"] = data.Address;
                else
                    dr["Address"] = DBNull.Value;
                    
                if(data.Zip != null)
    			    dr["Zip"] = data.Zip;
                else
                    dr["Zip"] = DBNull.Value;
                    
                if(data.Contact != null)
    			    dr["Contact"] = data.Contact;
                else
                    dr["Contact"] = DBNull.Value;
                    
                if(data.Telephone != null)
    			    dr["Telephone"] = data.Telephone;
                else
                    dr["Telephone"] = DBNull.Value;
                    
                if(data.CustomerName != null)
    			    dr["CustomerName"] = data.CustomerName;
                else
                    dr["CustomerName"] = DBNull.Value;
                    
                if(data.CustomerTelephone != null)
    			    dr["CustomerTelephone"] = data.CustomerTelephone;
                else
                    dr["CustomerTelephone"] = DBNull.Value;
                    
                if(data.TotalDistributionOrders != null)
    			    dr["TotalDistributionOrders"] = data.TotalDistributionOrders;
                else
                    dr["TotalDistributionOrders"] = DBNull.Value;
                    
                if(data.DistributionOrdersAmount != null)
    			    dr["DistributionOrdersAmount"] = data.DistributionOrdersAmount;
                else
                    dr["DistributionOrdersAmount"] = DBNull.Value;
                    
                if(data.TotalDistributor != null)
    			    dr["TotalDistributor"] = data.TotalDistributor;
                else
                    dr["TotalDistributor"] = DBNull.Value;
                    
                if(data.CumulativeDistributionAmount != null)
    			    dr["CumulativeDistributionAmount"] = data.CumulativeDistributionAmount;
                else
                    dr["CumulativeDistributionAmount"] = DBNull.Value;
                    
                if(data.MentionedAmount != null)
    			    dr["MentionedAmount"] = data.MentionedAmount;
                else
                    dr["MentionedAmount"] = DBNull.Value;
                    
                if(data.EMail != null)
    			    dr["EMail"] = data.EMail;
                else
                    dr["EMail"] = DBNull.Value;
                    
                if(data.TradePassword != null)
    			    dr["TradePassword"] = data.TradePassword;
                else
                    dr["TradePassword"] = DBNull.Value;
                    
                if(data.StroeList != null)
    			    dr["StroeList"] = data.StroeList;
                else
                    dr["StroeList"] = DBNull.Value;
                    
                if(data.PriceLable != null)
    			    dr["PriceLable"] = data.PriceLable;
                else
                    dr["PriceLable"] = DBNull.Value;
                    
                if(data.StoreState != null)
    			    dr["StoreState"] = data.StoreState;
                else
                    dr["StoreState"] = DBNull.Value;
                    
                if(data.CloseReason != null)
    			    dr["CloseReason"] = data.CloseReason;
                else
                    dr["CloseReason"] = DBNull.Value;
                    
                if(data.AgentGuid != null)
    			    dr["AgentGuid"] = data.AgentGuid;
                else
                    dr["AgentGuid"] = DBNull.Value;
                    
                if(data.UserType != null)
    			    dr["UserType"] = data.UserType;
                else
                    dr["UserType"] = DBNull.Value;
                    
                if(data.CreateDate != null)
    			    dr["CreateDate"] = data.CreateDate;
                else
                    dr["CreateDate"] = DBNull.Value;
                    
                if(data.ExpireDate != null)
    			    dr["ExpireDate"] = data.ExpireDate;
                else
                    dr["ExpireDate"] = DBNull.Value;
                    
                if(data.HomePageProductNum != null)
    			    dr["HomePageProductNum"] = data.HomePageProductNum;
                else
                    dr["HomePageProductNum"] = DBNull.Value;
                    
                if(data.CustomerServicesGuid != null)
    			    dr["CustomerServicesGuid"] = data.CustomerServicesGuid;
                else
                    dr["CustomerServicesGuid"] = DBNull.Value;
                    
                if(data.IsCustomerServices != null)
    			    dr["IsCustomerServices"] = data.IsCustomerServices;
                else
                    dr["IsCustomerServices"] = DBNull.Value;
                    
                if(data.IsEnable != null)
    			    dr["IsEnable"] = data.IsEnable;
                else
                    dr["IsEnable"] = DBNull.Value;
                    
                if(data.MerchantType != null)
    			    dr["MerchantType"] = data.MerchantType;
                else
                    dr["MerchantType"] = DBNull.Value;
                    
                if(data.TotalSales != null)
    			    dr["TotalSales"] = data.TotalSales;
                else
                    dr["TotalSales"] = DBNull.Value;
                    
                if(data.FsBalance != null)
    			    dr["FsBalance"] = data.FsBalance;
                else
                    dr["FsBalance"] = DBNull.Value;
                    
                if(data.Prestore != null)
    			    dr["Prestore"] = data.Prestore;
                else
                    dr["Prestore"] = DBNull.Value;
                    
                if(data.ComFreeze != null)
    			    dr["ComFreeze"] = data.ComFreeze;
                else
                    dr["ComFreeze"] = DBNull.Value;
                    
                if(data.ComAvailable != null)
    			    dr["ComAvailable"] = data.ComAvailable;
                else
                    dr["ComAvailable"] = 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_Merchants data)
        {
            SqlParameter[] parameters = {
                                            new SqlParameter("@SCreateDate", SqlDbType.DateTime),
                                            new SqlParameter("@SCreateUserName", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@WeChatGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@WeChatMenuGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@UserID", SqlDbType.NVarChar),
											new SqlParameter("@Password", SqlDbType.NVarChar),
											new SqlParameter("@StoreTitle", SqlDbType.NVarChar),
											new SqlParameter("@StoreUrl", SqlDbType.NVarChar),
											new SqlParameter("@StoreDescription", SqlDbType.NVarChar),
											new SqlParameter("@StoreSubtitle", SqlDbType.NVarChar),
											new SqlParameter("@StoreIntroduceUrl", SqlDbType.NVarChar),
											new SqlParameter("@StoreLogo", SqlDbType.NVarChar),
											new SqlParameter("@ButtomLogo", SqlDbType.NVarChar),
											new SqlParameter("@ShareImage", SqlDbType.NVarChar),
											new SqlParameter("@DistributionBackgroundImgae", SqlDbType.NVarChar),
											new SqlParameter("@BusinessIntroduceImage", SqlDbType.NVarChar),
											new SqlParameter("@Country", SqlDbType.NVarChar),
											new SqlParameter("@Province", SqlDbType.NVarChar),
											new SqlParameter("@City", SqlDbType.NVarChar),
											new SqlParameter("@Area", SqlDbType.NVarChar),
											new SqlParameter("@Address", SqlDbType.NVarChar),
											new SqlParameter("@Zip", SqlDbType.NVarChar),
											new SqlParameter("@Contact", SqlDbType.NVarChar),
											new SqlParameter("@Telephone", SqlDbType.NVarChar),
											new SqlParameter("@CustomerName", SqlDbType.NVarChar),
											new SqlParameter("@CustomerTelephone", SqlDbType.NVarChar),
											new SqlParameter("@TotalDistributionOrders", SqlDbType.Int),
											new SqlParameter("@DistributionOrdersAmount", SqlDbType.Decimal),
											new SqlParameter("@TotalDistributor", SqlDbType.Int),
											new SqlParameter("@CumulativeDistributionAmount", SqlDbType.Decimal),
											new SqlParameter("@MentionedAmount", SqlDbType.Decimal),
											new SqlParameter("@EMail", SqlDbType.NVarChar),
											new SqlParameter("@TradePassword", SqlDbType.NVarChar),
											new SqlParameter("@StroeList", SqlDbType.NVarChar),
											new SqlParameter("@PriceLable", SqlDbType.NVarChar),
											new SqlParameter("@StoreState", SqlDbType.Bit),
											new SqlParameter("@CloseReason", SqlDbType.NVarChar),
											new SqlParameter("@AgentGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@UserType", SqlDbType.Int),
											new SqlParameter("@CreateDate", SqlDbType.DateTime),
											new SqlParameter("@ExpireDate", SqlDbType.DateTime),
											new SqlParameter("@HomePageProductNum", SqlDbType.Int),
											new SqlParameter("@CustomerServicesGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@IsCustomerServices", SqlDbType.Bit),
											new SqlParameter("@IsEnable", SqlDbType.Bit),
											new SqlParameter("@MerchantType", SqlDbType.Int),
											new SqlParameter("@TotalSales", SqlDbType.Decimal),
											new SqlParameter("@FsBalance", SqlDbType.Decimal),
											new SqlParameter("@Prestore", SqlDbType.Decimal),
											new SqlParameter("@ComFreeze", SqlDbType.Decimal),
											new SqlParameter("@ComAvailable", SqlDbType.Decimal),
										};
            
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = CurrentManage.UserName;
			parameters[2].Value =  data.MerchantGuid;
            parameters[3].Value = data.MerchantGuid;
            parameters[4].Value = data.WeChatGuid;
            parameters[5].Value = data.WeChatMenuGuid;
            parameters[6].Value = data.UserID;
            parameters[7].Value = data.Password;
            parameters[8].Value = data.StoreTitle;
            parameters[9].Value = data.StoreUrl;
            parameters[10].Value = data.StoreDescription;
            parameters[11].Value = data.StoreSubtitle;
            parameters[12].Value = data.StoreIntroduceUrl;
            parameters[13].Value = data.StoreLogo;
            parameters[14].Value = data.ButtomLogo;
            parameters[15].Value = data.ShareImage;
            parameters[16].Value = data.DistributionBackgroundImgae;
            parameters[17].Value = data.BusinessIntroduceImage;
            parameters[18].Value = data.Country;
            parameters[19].Value = data.Province;
            parameters[20].Value = data.City;
            parameters[21].Value = data.Area;
            parameters[22].Value = data.Address;
            parameters[23].Value = data.Zip;
            parameters[24].Value = data.Contact;
            parameters[25].Value = data.Telephone;
            parameters[26].Value = data.CustomerName;
            parameters[27].Value = data.CustomerTelephone;
            parameters[28].Value = data.TotalDistributionOrders;
            parameters[29].Value = data.DistributionOrdersAmount;
            parameters[30].Value = data.TotalDistributor;
            parameters[31].Value = data.CumulativeDistributionAmount;
            parameters[32].Value = data.MentionedAmount;
            parameters[33].Value = data.EMail;
            parameters[34].Value = data.TradePassword;
            parameters[35].Value = data.StroeList;
            parameters[36].Value = data.PriceLable;
            parameters[37].Value = data.StoreState;
            parameters[38].Value = data.CloseReason;
            parameters[39].Value = data.AgentGuid;
            parameters[40].Value = data.UserType;
            parameters[41].Value = data.CreateDate;
            parameters[42].Value = data.ExpireDate;
            parameters[43].Value = data.HomePageProductNum;
            parameters[44].Value = data.CustomerServicesGuid;
            parameters[45].Value = data.IsCustomerServices;
            parameters[46].Value = data.IsEnable;
            parameters[47].Value = data.MerchantType;
            parameters[48].Value = data.TotalSales;
            parameters[49].Value = data.FsBalance;
            parameters[50].Value = data.Prestore;
            parameters[51].Value = data.ComFreeze;
            parameters[52].Value = data.ComAvailable;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Merchants_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_Merchants>  GetTopData(string top, Expression<Func<T_BAS_Merchants , bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Merchants , 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_Merchants> 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_Merchants> dataList = new List<T_BAS_Merchants>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Merchants_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_Merchants GetFirstData(Expression<Func<T_BAS_Merchants, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Merchants, 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_Merchants 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_Merchants_GetFirstData", CommandType.StoredProcedure, parameters, sqlRTransaction);

            T_BAS_Merchants 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_Merchants, object[]>> valueExpression, Expression<Func<T_BAS_Merchants, 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_Merchants_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_Merchants 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("@MerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@WeChatGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@WeChatMenuGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@UserID", SqlDbType.NVarChar),
											new SqlParameter("@Password", SqlDbType.NVarChar),
											new SqlParameter("@StoreTitle", SqlDbType.NVarChar),
											new SqlParameter("@StoreUrl", SqlDbType.NVarChar),
											new SqlParameter("@StoreDescription", SqlDbType.NVarChar),
											new SqlParameter("@StoreSubtitle", SqlDbType.NVarChar),
											new SqlParameter("@StoreIntroduceUrl", SqlDbType.NVarChar),
											new SqlParameter("@StoreLogo", SqlDbType.NVarChar),
											new SqlParameter("@ButtomLogo", SqlDbType.NVarChar),
											new SqlParameter("@ShareImage", SqlDbType.NVarChar),
											new SqlParameter("@DistributionBackgroundImgae", SqlDbType.NVarChar),
											new SqlParameter("@BusinessIntroduceImage", SqlDbType.NVarChar),
											new SqlParameter("@Country", SqlDbType.NVarChar),
											new SqlParameter("@Province", SqlDbType.NVarChar),
											new SqlParameter("@City", SqlDbType.NVarChar),
											new SqlParameter("@Area", SqlDbType.NVarChar),
											new SqlParameter("@Address", SqlDbType.NVarChar),
											new SqlParameter("@Zip", SqlDbType.NVarChar),
											new SqlParameter("@Contact", SqlDbType.NVarChar),
											new SqlParameter("@Telephone", SqlDbType.NVarChar),
											new SqlParameter("@CustomerName", SqlDbType.NVarChar),
											new SqlParameter("@CustomerTelephone", SqlDbType.NVarChar),
											new SqlParameter("@TotalDistributionOrders", SqlDbType.Int),
											new SqlParameter("@DistributionOrdersAmount", SqlDbType.Decimal),
											new SqlParameter("@TotalDistributor", SqlDbType.Int),
											new SqlParameter("@CumulativeDistributionAmount", SqlDbType.Decimal),
											new SqlParameter("@MentionedAmount", SqlDbType.Decimal),
											new SqlParameter("@EMail", SqlDbType.NVarChar),
											new SqlParameter("@TradePassword", SqlDbType.NVarChar),
											new SqlParameter("@StroeList", SqlDbType.NVarChar),
											new SqlParameter("@PriceLable", SqlDbType.NVarChar),
											new SqlParameter("@StoreState", SqlDbType.Bit),
											new SqlParameter("@CloseReason", SqlDbType.NVarChar),
											new SqlParameter("@AgentGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@UserType", SqlDbType.Int),
											new SqlParameter("@CreateDate", SqlDbType.DateTime),
											new SqlParameter("@ExpireDate", SqlDbType.DateTime),
											new SqlParameter("@HomePageProductNum", SqlDbType.Int),
											new SqlParameter("@CustomerServicesGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@IsCustomerServices", SqlDbType.Bit),
											new SqlParameter("@IsEnable", SqlDbType.Bit),
											new SqlParameter("@MerchantType", SqlDbType.Int),
											new SqlParameter("@TotalSales", SqlDbType.Decimal),
											new SqlParameter("@FsBalance", SqlDbType.Decimal),
											new SqlParameter("@Prestore", SqlDbType.Decimal),
											new SqlParameter("@ComFreeze", SqlDbType.Decimal),
											new SqlParameter("@ComAvailable", 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.MerchantGuid;
			parameters[5].Value = data.WeChatGuid;
			parameters[6].Value = data.WeChatMenuGuid;
			parameters[7].Value = data.UserID;
			parameters[8].Value = data.Password;
			parameters[9].Value = data.StoreTitle;
			parameters[10].Value = data.StoreUrl;
			parameters[11].Value = data.StoreDescription;
			parameters[12].Value = data.StoreSubtitle;
			parameters[13].Value = data.StoreIntroduceUrl;
			parameters[14].Value = data.StoreLogo;
			parameters[15].Value = data.ButtomLogo;
			parameters[16].Value = data.ShareImage;
			parameters[17].Value = data.DistributionBackgroundImgae;
			parameters[18].Value = data.BusinessIntroduceImage;
			parameters[19].Value = data.Country;
			parameters[20].Value = data.Province;
			parameters[21].Value = data.City;
			parameters[22].Value = data.Area;
			parameters[23].Value = data.Address;
			parameters[24].Value = data.Zip;
			parameters[25].Value = data.Contact;
			parameters[26].Value = data.Telephone;
			parameters[27].Value = data.CustomerName;
			parameters[28].Value = data.CustomerTelephone;
			parameters[29].Value = data.TotalDistributionOrders;
			parameters[30].Value = data.DistributionOrdersAmount;
			parameters[31].Value = data.TotalDistributor;
			parameters[32].Value = data.CumulativeDistributionAmount;
			parameters[33].Value = data.MentionedAmount;
			parameters[34].Value = data.EMail;
			parameters[35].Value = data.TradePassword;
			parameters[36].Value = data.StroeList;
			parameters[37].Value = data.PriceLable;
			parameters[38].Value = data.StoreState;
			parameters[39].Value = data.CloseReason;
			parameters[40].Value = data.AgentGuid;
			parameters[41].Value = data.UserType;
			parameters[42].Value = data.CreateDate;
			parameters[43].Value = data.ExpireDate;
			parameters[44].Value = data.HomePageProductNum;
			parameters[45].Value = data.CustomerServicesGuid;
			parameters[46].Value = data.IsCustomerServices;
			parameters[47].Value = data.IsEnable;
			parameters[48].Value = data.MerchantType;
			parameters[49].Value = data.TotalSales;
			parameters[50].Value = data.FsBalance;
			parameters[51].Value = data.Prestore;
			parameters[52].Value = data.ComFreeze;
			parameters[53].Value = data.ComAvailable;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Merchants_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_Merchants> dataList)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }

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

            List<T_BAS_Merchants> dataListUpdate = new List<T_BAS_Merchants>();
            List<string> dataListDelete = new List<string>();            
            StringBuilder sbDelete = new StringBuilder();
            sbDelete.Append(" MerchantGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {
                switch (data.EntityState)
                {
                    case EntityStates.ToBeAdd:
                        DataRow dr = dataListAdd.NewRow();
            			dr["MerchantGuid"] = data.MerchantGuid;
            			dr["WeChatGuid"] = data.WeChatGuid;
            			dr["WeChatMenuGuid"] = data.WeChatMenuGuid;
            			dr["UserID"] = data.UserID;
            			dr["Password"] = data.Password;
            			dr["StoreTitle"] = data.StoreTitle;
            			dr["StoreUrl"] = data.StoreUrl;
            			dr["StoreDescription"] = data.StoreDescription;
            			dr["StoreSubtitle"] = data.StoreSubtitle;
            			dr["StoreIntroduceUrl"] = data.StoreIntroduceUrl;
            			dr["StoreLogo"] = data.StoreLogo;
            			dr["ButtomLogo"] = data.ButtomLogo;
            			dr["ShareImage"] = data.ShareImage;
            			dr["DistributionBackgroundImgae"] = data.DistributionBackgroundImgae;
            			dr["BusinessIntroduceImage"] = data.BusinessIntroduceImage;
            			dr["Country"] = data.Country;
            			dr["Province"] = data.Province;
            			dr["City"] = data.City;
            			dr["Area"] = data.Area;
            			dr["Address"] = data.Address;
            			dr["Zip"] = data.Zip;
            			dr["Contact"] = data.Contact;
            			dr["Telephone"] = data.Telephone;
            			dr["CustomerName"] = data.CustomerName;
            			dr["CustomerTelephone"] = data.CustomerTelephone;
            			dr["TotalDistributionOrders"] = data.TotalDistributionOrders;
            			dr["DistributionOrdersAmount"] = data.DistributionOrdersAmount;
            			dr["TotalDistributor"] = data.TotalDistributor;
            			dr["CumulativeDistributionAmount"] = data.CumulativeDistributionAmount;
            			dr["MentionedAmount"] = data.MentionedAmount;
            			dr["EMail"] = data.EMail;
            			dr["TradePassword"] = data.TradePassword;
            			dr["StroeList"] = data.StroeList;
            			dr["PriceLable"] = data.PriceLable;
            			dr["StoreState"] = data.StoreState;
            			dr["CloseReason"] = data.CloseReason;
            			dr["AgentGuid"] = data.AgentGuid;
            			dr["UserType"] = data.UserType;
            			dr["CreateDate"] = data.CreateDate;
            			dr["ExpireDate"] = data.ExpireDate;
            			dr["HomePageProductNum"] = data.HomePageProductNum;
            			dr["CustomerServicesGuid"] = data.CustomerServicesGuid;
            			dr["IsCustomerServices"] = data.IsCustomerServices;
            			dr["IsEnable"] = data.IsEnable;
            			dr["MerchantType"] = data.MerchantType;
            			dr["TotalSales"] = data.TotalSales;
            			dr["FsBalance"] = data.FsBalance;
            			dr["Prestore"] = data.Prestore;
            			dr["ComFreeze"] = data.ComFreeze;
            			dr["ComAvailable"] = data.ComAvailable;
                        dr["SCreateDate"] = DateTime.Now;
                        dr["SCreateUserName"] = CurrentManage.UserName;
                        dr["SMerchantGuid"] = CurrentManage.SMerchantGuid;
                        dataListAdd.Rows.Add(dr);
                        break;
                    case EntityStates.ToBeDelete:
                        sbDelete.AppendFormat(" '{0}',", data.MerchantGuid);
                        deleteCount++;
                        if (deleteCount == 20)
                        {
                            sbDelete.Append(")");
                            deleteCount = 0;
                            strSql = sbDelete.ToString();
                            dataListDelete.Add(strSql.Replace(",)",") "));
                            sbDelete.Clear();
                            sbDelete.Append(" MerchantGuid in (");
                        }
                        break;
                    case EntityStates.ToBeUpdated:
                        dataListUpdate.Add(data);
                        break;
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " MerchantGuid 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("MerchantGuid = '{0}'",dataGuid),isFilterMerchant);
        }
                
         /// <summary>
        /// 根据条件删除记录
        /// </summary>
        /// <param name="dataGuid">删除条件</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(Expression<Func<T_BAS_Merchants, 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_Merchants> 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(" MerchantGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {              
                sbDelete.AppendFormat(" '{0}',", data.MerchantGuid);
                deleteCount++;
                if (deleteCount == 20)
                {
                    sbDelete.Append(")");
                    deleteCount = 0;
                    strSql = sbDelete.ToString();
                    dataListDelete.Add(strSql.Replace(",)",") "));
                    sbDelete.Clear();
                    sbDelete.Append(" MerchantGuid in (");
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " MerchantGuid 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_Merchants_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_Merchants> GetList(Expression<Func<T_BAS_Merchants, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Merchants, 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_Merchants> 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_Merchants> dataList = new List<T_BAS_Merchants>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Merchants_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_Merchants, 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_Merchants_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_Merchants> GetPageList(int page, int pageSize, out int pageCount, out int recordCount, Expression<Func<T_BAS_Merchants, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Merchants, 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_Merchants> GetPageList(GridModel gridModel, Expression<Func<T_BAS_Merchants, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Merchants, 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_Merchants> 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_Merchants> dataList = new List<T_BAS_Merchants>();
            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_Merchants_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_Merchants LoadModel(SqlDataReader dataReader)
        {
            T_BAS_Merchants data = new T_BAS_Merchants();
			if (dataReader["MerchantGuid"] != DBNull.Value)
				data.MerchantGuid = (Guid)dataReader["MerchantGuid"];
			if (dataReader["WeChatGuid"] != DBNull.Value)
				data.WeChatGuid = (Guid)dataReader["WeChatGuid"];
			if (dataReader["WeChatMenuGuid"] != DBNull.Value)
				data.WeChatMenuGuid = (Guid)dataReader["WeChatMenuGuid"];
			if (dataReader["UserID"] != DBNull.Value)
				data.UserID = (string)dataReader["UserID"];
			if (dataReader["Password"] != DBNull.Value)
				data.Password = (string)dataReader["Password"];
			if (dataReader["StoreTitle"] != DBNull.Value)
				data.StoreTitle = (string)dataReader["StoreTitle"];
			if (dataReader["StoreUrl"] != DBNull.Value)
				data.StoreUrl = (string)dataReader["StoreUrl"];
			if (dataReader["StoreDescription"] != DBNull.Value)
				data.StoreDescription = (string)dataReader["StoreDescription"];
			if (dataReader["StoreSubtitle"] != DBNull.Value)
				data.StoreSubtitle = (string)dataReader["StoreSubtitle"];
			if (dataReader["StoreIntroduceUrl"] != DBNull.Value)
				data.StoreIntroduceUrl = (string)dataReader["StoreIntroduceUrl"];
			if (dataReader["StoreLogo"] != DBNull.Value)
				data.StoreLogo = (string)dataReader["StoreLogo"];
			if (dataReader["ButtomLogo"] != DBNull.Value)
				data.ButtomLogo = (string)dataReader["ButtomLogo"];
			if (dataReader["ShareImage"] != DBNull.Value)
				data.ShareImage = (string)dataReader["ShareImage"];
			if (dataReader["DistributionBackgroundImgae"] != DBNull.Value)
				data.DistributionBackgroundImgae = (string)dataReader["DistributionBackgroundImgae"];
			if (dataReader["BusinessIntroduceImage"] != DBNull.Value)
				data.BusinessIntroduceImage = (string)dataReader["BusinessIntroduceImage"];
			if (dataReader["Country"] != DBNull.Value)
				data.Country = (string)dataReader["Country"];
			if (dataReader["Province"] != DBNull.Value)
				data.Province = (string)dataReader["Province"];
			if (dataReader["City"] != DBNull.Value)
				data.City = (string)dataReader["City"];
			if (dataReader["Area"] != DBNull.Value)
				data.Area = (string)dataReader["Area"];
			if (dataReader["Address"] != DBNull.Value)
				data.Address = (string)dataReader["Address"];
			if (dataReader["Zip"] != DBNull.Value)
				data.Zip = (string)dataReader["Zip"];
			if (dataReader["Contact"] != DBNull.Value)
				data.Contact = (string)dataReader["Contact"];
			if (dataReader["Telephone"] != DBNull.Value)
				data.Telephone = (string)dataReader["Telephone"];
			if (dataReader["CustomerName"] != DBNull.Value)
				data.CustomerName = (string)dataReader["CustomerName"];
			if (dataReader["CustomerTelephone"] != DBNull.Value)
				data.CustomerTelephone = (string)dataReader["CustomerTelephone"];
			if (dataReader["TotalDistributionOrders"] != DBNull.Value)
				data.TotalDistributionOrders = (int)dataReader["TotalDistributionOrders"];
			if (dataReader["DistributionOrdersAmount"] != DBNull.Value)
				data.DistributionOrdersAmount = (decimal)dataReader["DistributionOrdersAmount"];
			if (dataReader["TotalDistributor"] != DBNull.Value)
				data.TotalDistributor = (int)dataReader["TotalDistributor"];
			if (dataReader["CumulativeDistributionAmount"] != DBNull.Value)
				data.CumulativeDistributionAmount = (decimal)dataReader["CumulativeDistributionAmount"];
			if (dataReader["MentionedAmount"] != DBNull.Value)
				data.MentionedAmount = (decimal)dataReader["MentionedAmount"];
			if (dataReader["EMail"] != DBNull.Value)
				data.EMail = (string)dataReader["EMail"];
			if (dataReader["TradePassword"] != DBNull.Value)
				data.TradePassword = (string)dataReader["TradePassword"];
			if (dataReader["StroeList"] != DBNull.Value)
				data.StroeList = (string)dataReader["StroeList"];
			if (dataReader["PriceLable"] != DBNull.Value)
				data.PriceLable = (string)dataReader["PriceLable"];
			if (dataReader["StoreState"] != DBNull.Value)
				data.StoreState = (bool)dataReader["StoreState"];
			if (dataReader["CloseReason"] != DBNull.Value)
				data.CloseReason = (string)dataReader["CloseReason"];
			if (dataReader["SMerchantGuid"] != DBNull.Value)
				data.SMerchantGuid = (Guid)dataReader["SMerchantGuid"];
			if (dataReader["AgentGuid"] != DBNull.Value)
				data.AgentGuid = (Guid)dataReader["AgentGuid"];
			if (dataReader["UserType"] != DBNull.Value)
				data.UserType = (int)dataReader["UserType"];
			if (dataReader["CreateDate"] != DBNull.Value)
				data.CreateDate = (DateTime)dataReader["CreateDate"];
			if (dataReader["ExpireDate"] != DBNull.Value)
				data.ExpireDate = (DateTime)dataReader["ExpireDate"];
			if (dataReader["HomePageProductNum"] != DBNull.Value)
				data.HomePageProductNum = (int)dataReader["HomePageProductNum"];
			if (dataReader["CustomerServicesGuid"] != DBNull.Value)
				data.CustomerServicesGuid = (Guid)dataReader["CustomerServicesGuid"];
			if (dataReader["IsCustomerServices"] != DBNull.Value)
				data.IsCustomerServices = (bool)dataReader["IsCustomerServices"];
			if (dataReader["IsEnable"] != DBNull.Value)
				data.IsEnable = (bool)dataReader["IsEnable"];
			if (dataReader["MerchantType"] != DBNull.Value)
				data.MerchantType = (int)dataReader["MerchantType"];
			if (dataReader["TotalSales"] != DBNull.Value)
				data.TotalSales = (decimal)dataReader["TotalSales"];
			if (dataReader["FsBalance"] != DBNull.Value)
				data.FsBalance = (decimal)dataReader["FsBalance"];
			if (dataReader["Prestore"] != DBNull.Value)
				data.Prestore = (decimal)dataReader["Prestore"];
			if (dataReader["ComFreeze"] != DBNull.Value)
				data.ComFreeze = (decimal)dataReader["ComFreeze"];
			if (dataReader["ComAvailable"] != DBNull.Value)
				data.ComAvailable = (decimal)dataReader["ComAvailable"];
            data.EntityState = EntityStates.Original; 
            return data;
        }
        
          #region IDisposable 成员
        /// <summary>
        /// 回收
        /// </summary>
        public void Dispose()
        {
            sqlRTransaction.Dispose();
        }

        #endregion

    }
}

