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_OrdersDAL : IQuery<T_BAS_Orders>
    {
        /// <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("OrderGuid", 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_Orders_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_Orders, 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_Orders_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_Orders GetDataByGuid(Guid dataGuid, bool isFilterMerchant = true)
        {
            SqlParameter[] parameters = {
											new SqlParameter("@OrderGuid", 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_Orders_GetDataByGuid", CommandType.StoredProcedure, parameters, sqlRTransaction);

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

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

            
            foreach (var data in dataList)
            {
                DataRow dr = dataListAdd.NewRow();
                if(data.OrderGuid != null)
    			    dr["OrderGuid"] = data.OrderGuid;
                else
                    dr["OrderGuid"] = DBNull.Value;
                    
                if(data.LogisticrGuid != null)
    			    dr["LogisticrGuid"] = data.LogisticrGuid;
                else
                    dr["LogisticrGuid"] = DBNull.Value;
                    
                if(data.MemberGuid != null)
    			    dr["MemberGuid"] = data.MemberGuid;
                else
                    dr["MemberGuid"] = DBNull.Value;
                    
                if(data.MerchantGuid != null)
    			    dr["MerchantGuid"] = data.MerchantGuid;
                else
                    dr["MerchantGuid"] = DBNull.Value;
                    
                if(data.RecieverAddressGuid != null)
    			    dr["RecieverAddressGuid"] = data.RecieverAddressGuid;
                else
                    dr["RecieverAddressGuid"] = DBNull.Value;
                    
                if(data.DistributionPropGuid != null)
    			    dr["DistributionPropGuid"] = data.DistributionPropGuid;
                else
                    dr["DistributionPropGuid"] = DBNull.Value;
                    
                if(data.MerchantPayWayGuid != null)
    			    dr["MerchantPayWayGuid"] = data.MerchantPayWayGuid;
                else
                    dr["MerchantPayWayGuid"] = DBNull.Value;
                    
                if(data.OrderNo != null)
    			    dr["OrderNo"] = data.OrderNo;
                else
                    dr["OrderNo"] = DBNull.Value;
                    
                if(data.OrderInnerState != null)
    			    dr["OrderInnerState"] = data.OrderInnerState;
                else
                    dr["OrderInnerState"] = DBNull.Value;
                    
                if(data.OrderState != null)
    			    dr["OrderState"] = data.OrderState;
                else
                    dr["OrderState"] = DBNull.Value;
                    
                if(data.OrderTime != null)
    			    dr["OrderTime"] = data.OrderTime;
                else
                    dr["OrderTime"] = DBNull.Value;
                    
                if(data.PayTime != null)
    			    dr["PayTime"] = data.PayTime;
                else
                    dr["PayTime"] = DBNull.Value;
                    
                if(data.CompletedTime != null)
    			    dr["CompletedTime"] = data.CompletedTime;
                else
                    dr["CompletedTime"] = DBNull.Value;
                    
                if(data.PayAccount != null)
    			    dr["PayAccount"] = data.PayAccount;
                else
                    dr["PayAccount"] = DBNull.Value;
                    
                if(data.PayWay != null)
    			    dr["PayWay"] = data.PayWay;
                else
                    dr["PayWay"] = DBNull.Value;
                    
                if(data.DeliveryTime != null)
    			    dr["DeliveryTime"] = data.DeliveryTime;
                else
                    dr["DeliveryTime"] = DBNull.Value;
                    
                if(data.PayNO != null)
    			    dr["PayNO"] = data.PayNO;
                else
                    dr["PayNO"] = DBNull.Value;
                    
                if(data.Remark != null)
    			    dr["Remark"] = data.Remark;
                else
                    dr["Remark"] = DBNull.Value;
                    
                if(data.OrderSource != null)
    			    dr["OrderSource"] = data.OrderSource;
                else
                    dr["OrderSource"] = DBNull.Value;
                    
                if(data.TotalMoney != null)
    			    dr["TotalMoney"] = data.TotalMoney;
                else
                    dr["TotalMoney"] = DBNull.Value;
                    
                if(data.IsExtendReceiving != null)
    			    dr["IsExtendReceiving"] = data.IsExtendReceiving;
                else
                    dr["IsExtendReceiving"] = DBNull.Value;
                    
                if(data.ExtendDay != null)
    			    dr["ExtendDay"] = data.ExtendDay;
                else
                    dr["ExtendDay"] = DBNull.Value;
                    
                if(data.IsDistribute != null)
    			    dr["IsDistribute"] = data.IsDistribute;
                else
                    dr["IsDistribute"] = DBNull.Value;
                    
                if(data.Quantity != null)
    			    dr["Quantity"] = data.Quantity;
                else
                    dr["Quantity"] = DBNull.Value;
                    
                if(data.IsComment != null)
    			    dr["IsComment"] = data.IsComment;
                else
                    dr["IsComment"] = DBNull.Value;
                    
                if(data.TransactionID != null)
    			    dr["TransactionID"] = data.TransactionID;
                else
                    dr["TransactionID"] = DBNull.Value;
                    
                if(data.Package != null)
    			    dr["Package"] = data.Package;
                else
                    dr["Package"] = DBNull.Value;
                    
                if(data.Freight != null)
    			    dr["Freight"] = data.Freight;
                else
                    dr["Freight"] = DBNull.Value;
                    
                if(data.RecieverAddressInfo != null)
    			    dr["RecieverAddressInfo"] = data.RecieverAddressInfo;
                else
                    dr["RecieverAddressInfo"] = DBNull.Value;
                    
                if(data.PrivilegelMoney != null)
    			    dr["PrivilegelMoney"] = data.PrivilegelMoney;
                else
                    dr["PrivilegelMoney"] = DBNull.Value;
                    
                if(data.Privilege != null)
    			    dr["Privilege"] = data.Privilege;
                else
                    dr["Privilege"] = DBNull.Value;
                    
                if(data.PrivilegeGuid != null)
    			    dr["PrivilegeGuid"] = data.PrivilegeGuid;
                else
                    dr["PrivilegeGuid"] = DBNull.Value;
                    
                if(data.WXPayMoney != null)
    			    dr["WXPayMoney"] = data.WXPayMoney;
                else
                    dr["WXPayMoney"] = DBNull.Value;
                    
                if(data.IsVirtual != null)
    			    dr["IsVirtual"] = data.IsVirtual;
                else
                    dr["IsVirtual"] = 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.IntegralTe != null)
    			    dr["IntegralTe"] = data.IntegralTe;
                else
                    dr["IntegralTe"] = DBNull.Value;
                    
                if(data.PresentExp != null)
    			    dr["PresentExp"] = data.PresentExp;
                else
                    dr["PresentExp"] = DBNull.Value;
                    
                if(data.IntegralMoney != null)
    			    dr["IntegralMoney"] = data.IntegralMoney;
                else
                    dr["IntegralMoney"] = DBNull.Value;
                    
                if(data.InPresentExp != null)
    			    dr["InPresentExp"] = data.InPresentExp;
                else
                    dr["InPresentExp"] = DBNull.Value;
                    
                if(data.InProductAmount != null)
    			    dr["InProductAmount"] = data.InProductAmount;
                else
                    dr["InProductAmount"] = DBNull.Value;
                    
                if(data.InProportionIntegral != null)
    			    dr["InProportionIntegral"] = data.InProportionIntegral;
                else
                    dr["InProportionIntegral"] = DBNull.Value;
                    
                if(data.HasPresented != null)
    			    dr["HasPresented"] = data.HasPresented;
                else
                    dr["HasPresented"] = DBNull.Value;
                    
                if(data.PresentedTime != null)
    			    dr["PresentedTime"] = data.PresentedTime;
                else
                    dr["PresentedTime"] = DBNull.Value;
                    
                if(data.HasFactoraged != null)
    			    dr["HasFactoraged"] = data.HasFactoraged;
                else
                    dr["HasFactoraged"] = DBNull.Value;
                    
                if(data.HasProfited != null)
    			    dr["HasProfited"] = data.HasProfited;
                else
                    dr["HasProfited"] = DBNull.Value;
                    
                if(data.ProductClassify != null)
    			    dr["ProductClassify"] = data.ProductClassify;
                else
                    dr["ProductClassify"] = DBNull.Value;
                    
                if(data.FreightFirstCom != null)
    			    dr["FreightFirstCom"] = data.FreightFirstCom;
                else
                    dr["FreightFirstCom"] = DBNull.Value;
                    
                if(data.FreightSecondCom != null)
    			    dr["FreightSecondCom"] = data.FreightSecondCom;
                else
                    dr["FreightSecondCom"] = DBNull.Value;
                    
                if(data.FreightThirdCom != null)
    			    dr["FreightThirdCom"] = data.FreightThirdCom;
                else
                    dr["FreightThirdCom"] = DBNull.Value;
                    
                if(data.HasCountSale != null)
    			    dr["HasCountSale"] = data.HasCountSale;
                else
                    dr["HasCountSale"] = 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_Orders data)
        {
            SqlParameter[] parameters = {
                                            new SqlParameter("@SCreateDate", SqlDbType.DateTime),
                                            new SqlParameter("@SCreateUserName", SqlDbType.NVarChar),
                                            new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@OrderGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@LogisticrGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MemberGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@RecieverAddressGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@DistributionPropGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MerchantPayWayGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@OrderNo", SqlDbType.NVarChar),
											new SqlParameter("@OrderInnerState", SqlDbType.Int),
											new SqlParameter("@OrderState", SqlDbType.Int),
											new SqlParameter("@OrderTime", SqlDbType.DateTime),
											new SqlParameter("@PayTime", SqlDbType.DateTime),
											new SqlParameter("@CompletedTime", SqlDbType.DateTime),
											new SqlParameter("@PayAccount", SqlDbType.NVarChar),
											new SqlParameter("@PayWay", SqlDbType.NVarChar),
											new SqlParameter("@DeliveryTime", SqlDbType.DateTime),
											new SqlParameter("@PayNO", SqlDbType.NVarChar),
											new SqlParameter("@Remark", SqlDbType.NVarChar),
											new SqlParameter("@OrderSource", SqlDbType.NVarChar),
											new SqlParameter("@TotalMoney", SqlDbType.Decimal),
											new SqlParameter("@IsExtendReceiving", SqlDbType.Bit),
											new SqlParameter("@ExtendDay", SqlDbType.Int),
											new SqlParameter("@IsDistribute", SqlDbType.Bit),
											new SqlParameter("@Quantity", SqlDbType.Decimal),
											new SqlParameter("@IsComment", SqlDbType.Bit),
											new SqlParameter("@TransactionID", SqlDbType.NVarChar),
											new SqlParameter("@Package", SqlDbType.NVarChar),
											new SqlParameter("@Freight", SqlDbType.Decimal),
											new SqlParameter("@RecieverAddressInfo", SqlDbType.NVarChar),
											new SqlParameter("@PrivilegelMoney", SqlDbType.Decimal),
											new SqlParameter("@Privilege", SqlDbType.Int),
											new SqlParameter("@PrivilegeGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@WXPayMoney", SqlDbType.Decimal),
											new SqlParameter("@IsVirtual", SqlDbType.Bit),
											new SqlParameter("@NoDelivery", SqlDbType.Bit),
											new SqlParameter("@NoReceive", SqlDbType.Bit),
											new SqlParameter("@IntegralTe", SqlDbType.Int),
											new SqlParameter("@PresentExp", SqlDbType.Int),
											new SqlParameter("@IntegralMoney", SqlDbType.Decimal),
											new SqlParameter("@InPresentExp", SqlDbType.Int),
											new SqlParameter("@InProductAmount", SqlDbType.Decimal),
											new SqlParameter("@InProportionIntegral", SqlDbType.Int),
											new SqlParameter("@HasPresented", SqlDbType.Bit),
											new SqlParameter("@PresentedTime", SqlDbType.DateTime),
											new SqlParameter("@HasFactoraged", SqlDbType.Bit),
											new SqlParameter("@HasProfited", SqlDbType.Bit),
											new SqlParameter("@ProductClassify", SqlDbType.Int),
											new SqlParameter("@FreightFirstCom", SqlDbType.Decimal),
											new SqlParameter("@FreightSecondCom", SqlDbType.Decimal),
											new SqlParameter("@FreightThirdCom", SqlDbType.Decimal),
											new SqlParameter("@HasCountSale", SqlDbType.Bit),
										};
            
            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.OrderGuid;
            parameters[4].Value = data.LogisticrGuid;
            parameters[5].Value = data.MemberGuid;
            parameters[6].Value = data.MerchantGuid;
            parameters[7].Value = data.RecieverAddressGuid;
            parameters[8].Value = data.DistributionPropGuid;
            parameters[9].Value = data.MerchantPayWayGuid;
            parameters[10].Value = data.OrderNo;
            parameters[11].Value = data.OrderInnerState;
            parameters[12].Value = data.OrderState;
            parameters[13].Value = data.OrderTime;
            parameters[14].Value = data.PayTime;
            parameters[15].Value = data.CompletedTime;
            parameters[16].Value = data.PayAccount;
            parameters[17].Value = data.PayWay;
            parameters[18].Value = data.DeliveryTime;
            parameters[19].Value = data.PayNO;
            parameters[20].Value = data.Remark;
            parameters[21].Value = data.OrderSource;
            parameters[22].Value = data.TotalMoney;
            parameters[23].Value = data.IsExtendReceiving;
            parameters[24].Value = data.ExtendDay;
            parameters[25].Value = data.IsDistribute;
            parameters[26].Value = data.Quantity;
            parameters[27].Value = data.IsComment;
            parameters[28].Value = data.TransactionID;
            parameters[29].Value = data.Package;
            parameters[30].Value = data.Freight;
            parameters[31].Value = data.RecieverAddressInfo;
            parameters[32].Value = data.PrivilegelMoney;
            parameters[33].Value = data.Privilege;
            parameters[34].Value = data.PrivilegeGuid;
            parameters[35].Value = data.WXPayMoney;
            parameters[36].Value = data.IsVirtual;
            parameters[37].Value = data.NoDelivery;
            parameters[38].Value = data.NoReceive;
            parameters[39].Value = data.IntegralTe;
            parameters[40].Value = data.PresentExp;
            parameters[41].Value = data.IntegralMoney;
            parameters[42].Value = data.InPresentExp;
            parameters[43].Value = data.InProductAmount;
            parameters[44].Value = data.InProportionIntegral;
            parameters[45].Value = data.HasPresented;
            parameters[46].Value = data.PresentedTime;
            parameters[47].Value = data.HasFactoraged;
            parameters[48].Value = data.HasProfited;
            parameters[49].Value = data.ProductClassify;
            parameters[50].Value = data.FreightFirstCom;
            parameters[51].Value = data.FreightSecondCom;
            parameters[52].Value = data.FreightThirdCom;
            parameters[53].Value = data.HasCountSale;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Orders_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_Orders>  GetTopData(string top, Expression<Func<T_BAS_Orders , bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Orders , 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_Orders> 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_Orders> dataList = new List<T_BAS_Orders>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Orders_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_Orders GetFirstData(Expression<Func<T_BAS_Orders, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Orders, 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_Orders 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_Orders_GetFirstData", CommandType.StoredProcedure, parameters, sqlRTransaction);

            T_BAS_Orders 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_Orders, object[]>> valueExpression, Expression<Func<T_BAS_Orders, 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_Orders_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_Orders 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("@OrderGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@LogisticrGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MemberGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MerchantGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@RecieverAddressGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@DistributionPropGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@MerchantPayWayGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@OrderNo", SqlDbType.NVarChar),
											new SqlParameter("@OrderInnerState", SqlDbType.Int),
											new SqlParameter("@OrderState", SqlDbType.Int),
											new SqlParameter("@OrderTime", SqlDbType.DateTime),
											new SqlParameter("@PayTime", SqlDbType.DateTime),
											new SqlParameter("@CompletedTime", SqlDbType.DateTime),
											new SqlParameter("@PayAccount", SqlDbType.NVarChar),
											new SqlParameter("@PayWay", SqlDbType.NVarChar),
											new SqlParameter("@DeliveryTime", SqlDbType.DateTime),
											new SqlParameter("@PayNO", SqlDbType.NVarChar),
											new SqlParameter("@Remark", SqlDbType.NVarChar),
											new SqlParameter("@OrderSource", SqlDbType.NVarChar),
											new SqlParameter("@TotalMoney", SqlDbType.Decimal),
											new SqlParameter("@IsExtendReceiving", SqlDbType.Bit),
											new SqlParameter("@ExtendDay", SqlDbType.Int),
											new SqlParameter("@IsDistribute", SqlDbType.Bit),
											new SqlParameter("@Quantity", SqlDbType.Decimal),
											new SqlParameter("@IsComment", SqlDbType.Bit),
											new SqlParameter("@TransactionID", SqlDbType.NVarChar),
											new SqlParameter("@Package", SqlDbType.NVarChar),
											new SqlParameter("@Freight", SqlDbType.Decimal),
											new SqlParameter("@RecieverAddressInfo", SqlDbType.NVarChar),
											new SqlParameter("@PrivilegelMoney", SqlDbType.Decimal),
											new SqlParameter("@Privilege", SqlDbType.Int),
											new SqlParameter("@PrivilegeGuid", SqlDbType.UniqueIdentifier),
											new SqlParameter("@WXPayMoney", SqlDbType.Decimal),
											new SqlParameter("@IsVirtual", SqlDbType.Bit),
											new SqlParameter("@NoDelivery", SqlDbType.Bit),
											new SqlParameter("@NoReceive", SqlDbType.Bit),
											new SqlParameter("@IntegralTe", SqlDbType.Int),
											new SqlParameter("@PresentExp", SqlDbType.Int),
											new SqlParameter("@IntegralMoney", SqlDbType.Decimal),
											new SqlParameter("@InPresentExp", SqlDbType.Int),
											new SqlParameter("@InProductAmount", SqlDbType.Decimal),
											new SqlParameter("@InProportionIntegral", SqlDbType.Int),
											new SqlParameter("@HasPresented", SqlDbType.Bit),
											new SqlParameter("@PresentedTime", SqlDbType.DateTime),
											new SqlParameter("@HasFactoraged", SqlDbType.Bit),
											new SqlParameter("@HasProfited", SqlDbType.Bit),
											new SqlParameter("@ProductClassify", SqlDbType.Int),
											new SqlParameter("@FreightFirstCom", SqlDbType.Decimal),
											new SqlParameter("@FreightSecondCom", SqlDbType.Decimal),
											new SqlParameter("@FreightThirdCom", SqlDbType.Decimal),
											new SqlParameter("@HasCountSale", SqlDbType.Bit),
										};										
			
            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.OrderGuid;
			parameters[5].Value = data.LogisticrGuid;
			parameters[6].Value = data.MemberGuid;
			parameters[7].Value = data.MerchantGuid;
			parameters[8].Value = data.RecieverAddressGuid;
			parameters[9].Value = data.DistributionPropGuid;
			parameters[10].Value = data.MerchantPayWayGuid;
			parameters[11].Value = data.OrderNo;
			parameters[12].Value = data.OrderInnerState;
			parameters[13].Value = data.OrderState;
			parameters[14].Value = data.OrderTime;
			parameters[15].Value = data.PayTime;
			parameters[16].Value = data.CompletedTime;
			parameters[17].Value = data.PayAccount;
			parameters[18].Value = data.PayWay;
			parameters[19].Value = data.DeliveryTime;
			parameters[20].Value = data.PayNO;
			parameters[21].Value = data.Remark;
			parameters[22].Value = data.OrderSource;
			parameters[23].Value = data.TotalMoney;
			parameters[24].Value = data.IsExtendReceiving;
			parameters[25].Value = data.ExtendDay;
			parameters[26].Value = data.IsDistribute;
			parameters[27].Value = data.Quantity;
			parameters[28].Value = data.IsComment;
			parameters[29].Value = data.TransactionID;
			parameters[30].Value = data.Package;
			parameters[31].Value = data.Freight;
			parameters[32].Value = data.RecieverAddressInfo;
			parameters[33].Value = data.PrivilegelMoney;
			parameters[34].Value = data.Privilege;
			parameters[35].Value = data.PrivilegeGuid;
			parameters[36].Value = data.WXPayMoney;
			parameters[37].Value = data.IsVirtual;
			parameters[38].Value = data.NoDelivery;
			parameters[39].Value = data.NoReceive;
			parameters[40].Value = data.IntegralTe;
			parameters[41].Value = data.PresentExp;
			parameters[42].Value = data.IntegralMoney;
			parameters[43].Value = data.InPresentExp;
			parameters[44].Value = data.InProductAmount;
			parameters[45].Value = data.InProportionIntegral;
			parameters[46].Value = data.HasPresented;
			parameters[47].Value = data.PresentedTime;
			parameters[48].Value = data.HasFactoraged;
			parameters[49].Value = data.HasProfited;
			parameters[50].Value = data.ProductClassify;
			parameters[51].Value = data.FreightFirstCom;
			parameters[52].Value = data.FreightSecondCom;
			parameters[53].Value = data.FreightThirdCom;
			parameters[54].Value = data.HasCountSale;
			try
            {
                int rowsAffected = SqlHelper.ExecuteNonQuery("PT_BAS_Orders_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_Orders> dataList)
        {
            bool istran = false;
            if (sqlRTransaction.IsTransaction == false)
            {
                istran = true;
                sqlRTransaction.BeginTransaction();
            }

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

            List<T_BAS_Orders> dataListUpdate = new List<T_BAS_Orders>();
            List<string> dataListDelete = new List<string>();            
            StringBuilder sbDelete = new StringBuilder();
            sbDelete.Append(" OrderGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {
                switch (data.EntityState)
                {
                    case EntityStates.ToBeAdd:
                        DataRow dr = dataListAdd.NewRow();
            			dr["OrderGuid"] = data.OrderGuid;
            			dr["LogisticrGuid"] = data.LogisticrGuid;
            			dr["MemberGuid"] = data.MemberGuid;
            			dr["MerchantGuid"] = data.MerchantGuid;
            			dr["RecieverAddressGuid"] = data.RecieverAddressGuid;
            			dr["DistributionPropGuid"] = data.DistributionPropGuid;
            			dr["MerchantPayWayGuid"] = data.MerchantPayWayGuid;
            			dr["OrderNo"] = data.OrderNo;
            			dr["OrderInnerState"] = data.OrderInnerState;
            			dr["OrderState"] = data.OrderState;
            			dr["OrderTime"] = data.OrderTime;
            			dr["PayTime"] = data.PayTime;
            			dr["CompletedTime"] = data.CompletedTime;
            			dr["PayAccount"] = data.PayAccount;
            			dr["PayWay"] = data.PayWay;
            			dr["DeliveryTime"] = data.DeliveryTime;
            			dr["PayNO"] = data.PayNO;
            			dr["Remark"] = data.Remark;
            			dr["OrderSource"] = data.OrderSource;
            			dr["TotalMoney"] = data.TotalMoney;
            			dr["IsExtendReceiving"] = data.IsExtendReceiving;
            			dr["ExtendDay"] = data.ExtendDay;
            			dr["IsDistribute"] = data.IsDistribute;
            			dr["Quantity"] = data.Quantity;
            			dr["IsComment"] = data.IsComment;
            			dr["TransactionID"] = data.TransactionID;
            			dr["Package"] = data.Package;
            			dr["Freight"] = data.Freight;
            			dr["RecieverAddressInfo"] = data.RecieverAddressInfo;
            			dr["PrivilegelMoney"] = data.PrivilegelMoney;
            			dr["Privilege"] = data.Privilege;
            			dr["PrivilegeGuid"] = data.PrivilegeGuid;
            			dr["WXPayMoney"] = data.WXPayMoney;
            			dr["IsVirtual"] = data.IsVirtual;
            			dr["NoDelivery"] = data.NoDelivery;
            			dr["NoReceive"] = data.NoReceive;
            			dr["IntegralTe"] = data.IntegralTe;
            			dr["PresentExp"] = data.PresentExp;
            			dr["IntegralMoney"] = data.IntegralMoney;
            			dr["InPresentExp"] = data.InPresentExp;
            			dr["InProductAmount"] = data.InProductAmount;
            			dr["InProportionIntegral"] = data.InProportionIntegral;
            			dr["HasPresented"] = data.HasPresented;
            			dr["PresentedTime"] = data.PresentedTime;
            			dr["HasFactoraged"] = data.HasFactoraged;
            			dr["HasProfited"] = data.HasProfited;
            			dr["ProductClassify"] = data.ProductClassify;
            			dr["FreightFirstCom"] = data.FreightFirstCom;
            			dr["FreightSecondCom"] = data.FreightSecondCom;
            			dr["FreightThirdCom"] = data.FreightThirdCom;
            			dr["HasCountSale"] = data.HasCountSale;
                        dr["SCreateDate"] = DateTime.Now;
                        dr["SCreateUserName"] = CurrentManage.UserName;
                        dr["SMerchantGuid"] = CurrentManage.SMerchantGuid;
                        dataListAdd.Rows.Add(dr);
                        break;
                    case EntityStates.ToBeDelete:
                        sbDelete.AppendFormat(" '{0}',", data.OrderGuid);
                        deleteCount++;
                        if (deleteCount == 20)
                        {
                            sbDelete.Append(")");
                            deleteCount = 0;
                            strSql = sbDelete.ToString();
                            dataListDelete.Add(strSql.Replace(",)",") "));
                            sbDelete.Clear();
                            sbDelete.Append(" OrderGuid in (");
                        }
                        break;
                    case EntityStates.ToBeUpdated:
                        dataListUpdate.Add(data);
                        break;
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " OrderGuid 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("OrderGuid = '{0}'",dataGuid),isFilterMerchant);
        }
                
         /// <summary>
        /// 根据条件删除记录
        /// </summary>
        /// <param name="dataGuid">删除条件</param>
        /// <returns>返回删除结果，成功为True，失败为False</returns>
        public void Delete(Expression<Func<T_BAS_Orders, 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_Orders> 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(" OrderGuid in (");
            int deleteCount = 0;
            string strSql = string.Empty;
            foreach (var data in dataList)
            {              
                sbDelete.AppendFormat(" '{0}',", data.OrderGuid);
                deleteCount++;
                if (deleteCount == 20)
                {
                    sbDelete.Append(")");
                    deleteCount = 0;
                    strSql = sbDelete.ToString();
                    dataListDelete.Add(strSql.Replace(",)",") "));
                    sbDelete.Clear();
                    sbDelete.Append(" OrderGuid in (");
                }
            }
            if (sbDelete.Length>0 && sbDelete.ToString() != " OrderGuid 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_Orders_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_Orders> GetList(Expression<Func<T_BAS_Orders, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Orders, 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_Orders> 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_Orders> dataList = new List<T_BAS_Orders>();
			           
            SqlDataReader dataReader = SqlHelper.ExecuteReader("PT_BAS_Orders_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_Orders, 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_Orders_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_Orders> GetPageList(int page, int pageSize, out int pageCount, out int recordCount, Expression<Func<T_BAS_Orders, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Orders, 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_Orders> GetPageList(GridModel gridModel, Expression<Func<T_BAS_Orders, bool>> conditionExpression, bool isFilterNull = false, Expression<Func<T_BAS_Orders, 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_Orders> 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_Orders> dataList = new List<T_BAS_Orders>();
            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_Orders_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_Orders LoadModel(SqlDataReader dataReader)
        {
            T_BAS_Orders data = new T_BAS_Orders();
			if (dataReader["OrderGuid"] != DBNull.Value)
				data.OrderGuid = (Guid)dataReader["OrderGuid"];
			if (dataReader["LogisticrGuid"] != DBNull.Value)
				data.LogisticrGuid = (Guid)dataReader["LogisticrGuid"];
			if (dataReader["MemberGuid"] != DBNull.Value)
				data.MemberGuid = (Guid)dataReader["MemberGuid"];
			if (dataReader["MerchantGuid"] != DBNull.Value)
				data.MerchantGuid = (Guid)dataReader["MerchantGuid"];
			if (dataReader["RecieverAddressGuid"] != DBNull.Value)
				data.RecieverAddressGuid = (Guid)dataReader["RecieverAddressGuid"];
			if (dataReader["DistributionPropGuid"] != DBNull.Value)
				data.DistributionPropGuid = (Guid)dataReader["DistributionPropGuid"];
			if (dataReader["MerchantPayWayGuid"] != DBNull.Value)
				data.MerchantPayWayGuid = (Guid)dataReader["MerchantPayWayGuid"];
			if (dataReader["OrderNo"] != DBNull.Value)
				data.OrderNo = (string)dataReader["OrderNo"];
			if (dataReader["OrderInnerState"] != DBNull.Value)
				data.OrderInnerState = (int)dataReader["OrderInnerState"];
			if (dataReader["OrderState"] != DBNull.Value)
				data.OrderState = (int)dataReader["OrderState"];
			if (dataReader["OrderTime"] != DBNull.Value)
				data.OrderTime = (DateTime)dataReader["OrderTime"];
			if (dataReader["PayTime"] != DBNull.Value)
				data.PayTime = (DateTime)dataReader["PayTime"];
			if (dataReader["CompletedTime"] != DBNull.Value)
				data.CompletedTime = (DateTime)dataReader["CompletedTime"];
			if (dataReader["PayAccount"] != DBNull.Value)
				data.PayAccount = (string)dataReader["PayAccount"];
			if (dataReader["PayWay"] != DBNull.Value)
				data.PayWay = (string)dataReader["PayWay"];
			if (dataReader["DeliveryTime"] != DBNull.Value)
				data.DeliveryTime = (DateTime)dataReader["DeliveryTime"];
			if (dataReader["PayNO"] != DBNull.Value)
				data.PayNO = (string)dataReader["PayNO"];
			if (dataReader["Remark"] != DBNull.Value)
				data.Remark = (string)dataReader["Remark"];
			if (dataReader["OrderSource"] != DBNull.Value)
				data.OrderSource = (string)dataReader["OrderSource"];
			if (dataReader["TotalMoney"] != DBNull.Value)
				data.TotalMoney = (decimal)dataReader["TotalMoney"];
			if (dataReader["IsExtendReceiving"] != DBNull.Value)
				data.IsExtendReceiving = (bool)dataReader["IsExtendReceiving"];
			if (dataReader["ExtendDay"] != DBNull.Value)
				data.ExtendDay = (int)dataReader["ExtendDay"];
			if (dataReader["IsDistribute"] != DBNull.Value)
				data.IsDistribute = (bool)dataReader["IsDistribute"];
			if (dataReader["Quantity"] != DBNull.Value)
				data.Quantity = (decimal)dataReader["Quantity"];
			if (dataReader["IsComment"] != DBNull.Value)
				data.IsComment = (bool)dataReader["IsComment"];
			if (dataReader["TransactionID"] != DBNull.Value)
				data.TransactionID = (string)dataReader["TransactionID"];
			if (dataReader["Package"] != DBNull.Value)
				data.Package = (string)dataReader["Package"];
			if (dataReader["SMerchantGuid"] != DBNull.Value)
				data.SMerchantGuid = (Guid)dataReader["SMerchantGuid"];
			if (dataReader["Freight"] != DBNull.Value)
				data.Freight = (decimal)dataReader["Freight"];
			if (dataReader["RecieverAddressInfo"] != DBNull.Value)
				data.RecieverAddressInfo = (string)dataReader["RecieverAddressInfo"];
			if (dataReader["PrivilegelMoney"] != DBNull.Value)
				data.PrivilegelMoney = (decimal)dataReader["PrivilegelMoney"];
			if (dataReader["Privilege"] != DBNull.Value)
				data.Privilege = (int)dataReader["Privilege"];
			if (dataReader["PrivilegeGuid"] != DBNull.Value)
				data.PrivilegeGuid = (Guid)dataReader["PrivilegeGuid"];
			if (dataReader["WXPayMoney"] != DBNull.Value)
				data.WXPayMoney = (decimal)dataReader["WXPayMoney"];
			if (dataReader["IsVirtual"] != DBNull.Value)
				data.IsVirtual = (bool)dataReader["IsVirtual"];
			if (dataReader["NoDelivery"] != DBNull.Value)
				data.NoDelivery = (bool)dataReader["NoDelivery"];
			if (dataReader["NoReceive"] != DBNull.Value)
				data.NoReceive = (bool)dataReader["NoReceive"];
			if (dataReader["IntegralTe"] != DBNull.Value)
				data.IntegralTe = (int)dataReader["IntegralTe"];
			if (dataReader["PresentExp"] != DBNull.Value)
				data.PresentExp = (int)dataReader["PresentExp"];
			if (dataReader["IntegralMoney"] != DBNull.Value)
				data.IntegralMoney = (decimal)dataReader["IntegralMoney"];
			if (dataReader["InPresentExp"] != DBNull.Value)
				data.InPresentExp = (int)dataReader["InPresentExp"];
			if (dataReader["InProductAmount"] != DBNull.Value)
				data.InProductAmount = (decimal)dataReader["InProductAmount"];
			if (dataReader["InProportionIntegral"] != DBNull.Value)
				data.InProportionIntegral = (int)dataReader["InProportionIntegral"];
			if (dataReader["HasPresented"] != DBNull.Value)
				data.HasPresented = (bool)dataReader["HasPresented"];
			if (dataReader["PresentedTime"] != DBNull.Value)
				data.PresentedTime = (DateTime)dataReader["PresentedTime"];
			if (dataReader["HasFactoraged"] != DBNull.Value)
				data.HasFactoraged = (bool)dataReader["HasFactoraged"];
			if (dataReader["HasProfited"] != DBNull.Value)
				data.HasProfited = (bool)dataReader["HasProfited"];
			if (dataReader["ProductClassify"] != DBNull.Value)
				data.ProductClassify = (int)dataReader["ProductClassify"];
			if (dataReader["FreightFirstCom"] != DBNull.Value)
				data.FreightFirstCom = (decimal)dataReader["FreightFirstCom"];
			if (dataReader["FreightSecondCom"] != DBNull.Value)
				data.FreightSecondCom = (decimal)dataReader["FreightSecondCom"];
			if (dataReader["FreightThirdCom"] != DBNull.Value)
				data.FreightThirdCom = (decimal)dataReader["FreightThirdCom"];
			if (dataReader["HasCountSale"] != DBNull.Value)
				data.HasCountSale = (bool)dataReader["HasCountSale"];
            data.EntityState = EntityStates.Original; 
            return data;
        }
        
          #region IDisposable 成员
        /// <summary>
        /// 回收
        /// </summary>
        public void Dispose()
        {
            sqlRTransaction.Dispose();
        }

        #endregion

    }
}

