using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RFramework.SQLServer;
using RFrameGenerate.BLL.DALExtensions;
using System.Linq.Expressions;
using RFrameGenerate.Model;
using RFrameGenerate.Model.PageModel;
using System.Data.SqlClient;
using System.Data;
using RFrameGenerate.Common;

namespace RFrameGenerate.BLL.Marketing
{
    public class ActivityDetailManage
    {
        #region 逻辑处理

        /// <summary>
        /// 获取已使用优惠券数量
        /// </summary>
        public static int GetUseCoupons(Guid activityGuid)
        {
            if (activityGuid == Guid.Empty) return 0;

            using (var query = Factory.CreateT_SA_ActivityDetail())
            {
                return query.GetCount(m => m.State == DictionaryConst.CouponsState.Used && m.StoreActivityGuid == activityGuid);
            }
        }

        /// <summary>
        /// 获取活动交易额
        /// </summary>
        public static decimal? GetOrderVolume(Guid activityGuid)
        {
            if (activityGuid == Guid.Empty) return null;

            Expression<Func<T_ST_ActivityOrders, bool>> condition = m => m.State == DictionaryConst.CouponsState.Used;

            condition = condition.AndAlso(m => m.OrderState == DictionaryConst.OrderState.Completed);
            condition = condition.AndAlso(m => m.StoreActivityGuid == activityGuid);
            condition = condition.AndAlso(m => m.MerchantGuid == CurrentManage.MerchantGuid);

            return CommonDAL<Model.T_ST_ActivityOrders>.Sum(m => m.TotalMoney, condition);
        }

        /// <summary>
        /// 获取优惠券详情列表
        /// </summary>
        public static List<T_ST_CouponStatistics> GetCouponPageList(GridModel gridModel, Guid activityGuid)
        {
            if (gridModel.recordCount <= 0)
            {
                gridModel.recordCount = GetCouponCount(activityGuid);
            }

            int start = (gridModel.page - 1) * gridModel.rows;
            int end = gridModel.page * gridModel.rows;

            StringBuilder sql = new StringBuilder();
            sql.Append("select * from (");
            sql.Append("select a.*,ROW_NUMBER() OVER (ORDER BY MemberName) AS RowNumber from (");
            sql.Append("select MemberName,MemberGuid,count(*) MemberCount,count(case when State=2 then 1 else null end) UsedCount,count(case when ExpiryDate < getdate() then 1 else null end) ExpiryCount,Sum(case when OrderState = 5 then TotalMoney else null end) OrderAmount from [dbo].[T_ST_ActivityOrders]");
            sql.Append("where SMerchantGuid = @SMerchantGuid and StoreActivityGuid = @StoreActivityGuid group by  MemberName,MemberGuid) a ) c where RowNumber > @Start AND RowNumber <= @End");

            SqlParameter[] parameters = {
                new SqlParameter("@StoreActivityGuid", SqlDbType.UniqueIdentifier),
                new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier),
                new SqlParameter("@Start", SqlDbType.Int),
                new SqlParameter("@End", SqlDbType.Int),
            };
            parameters[0].Value = activityGuid;
            parameters[1].Value = CurrentManage.SMerchantGuid;
            parameters[2].Value = start;
            parameters[3].Value = end;

            List<T_ST_CouponStatistics> list = new List<T_ST_CouponStatistics>();
            SqlRTransaction sqlRTransaction = null;
            SqlDataReader dataReader = null;
            try
            {
                sqlRTransaction = new SqlRTransaction();

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

                while (dataReader.Read())
                {
                    var model = new T_ST_CouponStatistics();

                    if (dataReader["MemberName"] != DBNull.Value)
                        model.MemberName = (string)dataReader["MemberName"];
                    if (dataReader["MemberGuid"] != DBNull.Value)
                        model.MemberGuid = (Guid)dataReader["MemberGuid"];
                    if (dataReader["MemberCount"] != DBNull.Value)
                        model.MemberCount = (int)dataReader["MemberCount"];
                    if (dataReader["UsedCount"] != DBNull.Value)
                        model.UsedCount = (int)dataReader["UsedCount"];
                    if (dataReader["ExpiryCount"] != DBNull.Value)
                        model.ExpiryCount = (int)dataReader["ExpiryCount"];
                    if (dataReader["OrderAmount"] != DBNull.Value)
                        model.OrderAmount = (decimal?)dataReader["OrderAmount"];

                    list.Add(model);
                }
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " ActivityDetailManage.GetCouponPageList！ Message :" + ex.Message);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " ActivityDetailManage.GetCouponPageList！ Source :" + ex.Source);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " ActivityDetailManage.GetCouponPageList！ StackTrace :" + ex.StackTrace);
            }
            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();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取优惠券详情总数
        /// </summary>
        public static int GetCouponCount(Guid activityGuid)
        {
            string sql = "select count(*) AllMemberCount from ( select MemberGuid from [T_ST_ActivityOrders] where StoreActivityGuid = @StoreActivityGuid and SMerchantGuid = @SMerchantGuid group by MemberGuid ) a";
            SqlParameter[] parameters = {
                new SqlParameter("@StoreActivityGuid", SqlDbType.UniqueIdentifier),
                new SqlParameter("@SMerchantGuid", SqlDbType.UniqueIdentifier)
            };
            parameters[0].Value = activityGuid;
            parameters[1].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 0;

                var result = dataReader[0];

                if (result == null || result == DBNull.Value || !(result is int)) return 0;

                return Convert.ToInt32(result);

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

                return 0;
            }
            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();
                    }
                }
            }
        }

        /// <summary>
        /// 获取订单编号
        /// </summary>
        public static string GetOrderNos(Guid MemberGuid, Guid activityGuid)
        {
            if (MemberGuid == Guid.Empty) return string.Empty;

            if (activityGuid == Guid.Empty) return string.Empty;

            var list = new List<T_ST_ActivityOrders>();
            using (var query = Factory.CreateT_ST_ActivityOrders())
            {
                list = query.GetList(m => m.OrderState == DictionaryConst.OrderState.Completed && m.State == DictionaryConst.CouponsState.Used &&
                                         m.StoreActivityGuid == activityGuid && m.MemberGuid == MemberGuid);
            }
            if (list == null || list.Count <= 0) return string.Empty;

            StringBuilder str = new StringBuilder();
            foreach (var item in list)
            {
                str.AppendFormat("{0},", item.OrderNo);
            }
            return str.ToString();
        }
        #endregion

        #region 获取优惠券列表

        /// <summary>
        /// 获取我的优惠券
        /// </summary>
        public static List<T_ST_MemberCoupons> GetMyCoupons(Guid memberGuid, int? state)
        {
            using (var query = Factory.CreateT_ST_MemberCoupons())
            {
                if (state == null || state == 1)
                    return query.GetList(m => m.ActivityState == DictionaryConst.ActivityState.Normal && m.State == DictionaryConst.CouponsState.NotUsed && m.StartDate < DateTime.Now && m.ExpiryDate > DateTime.Now && m.MerchantGuid == CurrentManage.MerchantGuid && m.MemberGuid == memberGuid);
                else
                    return query.GetList(m => m.MerchantGuid == CurrentManage.MerchantGuid && m.MemberGuid == memberGuid);
            }
        }

        /// <summary>
        /// 获取我的可用优惠券数量
        /// </summary>
        public static int GetAvailableCoupons(Guid memberGuid)
        {
            using (var query = Factory.CreateT_ST_MemberCoupons())
            {
                return query.GetCount(m => m.ActivityState == DictionaryConst.ActivityState.Normal && m.State == DictionaryConst.CouponsState.NotUsed && m.StartDate < DateTime.Now && m.ExpiryDate > DateTime.Now && m.MemberGuid == memberGuid);
            }
        }

        /// <summary>
        /// 获取下订单可用优惠券
        /// </summary>
        public static List<T_ST_MemberCoupons> GetAvailableCoupons(decimal amount, Guid memberGuid)
        {
            Expression<Func<T_ST_MemberCoupons, bool>> condition = m => m.State == DictionaryConst.CouponsState.NotUsed && m.ActivityState == DictionaryConst.ActivityState.Normal;

            condition = condition.AndAlso(m => m.StartDate < DateTime.Now && m.ExpiryDate > DateTime.Now);
            condition = condition.AndAlso(m => (m.ServiceConditions == 1 && amount > m.Amount) || (m.ServiceConditions == 2 && amount >= m.ServiceConditionsMoney));
            condition = condition.AndAlso(m => m.MerchantGuid == CurrentManage.MerchantGuid && m.MemberGuid == memberGuid);

            using (var query = Factory.CreateT_ST_MemberCoupons())
            {
                return query.GetList(condition);
            }
        }

        /// <summary>
        /// 获取优惠券
        /// </summary>
        public static T_ST_MemberCoupons GetMemberCoupon(Guid couponDetailGuid)
        {
            var memberGuid = CurrentUser.GetCurrUserGuid();
            using (var query = Factory.CreateT_ST_MemberCoupons())
            {
                return query.GetFirstData(m => m.MemberGuid == memberGuid && m.ActivityDetailGuid == couponDetailGuid);
            }
        }

        /// <summary>
        /// 检查优惠券状态
        /// </summary>
        public static Result CheckCoupon(T_ST_MemberCoupons coupons)
        {
            if (coupons == null) return new Result(false, "不存在优惠券");

            if (coupons.StartDate > DateTime.Now) return new Result(false, "优惠券开始时间未到，不能使用！");

            if (coupons.ExpiryDate < DateTime.Now) return new Result(false, "优惠券已过期，不能使用！");

            if (coupons.State == DictionaryConst.CouponsState.Used) return new Result(false, "此优惠券已经使用，不能再使用！");

            if (coupons.State == DictionaryConst.CouponsState.Invalid) return new Result(false, "此优惠券已失效，不能使用！");

            if (coupons.ActivityState == DictionaryConst.ActivityState.Closed) return new Result(false, "此活动已关闭，不能使用！");

            return new Result(true);
        }

        #endregion
    }
}
