using RFrameGenerate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Wechat.Model;
using RFramework.SQLQuery;
using weixinopen;
using Wechat;
using RFramework.SQLServer;
using RFramework.SQLQuery.SQLExpands;
using RFrameGenerate.Common;
using RFrameGenerate.Model.PageModel;

namespace RFrameGenerate.BLL
{
    public class IntegralRulesManage
    {


        #region 新增商家自定义积分规则
        /// <summary>
        /// 新增商家自定义积分规则
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Result AddIntegralRules(T_INT_IntegralRules entity)
        {
            using (var query = Factory.CreateT_INT_IntegralRules())
            {
                try
                {
                    entity.IntegralRulesGuid = Guid.NewGuid();
                    query.Add(entity);
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    return new Result(false, ex.Message);
                }
            }
        }
        #endregion


        #region 删除指定商家的积分规则
        /// <summary>
        /// 删除指定商家的积分规则
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Result DeleteIntegralRules(Guid guid)
        {
            using (var query = Factory.CreateT_INT_IntegralRules())
            {
                try
                {
                    query.Delete(c => c.MerchantGuid == guid);
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    return new Result(false, ex.Message);
                }
            }
        }
        #endregion


        #region 更新商家自定义积分规则
        /// <summary>
        /// 更新商家自定义积分规则
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Result UpdateIntegralRules(T_INT_IntegralRules entity)
        {
            using (var query = Factory.CreateT_INT_IntegralRules())
            {
                try
                {
                    query.Update(c => new object[]
                    { 
                     c.MerchantGuid==entity.MerchantGuid,
                     c.IntegralEnable==entity.IntegralEnable,
                     c.ProductAmount==entity.ProductAmount,
                     c.PresentExp==entity.PresentExp,
                     c.ProportionIntegral==entity.ProportionIntegral,
                     c.MaxUseIntegralType==entity.MaxUseIntegralType,
                     c.MaxUseIntegral==entity.MaxUseIntegral,
                    }, c => c.MerchantGuid == entity.MerchantGuid);
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    return new Result(false, ex.Message);
                }
            }
        }
        #endregion


        #region 新增覆盖商家自定义积分规则-关联事务(临时使用)
        /// <summary>
        /// 新增覆盖商家自定义积分规则-关联事务(临时使用)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static void AddorUpdateIntegralRulesTemp(T_INT_IntegralRules entity, SqlRTransaction tran)
        {
            var query = Factory.CreateT_INT_IntegralRules(tran);
            if (query.GetFirstData(c => c.MerchantGuid == entity.MerchantGuid) != null)
            {
                query.Delete(c => c.MerchantGuid == entity.MerchantGuid);
            }
            entity.IntegralRulesGuid = Guid.NewGuid();
            query.Add(entity);

        }
        #endregion


        #region 删除指定商家的积分规则-关联事务(临时使用)
        /// <summary>
        /// 删除指定商家的积分规则-关联事务(临时使用)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static void DeleteIntegralRulesTemp(Guid guid, SqlRTransaction tran)
        {
            var query = Factory.CreateT_INT_IntegralRules(tran);
            query.Delete(c => c.MerchantGuid == guid);

        }
        #endregion


        #region 获取指定商家的自定义积分规则
        /// <summary>
        /// 获取指定商家的自定义积分规则
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static T_INT_IntegralRules GetIntegralRuleByMerchant(Guid? merchantGuid, SqlRTransaction tran = null)
        {
            if (tran == null)
            {
                using (var query = Factory.CreateT_INT_IntegralRules())
                {
                    return query.GetFirstData(c => c.MerchantGuid == merchantGuid, isFilterMerchant: false);
                }
            }
            else
            {
                var query = Factory.CreateT_INT_IntegralRules(tran);
                return query.GetFirstData(c => c.MerchantGuid == merchantGuid, isFilterMerchant: false);

            }

        }
        #endregion


        #region 获取指定会员的积分
        /// <summary>
        /// 获取指定会员的积分
        /// </summary>
        /// <param name="memberGuid"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public static int GetMemberIntegral(Guid memberGuid, SqlRTransaction tran = null)
        {
            if (tran == null)
            {
                using (var query = Factory.CreateT_BAS_Member())
                {
                    return query.GetFirstData(c => c.MemberGuid == memberGuid).Integral ?? 0;
                }
            }
            else
            {
                var query = Factory.CreateT_BAS_Member(tran);
                return query.GetFirstData(c => c.MemberGuid == memberGuid).Integral ?? 0;
            }
        }
        #endregion


        #region 根据金额获取赠送消费积分-总单(勿随意修改 Bing)
        /// <summary>
        /// 根据金额获取赠送消费积分-总单(勿随意修改 Bing)
        /// </summary>
        /// <param name="money"></param>
        /// <param name="IntegralEntity"></param>
        /// <param name="Integral"></param>
        public static void GetIntegral(decimal? money, T_INT_IntegralRules IntegralEntity, out int integral)
        {
            integral = 0;
            if (IntegralEntity != null && IntegralEntity.IntegralEnable == true)
            {
                if (money >= IntegralEntity.ProductAmount)
                {
                    var countTemp = Math.Floor(money.Value / IntegralEntity.ProductAmount.Value);
                    for (int i = 0; i < countTemp; i++)
                    {
                        integral += IntegralEntity.PresentExp.Value;
                    }
                }
            }
        }
        #endregion


        #region 根据金额获取赠送消费积分-备用子单(勿随意修改 Bing)
        /// <summary>
        /// 根据金额获取赠送消费积分-备用子单(勿随意修改 Bing)
        /// </summary>
        /// <param name="money"></param>
        /// <param name="IntegralEntity"></param>
        /// <param name="Integral"></param>
        public static void GetIntegralChild(decimal? money, T_INT_IntegralRules IntegralEntity, out int integral)
        {
            integral = 0;
            if (IntegralEntity != null && IntegralEntity.IntegralEnable == true)
            {
                if (money >= IntegralEntity.ProductAmount)
                {
                    var countTemp = Math.Ceiling(money.Value / IntegralEntity.ProductAmount.Value);
                    for (int i = 0; i < countTemp; i++)
                    {
                        integral += IntegralEntity.PresentExp.Value;
                    }
                }
            }
        }
        #endregion


        #region 获取转换 金额_积分 支持合法数据（勿随意修改 Bing）
        /// <summary>
        /// 获取转换 金额_积分 支持合法数据（勿随意修改 Bing）
        /// </summary>
        /// <param name="tempPrice"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public static void GetIntegralTranSupportData(decimal tempPrice, T_INT_IntegralRules IntegralEntity, out decimal supportMoney, out int supportIntegral)
        {

            supportMoney = 0M;
            supportIntegral = 0;

            //计算合法的支持抵扣金额上限（Has Not Fix M_I Ratio）
            if (IntegralEntity.MaxUseIntegralType == ParameterName.IntegralRulesName.MaxUseIntegralType.MaxUseIntegralTypeA)
            {
                if (IntegralEntity.ProportionIntegral == 100)
                {
                    supportMoney = (tempPrice * IntegralEntity.MaxUseIntegral.Value / 100);
                    supportMoney = supportMoney.ToString().LastIndexOf(".") != -1 && (supportMoney.ToString().Length - supportMoney.ToString().LastIndexOf(".") > 3) ? Convert.ToDecimal(supportMoney.ToString().Substring(0, supportMoney.ToString().LastIndexOf(".") + 3)) : supportMoney;

                }
                else
                {
                    supportMoney = Math.Floor(tempPrice * IntegralEntity.MaxUseIntegral.Value / 100);
                }
            }
            else
            {
                if (IntegralEntity.ProportionIntegral == 100)
                {
                    supportMoney = tempPrice > IntegralEntity.MaxUseIntegral.Value ? IntegralEntity.MaxUseIntegral.Value : (tempPrice.ToString().LastIndexOf(".") != -1 && (tempPrice.ToString().Length - tempPrice.ToString().LastIndexOf(".") > 3) ? Convert.ToDecimal(tempPrice.ToString().Substring(0, tempPrice.ToString().LastIndexOf(".") + 3)) : tempPrice);//确保不超出当前总价
                }
                else
                {
                    supportMoney = tempPrice > IntegralEntity.MaxUseIntegral.Value ? Math.Floor(IntegralEntity.MaxUseIntegral.Value) : Math.Floor(tempPrice);//确保不超出当前总价
                }

            }

            //转换对应抵扣积分上限
            supportIntegral = (int)(supportMoney * IntegralEntity.ProportionIntegral.Value);
        }

        #endregion


        #region 获取转换 金额_积分 使用数据（勿随意修改 Bing）
        /// <summary>
        /// 获取转换 金额_积分 使用数据（勿随意修改 Bing）
        /// </summary>
        /// <param name="tempPrice"></param>
        /// <param name="tempIntegral"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public static IntegralTranData GetIntegraltranData(decimal tempPrice, int tempIntegral, T_INT_IntegralRules IntegralEntity)
        {

            if (tempPrice <= 0)
            {
                return new IntegralTranData(IntegralTranSate.Error, 0, 0, "金额错误"); //T
            }
            if (tempIntegral <= 0)
            {
                return new IntegralTranData(IntegralTranSate.Error, 0, 0, "积分不足"); //U
            }

            #region Supported M_I 转换

            //当前商家积分规则（Depend）暂 
            if (IntegralEntity == null || IntegralEntity.IntegralEnable == false)
            {
                return new IntegralTranData(IntegralTranSate.Error, 0, 0, "当前商家未启用积分活动");
            }

            var supportMoney = 0M;
            var supportIntegral = 0;

            IntegralRulesManage.GetIntegralTranSupportData(tempPrice, IntegralEntity, out supportMoney, out supportIntegral);

            #endregion

            #region TempTe M_I 转换

            var integralTe = 0;
            var moneyTe = 0M;

            //暂定
            if (tempIntegral > supportIntegral)
            {
                integralTe = supportIntegral;
                moneyTe = supportMoney;
            }
            else
            {
                if (IntegralEntity.ProportionIntegral == 100)
                {
                    moneyTe = (decimal)tempIntegral / IntegralEntity.ProportionIntegral.Value;
                    moneyTe = moneyTe.ToString().LastIndexOf(".") != -1 && (moneyTe.ToString().Length - moneyTe.ToString().LastIndexOf(".")) > 3 ? Convert.ToDecimal(moneyTe.ToString().Substring(0, moneyTe.ToString().LastIndexOf(".") + 3)) : moneyTe;
                }
                else
                {
                    moneyTe = Math.Floor((decimal)tempIntegral / IntegralEntity.ProportionIntegral.Value);
                }
                integralTe = (int)(moneyTe * IntegralEntity.ProportionIntegral.Value);
            }

            //暂不处理转换空数据
            return new IntegralTranData(IntegralTranSate.SuccessDefault, integralTe, moneyTe);

            #endregion

        }
        #endregion


        #region  根据传入金额，旧赠送积分，验证赠送积分
        /// <summary>
        /// 根据传入金额，旧赠送积分，验证赠送积分 
        /// </summary>
        /// <param name="money"></param>
        /// <param name="PresentExp"></param>
        /// <param name="integralEntity"></param>
        /// <returns></returns>
        public static Result ValidateIntegral(decimal? money, int? PresentExp, T_INT_IntegralRules integralEntity)
        {
            //必要二次验证 
            if (integralEntity == null || integralEntity.IntegralEnable == false)
            {
                return new Result(false, "当前积分活动被关闭，请重新下单");
            }

            int tempPresentExp;
            IntegralRulesManage.GetIntegral(money, integralEntity, out tempPresentExp);
            if (PresentExp != tempPresentExp)
            {
                return new Result(false, "积分数据赠送已更新，请重新下单");
            }

            return new Result(true);
        }
        #endregion


        #region 根据传入金额，积分，旧积分_金额数据，验证积分_金额数据
        /// <summary>
        /// 根据传入金额，积分，旧积分_金额数据，验证积分_金额数据
        /// </summary>
        /// <param name="tempPrice"></param>
        /// <param name="tempIntegral"></param>
        /// <param name="IntegralTe"></param>
        /// <param name="integralMoney"></param>
        /// <param name="integralEntity"></param>
        /// <returns></returns>
        public static Result ValidateIntegraltranData(decimal tempPrice, int tempIntegral, int IntegralTe, decimal integralMoney, T_INT_IntegralRules integralEntity)
        {
            //必要二次验证 
            if (integralEntity == null || integralEntity.IntegralEnable == false)
            {
                return new Result(false, "当前积分活动被关闭，请重新下单");
            }

            //获取积分转换数据二次验证 
            IntegralTranData integralData = IntegralRulesManage.GetIntegraltranData(tempPrice, tempIntegral, integralEntity);
            if (integralData.State == IntegralTranSate.Error)
            {
                return new Result(false, integralData.Remark);
            }
            if (IntegralTe != integralData.IntegralTe || integralMoney != integralData.MoneyTe)
            {
                return new Result(false, "积分数据使用已更新，请重新下单");
            }

            return new Result(true);
        }
        #endregion




    }




}
