using Mall.Common.Plugin;
using Mall.Model.Entity.MarketingCenter;
using Mall.Model.Entity.User;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Extend.User;
using Mall.Repository;
using Mall.Repository.MarketingCenter;
using Mall.Repository.User;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Text;

namespace Mall.Module.MarketingCenter
{
    public class RechargeModule
    {
        private RB_Recharge_RulesRepository rulesRepository = new RB_Recharge_RulesRepository();


        private RB_Member_BalanceRepository balanceRepository = new RB_Member_BalanceRepository();
        private RB_Member_IntegralRepository integralRepository = new RB_Member_IntegralRepository();
        private RB_Recharge_SettingsRepository settingsRepository = new RB_Recharge_SettingsRepository();

        private RB_Recharge_CustomRepository customRepository = new RB_Recharge_CustomRepository();
        private RB_Member_BalanceRechargeRepository balanceRechargeRepository = new RB_Member_BalanceRechargeRepository();
        /// <summary>
        /// 会员信息
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();

        #region 充值规则信息
        /// <summary>
        /// 充值信息列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Recharge_Rules_Extend> GetRechargeRulesPageList(int pageIndex, int pageSize, out long rowCount, RB_Recharge_Rules_Extend query)
        {
            return rulesRepository.GetRechargeRulesPageList(pageIndex, pageSize, out rowCount, query);
        }


        /// <summary>
        /// 充值信息列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Recharge_Rules_Extend> GetRechargeRulesList(RB_Recharge_Rules_Extend query)
        {
            return rulesRepository.GetRechargeRulesList(query);
        }


        public bool AddOrUpdateRechargeRules(RB_Recharge_Rules_Extend model)
        {
            if (model.ID == 0)
            {
                return rulesRepository.Insert(model) > 0;
            }
            else
            {
                return rulesRepository.Update(model);
            }
        }


        /// <summary>
        /// 删除充值方案
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelRechargeRules(int id, int uid, int mallBaseId)
        {
            try
            {
                Dictionary<string, object> cols = new Dictionary<string, object>()
                {
                    { nameof(RB_Recharge_Rules.Status),1},
                    { nameof(RB_Recharge_Rules.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Recharge_Rules.ID),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Recharge_Rules.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Recharge_Rules.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
            };
                return rulesRepository.Update(cols, wheres1);

            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelRechargeRules");
                return false;
            }
        }

        #endregion


        #region 充值设置


        /// <summary>
        /// 充值设置列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Recharge_Settings> GetRechargeSettingsList(RB_Recharge_Settings query)
        {
            return settingsRepository.GetRechargeSettingsList(query);
        }

        public bool AddOrUpdateRechargeSettings(RB_Recharge_Settings model)
        {
            if (model.ID == 0)
            {
                return settingsRepository.Insert(model) > 0;
            }
            else
            {
                return settingsRepository.Update(model);
            }
        }
        #endregion

        #region 余额收支
        /// <summary>
        /// 营销中心-余额收支
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_Balance_Extend> GetMemberBalancePageList(int pageIndex, int pageSize, out long rowCount, RB_Member_Balance_Extend query)
        {
            return balanceRepository.GetMemberBalancePageList(pageIndex, pageSize, out rowCount, query);
        }




        /// <summary>
        /// 导出余额收支
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Member_Balance_Extend> GetMemberBalanceExport(RB_Member_Balance_Extend query)
        {
            return balanceRepository.GetMemberBalanceExport(query);
        }

        #endregion


        #region 自定义充值
        /// <summary>
        /// 自定义充值信息列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Recharge_Custom> GetRechargeCustomList(RB_Recharge_Custom query)
        {
            return customRepository.GetRechargeCustomList(query);
        }

        /// <summary>
        /// 新增/修改自定义充值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateRechargeCustom(RB_Recharge_Custom model)
        {
            if (model.ID == 0)
            {
                return customRepository.Insert(model) > 0;
            }
            else
            {

                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Recharge_Custom.BalanceName), model.BalanceName},
                    {nameof(RB_Recharge_Custom.RechareName), model.RechareName},
                    {nameof(RB_Recharge_Custom.RechareExplain), model.RechareExplain},
                    {nameof(RB_Recharge_Custom.BtnFillet), model.BtnFillet},
                    {nameof(RB_Recharge_Custom.BtnName), model.BtnName},
                    {nameof(RB_Recharge_Custom.BackgroundColor), model.BackgroundColor},
                    {nameof(RB_Recharge_Custom.TextColor), model.TextColor},
                    {nameof(RB_Recharge_Custom.UpdateDate), model.UpdateDate},
                };
                List<WhereHelper> whereHelpers = new List<WhereHelper>()
                {
                    new WhereHelper(){ FiledName=nameof(RB_Recharge_Custom.ID),FiledValue=model.ID ,OperatorEnum=OperatorEnum.Equal}
                };
                return customRepository.Update(fileds, whereHelpers);
            }
        }
        #endregion


        #region 充值
        /// <summary>
        /// 卡券信息列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_BalanceRecharge> GetBalanceRechargePageList(int pageIndex, int pageSize, out long rowCount, RB_Member_BalanceRecharge query)
        {
            return balanceRechargeRepository.GetBalanceRechargePageList(pageIndex, pageSize, out rowCount, query);
        }


        /// <summary>
        /// 充值信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_BalanceRecharge> GetBalanceRechargeList(RB_Member_BalanceRecharge query)
        {
            return balanceRechargeRepository.GetBalanceRechargeList(query);
        }

        /// <summary>
        /// 新增充值金额
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddBalanceRecharge(RB_Member_BalanceRecharge model)
        {
            if (model.Id == 0)
            {
                int Id = balanceRechargeRepository.Insert(model);
                return Id;
            }
            return 0;
        }


        /// <summary>
        /// 新增充值金额
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateBalanceRecharge(int UserId, int OrderId, string Out_Trade_No, string Transaction_Id, Common.Enum.Goods.OrderPayTypeEnum PayWay, string PayType, decimal Money, DateTime Time_End)
        {
            bool flag = false;
            var umodel = member_UserRepository.GetEntity(UserId);
            if (umodel == null)
            {
                return false;
            }
            //判断订单状态是否是待支付  2020-06-16 Add By:W
            var model = balanceRechargeRepository.GetEntity(OrderId);
            if (model == null)
            {
                return false;
            }
            if (model.State != 0)
            {
                return false;
            }
            if (model.Balance!= Money)
            {
                return false;
            }

            var trans = balanceRechargeRepository.DbTransaction;
            try
            {

                //更新订单信息
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Member_BalanceRecharge.State),1},
                    { nameof(RB_Member_BalanceRecharge.Out_Trade_No),Out_Trade_No},
                    { nameof(RB_Member_BalanceRecharge.RechargeTime),Time_End},
                    { nameof(RB_Member_BalanceRecharge.Transaction_Id),Transaction_Id}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Member_BalanceRecharge.Id),
                          FiledValue=model.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = balanceRechargeRepository.Update(keyValues, wheres, trans);//更新充值记录
                                                                                  //新增余额
                RB_Member_Balance memberBalanceModel = new RB_Member_Balance();
                memberBalanceModel.UserId = model.UserId;
                memberBalanceModel.Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income;
                memberBalanceModel.Balance = model.Balance + Convert.ToDecimal(model.GiveMoney);
                memberBalanceModel.Description = "在线充值" + model.Balance + "元余额" + (model.GiveMoney > 0 ? ("赠送" + Convert.ToDecimal(model.GiveMoney)) : "");
                memberBalanceModel.CreateDate = model.RechargeTime;
                memberBalanceModel.TenantId = model.TenantId;
                memberBalanceModel.MallBaseId = model.MallBaseId;
                memberBalanceModel.Remarks = "订单号：" + model.OrderNo + "在线充值" + model.Balance + "元余额" + (model.GiveMoney > 0 ? ("赠送" + Convert.ToDecimal(model.GiveMoney)) : "");
                memberBalanceModel.PlatformType = model.OrderSource;
                balanceRepository.Insert(memberBalanceModel, trans);

                //判断是否赠送积分
                if (model.GiveIntegral > 0)//有赠送的积分
                {
                    RB_Member_Integral memberIntegralModel = new RB_Member_Integral();
                    memberIntegralModel.UserId = model.UserId;
                    memberIntegralModel.Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income;
                    memberIntegralModel.PlatformType = model.OrderSource;
                    memberIntegralModel.Integral = model.GiveIntegral;
                    memberIntegralModel.Description = "在线充值" + model.Balance + "元余额" + (model.GiveMoney > 0 ? ("赠送" + model.GiveIntegral + "积分") : "");
                    memberIntegralModel.TenantId = model.TenantId;
                    memberIntegralModel.MallBaseId = model.MallBaseId;
                    memberIntegralModel.Remarks = "订单号：" + model.OrderNo + "在线充值" + model.Balance + "元余额" + (model.GiveMoney > 0 ? ("赠送" + model.GiveIntegral + "积分") : "");
                    memberIntegralModel.CreateDate = model.RechargeTime;
                    memberIntegralModel.OrderId = 0;
                    integralRepository.Insert(memberIntegralModel, trans);
                }
                balanceRechargeRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "UpdateBalanceRecharge");
                balanceRechargeRepository.DBSession.Rollback("UpdateBalanceRecharge");
                return false;
            }
            return flag;
        }




        #endregion
    }
}
