using RFrameGenerate.Common;
using RFramework.SQLQuery;
using RFramework.SQLServer;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace RFrameGenerate.BLL.DALExtensions
{
    /// <summary>
    /// 扩展现有不支持的方法
    /// </summary>
    public class CommonDAL<T>
    {
        #region Sum 

        public static decimal? Sum(Expression<Func<T, decimal?>> selector, Expression<Func<T, bool>> conditionExpression, bool isFilterNull = false, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);

            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();

            var field = ((MemberExpression)selector.Body).Member.Name;

            if (string.IsNullOrEmpty(field)) return null;

            return Sum(conditionString, field, isFilterMerchant);
        }

        public static decimal? Sum(Expression<Func<T, int?>> selector, Expression<Func<T, bool>> conditionExpression, bool isFilterNull = false, bool isFilterMerchant = true)
        {
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(conditionExpression);

            if (isFilterNull == true)
                conditionString = conditionString.SqlFilterNull();

            var field = ((MemberExpression)selector.Body).Member.Name;

            if (string.IsNullOrEmpty(field)) return null;

            return Sum(conditionString, field, isFilterMerchant);
        }

        public static decimal? Sum(Expression<Func<RFrameGenerate.Model.T_BAS_Orders, decimal?>> selector, Expression<Func<RFrameGenerate.Model.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();

            var field = ((MemberExpression)selector.Body).Member.Name;

            if (string.IsNullOrEmpty(field)) return null;

            return Sum(conditionString, field, isFilterMerchant);
        }

        private static decimal? Sum(string conditionString, string field, bool isFilterMerchant = true)
        {
            string sql = string.Format("select sum({0}) from {1}", field, GetTableName());

            if (!string.IsNullOrEmpty(conditionString))
            {
                sql += string.Format(" where {0}", conditionString);
            }

            if (!string.IsNullOrEmpty(conditionString) && isFilterMerchant)
            {
                sql += " and SMerchantGuid = @SMerchantGuid";
            }
            else if (string.IsNullOrEmpty(conditionString) && isFilterMerchant)
            {
                sql += " where SMerchantGuid = @SMerchantGuid";
            }

            SqlParameter[] parameters = {
                new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier)
            };
            parameters[0].Value = CurrentManage.SMerchantGuid;

            SqlRTransaction sqlRTransaction = null;
            SqlDataReader dataReader = null;
            try
            {
                sqlRTransaction = new SqlRTransaction();

                dataReader = SqlHelper.ExecuteReader(sql, CommandType.Text, parameters, sqlRTransaction);

                if (!dataReader.Read()) return null;

                var result = dataReader[0];

                if (result == null || result == DBNull.Value) return null;

                return result as decimal?;

            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " Table " + GetTableName() + " CommonDAL.Sum！ Message :" + ex.Message);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " Table " + GetTableName() + " CommonDAL.Sum！ Source :" + ex.Source);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " Table " + GetTableName() + " CommonDAL.Sum！ StackTrace :" + ex.StackTrace);

                return null;
            }
            finally
            {
                if (dataReader != null) dataReader.Close();

                if (sqlRTransaction != null)
                {
                    sqlRTransaction.Dispose();

                    if (sqlRTransaction.SqlConnection != null && sqlRTransaction.SqlConnection.State != System.Data.ConnectionState.Closed)
                    {
                        sqlRTransaction.SqlConnection.Close();
                    }
                }
            }
        }

        #endregion

        private static string GetTableName()
        {
            return typeof(T).Name;
        }
    }
}
