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.Model.Query;
using Mall.Repository;
using Mall.Repository.MarketingCenter;
using Mall.Repository.User;
using MySqlX.XDevAPI.Relational;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Crypto.Tls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Mall.Module.MarketingCenter
{
    public class CouponModule
    {
        private RB_CouponRepository couponRepository = new RB_CouponRepository();
        private RB_DiscountCouponRepository discountCouponRepository = new RB_DiscountCouponRepository();
        private RB_DiscountCoupon_ProductRepository productRepository = new RB_DiscountCoupon_ProductRepository();


        private Repository.User.RB_Member_CouponRepository memberCouponRepository = new Repository.User.RB_Member_CouponRepository();
        private RB_Coupon_SelfMotionMemberRepository selfMotionMemberRepository = new RB_Coupon_SelfMotionMemberRepository();

        private RB_Coupon_SelfMotionRepository selfMotionRepository = new RB_Coupon_SelfMotionRepository();

        /// <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_Coupon_Extend> GetCouponPageList(int pageIndex, int pageSize, out long rowCount, RB_Coupon_Extend query)
        {
            return couponRepository.GetCouponPageList(pageIndex, pageSize, out rowCount, query);
        }

        /// <summary>
        /// 卡券信息列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Coupon_Extend> GetCouponList(RB_Coupon_Extend query)
        {
            return couponRepository.GetCouponList(query);

        }

        public bool AddOrUpdateCoupon(RB_Coupon_Extend model)
        {
            if (model.ID == 0)
            {
                return couponRepository.Insert(model) > 0;
            }
            else
            {
                return couponRepository.Update(model);
            }
        }


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

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



        #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_DiscountCoupon_Extend> GetDiscountCouponPageList(int pageIndex, int pageSize, out long rowCount, RB_DiscountCoupon_Extend query)
        {
            return discountCouponRepository.GetDiscountCouponPageList(pageIndex, pageSize, out rowCount, query);
        }

        /// <summary>
        /// 优惠券信息列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_DiscountCoupon_Extend> GetDiscountCouponList(RB_DiscountCoupon_Extend query)
        {
            var list = discountCouponRepository.GetDiscountCouponList(query);
            if (list != null && list.Any())
            {

                string Ids = string.Join(",", list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category || x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ID));
                var listProduct = productRepository.GetListByDiscountCouponIds(query, Ids);
                foreach (var item in list)
                {
                    item.ProductList = new List<RB_DiscountCoupon_Product_Extend>();
                    item.ProductList = listProduct.Where(x => x.DiscountCouponId == item.ID).ToList();
                }
            }
            return list;

        }

        /// <summary>
        /// 优惠券信息列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_DiscountCoupon_Extend> GetAllDiscountCouponList(RB_DiscountCoupon_Extend query)
        {
            return discountCouponRepository.GetDiscountCouponList(query);

        }



        /// <summary>
        /// 新增/修改优惠券
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateDiscountCoupon(RB_DiscountCoupon_Extend model)
        {
            bool flag = false;
            var trans = discountCouponRepository.DbTransaction;
            try
            {
                int id = 0;
                if (model.ID == 0)
                {
                    id = discountCouponRepository.Insert(model, trans);
                    if (id > 0 && model.ProductList != null && model.ProductList.Any())
                    {
                        model.ProductList.ForEach(x => x.DiscountCouponType = model.UseType);
                        model.ProductList.ForEach(x => x.MallBaseId = model.MallBaseId);
                        model.ProductList.ForEach(x => x.TenantId = model.TenantId);
                        model.ProductList.ForEach(x => x.CreateDate = model.CreateDate);
                        model.ProductList.ForEach(x => x.UpdateDate = model.UpdateDate);
                        model.ProductList.ForEach(x => x.DiscountCouponId = id);
                        flag = productRepository.InsertBatch(model.ProductList, trans);
                    }
                    flag = id > 0;
                }
                else
                {
                    id = model.ID;
                    flag = discountCouponRepository.Update(model, trans);


                    IDictionary<string, object> fileds = new Dictionary<string, object>()
                         {
                            { nameof(RB_DiscountCoupon_Product.Status),1},
                             { nameof(RB_DiscountCoupon_Product.UpdateDate),model.UpdateDate},
                          };
                    IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_DiscountCoupon_Product.DiscountCouponId),FiledValue=id,OperatorEnum=OperatorEnum.Equal}
                        };
                    productRepository.Update(fileds, whereHelpers, trans);
                    ////var listProduct = productRepository.GetCouponProductList(new RB_DiscountCoupon_Product { TenantId = model.TenantId, MallBaseId = model.MallBaseId, DiscountCouponId = id });
                    ////if (listProduct != null && listProduct.Any())
                    ////{
                    ////    foreach (var item in listProduct)
                    ////    {
                    ////        IDictionary<string, object> fileds = new Dictionary<string, object>()
                    ////     {
                    ////        { nameof(RB_DiscountCoupon_Product.Status),1},
                    ////         { nameof(RB_DiscountCoupon_Product.UpdateDate),model.UpdateDate},
                    ////      };
                    ////        IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                    ////    {
                    ////        new WhereHelper (){ FiledName=nameof(RB_DiscountCoupon_Product.ID),FiledValue=item.ID,OperatorEnum=OperatorEnum.Equal}
                    ////    };
                    ////        flag = productRepository.Update(fileds, whereHelpers, trans);
                    ////    }
                    ////}

                    if (model.ProductList != null && model.ProductList.Any())
                    {
                        model.ProductList.ForEach(x => x.DiscountCouponType = model.UseType);
                        model.ProductList.ForEach(x => x.MallBaseId = model.MallBaseId);
                        model.ProductList.ForEach(x => x.TenantId = model.TenantId);
                        model.ProductList.ForEach(x => x.CreateDate = model.CreateDate);
                        model.ProductList.ForEach(x => x.UpdateDate = model.UpdateDate);
                        model.ProductList.ForEach(x => x.DiscountCouponId = id);
                        flag = productRepository.InsertBatch(model.ProductList, trans);
                    }
                }
                discountCouponRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateDiscountCoupon");
                discountCouponRepository.DBSession.Rollback("AddOrUpdateDiscountCoupon");
                return false;
            }
            return flag;
        }

        /// <summary>
        /// 删除优惠券
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelDiscountCoupon(int id, int uid, int mallBaseId)
        {
            bool flag = false;
            var trans = discountCouponRepository.DbTransaction;
            try
            {
                Dictionary<string, object> cols1 = new Dictionary<string, object>()
                    {
                        { nameof(RB_DiscountCoupon.Status),1},
                        { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                    };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon.ID),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
                };
                flag = discountCouponRepository.Update(cols1, wheres1);

                Dictionary<string, object> cols = new Dictionary<string, object>()
                    {
                        { nameof(RB_DiscountCoupon.Status),1},
                        { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                    };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon_Product.DiscountCouponId),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon_Product.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon_Product.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
                };
                productRepository.Update(cols, wheres);


                discountCouponRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelDiscountCoupon");
                discountCouponRepository.DBSession.Rollback("DelDiscountCoupon");
                return false;
            }
            return flag;
        }





        /// <summary>
        /// 删除优惠券
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelMemberCoupon(int id, int uid, int mallBaseId)
        {
            bool flag = false;

            try
            {
                Dictionary<string, object> cols1 = new Dictionary<string, object>()
                    {
                        { nameof(RB_Member_DiscountCoupon.Status),1},
                        { nameof(RB_Member_DiscountCoupon.Remarks),System.DateTime.Now+"删除"},
                    };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Member_DiscountCoupon.Id),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Member_DiscountCoupon.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Member_DiscountCoupon.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
                };
                flag = memberCouponRepository.Update(cols1, wheres1);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelMemberCoupon");
                return false;
            }
            return flag;
        }



        /// <summary>
        /// 领劵中心
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool UpdatePickupType(int id, int uid, int mallBaseId)
        {
            try
            {
                var model = discountCouponRepository.GetEntity(id);

                Dictionary<string, object> cols1 = new Dictionary<string, object>()
                    {
                        { nameof(RB_DiscountCoupon.PickupCenter),model.PickupCenter==0?1:0},
                        { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                    };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon.ID),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_DiscountCoupon.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
                };
                return discountCouponRepository.Update(cols1, wheres1);


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



        /// <summary>
        /// 发放优惠券
        /// </summary>
        /// <param name="list"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool GrantCoupon(List<RB_Member_DiscountCoupon_Extend> list, RB_DiscountCoupon_Extend model)
        {
            bool flag = false;
            var trans = memberCouponRepository.DbTransaction;
            try
            {

                //foreach (var item in list)
                //{
                flag = memberCouponRepository.InsertBatch(list, trans);

                // }
                if (model != null && flag)
                {
                    Dictionary<string, object> cols1;

                    if (model.TotalNum != -1)
                    {
                        cols1 = new Dictionary<string, object>()
                        {
                            { nameof(RB_DiscountCoupon.ReceiveNum),model.ReceiveNum+list.Count()},
                            { nameof(RB_DiscountCoupon.TotalNum),model.TotalNum - list.Count()},
                            { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                        };
                    }
                    else
                    {
                        cols1 = new Dictionary<string, object>()
                        {
                            { nameof(RB_DiscountCoupon.ReceiveNum),model.ReceiveNum+list.Count()},

                            { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                        };
                    }
                    List<WhereHelper> wheres1 = new List<WhereHelper>()
                    {
                    new WhereHelper(){
                            FiledName=nameof(RB_DiscountCoupon.ID),
                            FiledValue=model.ID,
                            OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                            FiledName=nameof(RB_DiscountCoupon.TenantId),
                            FiledValue=model.TenantId,
                            OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                            FiledName=nameof(RB_DiscountCoupon.MallBaseId),
                            FiledValue=model.MallBaseId,
                            OperatorEnum=OperatorEnum.Equal
                    }
                    };
                    flag = discountCouponRepository.Update(cols1, wheres1, trans);
                }
                memberCouponRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "GrantCoupon");
                memberCouponRepository.DBSession.Rollback("GrantCoupon");
                return false;
            }
            return flag;
        }


        /// <summary>
        /// 根据用户id和商品分类以及商品id获取未使用的优惠券信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_DiscountCoupon_Extend> GetNoUseCouponList(RB_DiscountCoupon_Extend query)
        {
            var list = discountCouponRepository.GetNoUseCouponList(query);
            //获取特定商品或者分类的数据
            string Ids = string.Join(",", list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ID));
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                query.UseType = Common.Enum.MarketingCenter.UseTypeEnum.Category;
                var listProduct = productRepository.GetListByDiscountCouponIds(query, Ids);
                foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category))
                {
                    item.ProductList = new List<RB_DiscountCoupon_Product_Extend>();
                    item.ProductList = listProduct.Where(x => x.DiscountCouponId == item.ID).ToList();
                }
            }
            Ids = string.Join(",", list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ID));
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                query.UseType = Common.Enum.MarketingCenter.UseTypeEnum.Product;
                var listProduct = productRepository.GetListByDiscountCouponIds(query, Ids);
                foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product))
                {
                    item.ProductList = new List<RB_DiscountCoupon_Product_Extend>();
                    item.ProductList = listProduct.Where(x => x.DiscountCouponId == item.ID).ToList();
                }
            }

            return list;
        }


        #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_Coupon_SelfMotion_Extend> GetSelfMotionPageLis(int pageIndex, int pageSize, out long rowCount, RB_Coupon_SelfMotion_Extend query)
        {
            return selfMotionRepository.GetSelfMotionPageLis(pageIndex, pageSize, out rowCount, query);
        }

        /// <summary>
        /// 自动发放优惠券规则列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Coupon_SelfMotion_Extend> GettRepositoryList(RB_Coupon_SelfMotion_Extend query)
        {
            var list = selfMotionRepository.GettRepositoryList(query);

            return list;
        }



        /// <summary>
        /// 获取发放优惠券的人员信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Coupon_SelfMotionMember_Extend> GetSelfMotionMemberList(RB_Coupon_SelfMotionMember_Extend query)
        {
            return selfMotionMemberRepository.GetListRepository(query);
        }


        /// <summary>
        /// 新增/修改自动发放优惠券
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateSelfMotion(RB_Coupon_SelfMotion_Extend model)
        {
            bool flag = false;
            var trans = selfMotionRepository.DbTransaction;
            try
            {
                int id = 0;
                if (model.ID == 0)
                {
                    id = selfMotionRepository.Insert(model, trans);
                    if (id > 0 && model.UserList != null && model.UserList.Any())
                    {
                        model.UserList.ForEach(x => x.MallBaseId = model.MallBaseId);
                        model.UserList.ForEach(x => x.TenantId = model.TenantId);
                        model.UserList.ForEach(x => x.CreateDate = model.CreateDate);
                        model.UserList.ForEach(x => x.UpdateDate = model.UpdateDate);
                        model.UserList.ForEach(x => x.SelfMotionId = id);
                        flag = selfMotionMemberRepository.InsertBatch(model.UserList, trans);
                    }
                    flag = id > 0;
                }
                else
                {
                    id = model.ID;
                    flag = selfMotionRepository.Update(model, trans);
                    // var listProduct = selfMotionMemberRepository.GetListRepository(new RB_Coupon_SelfMotionMember_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, SelfMotionId = id });
                    //if (listProduct != null && listProduct.Any())
                    //{
                    //    foreach (var item in model.UserList)
                    //    {
                    //        IDictionary<string, object> fileds = new Dictionary<string, object>()
                    //     {
                    //        { nameof(RB_Coupon_SelfMotionMember.Status),1},
                    //         { nameof(RB_Coupon_SelfMotionMember.UpdateDate),model.UpdateDate},
                    //      };
                    //        IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                    //    {
                    //        new WhereHelper (){ FiledName=nameof(RB_Coupon_SelfMotionMember.ID),FiledValue=item.ID,OperatorEnum=OperatorEnum.Equal}
                    //    };
                    //        flag = selfMotionMemberRepository.Update(fileds, whereHelpers, trans);
                    //    }
                    //}
                    IDictionary<string, object> fileds = new Dictionary<string, object>()
                         {
                            { nameof(RB_Coupon_SelfMotionMember.Status),1},
                             { nameof(RB_Coupon_SelfMotionMember.UpdateDate),model.UpdateDate},
                          };
                    IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_Coupon_SelfMotionMember.SelfMotionId),FiledValue=model.ID,OperatorEnum=OperatorEnum.Equal},
                             new WhereHelper (){ FiledName=nameof(RB_Coupon_SelfMotionMember.MallBaseId),FiledValue=model.MallBaseId,OperatorEnum=OperatorEnum.Equal},
                              new WhereHelper (){ FiledName=nameof(RB_Coupon_SelfMotionMember.TenantId),FiledValue=model.TenantId,OperatorEnum=OperatorEnum.Equal}
                        };
                    selfMotionMemberRepository.Update(fileds, whereHelpers, trans);


                    if (model.UserList != null && model.UserList.Any())
                    {
                        model.UserList.ForEach(x => x.MallBaseId = model.MallBaseId);
                        model.UserList.ForEach(x => x.TenantId = model.TenantId);
                        model.UserList.ForEach(x => x.CreateDate = model.CreateDate);
                        model.UserList.ForEach(x => x.UpdateDate = model.UpdateDate);
                        model.UserList.ForEach(x => x.SelfMotionId = id);
                        flag = selfMotionMemberRepository.InsertBatch(model.UserList, trans);
                    }
                }
                selfMotionRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateSelfMotion");
                selfMotionRepository.DBSession.Rollback("AddOrUpdateSelfMotion");
                return false;
            }
            return flag;
        }

        /// <summary>
        /// 删除自动发放优惠券
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelDiscountSelfMotion(int id, int uid, int mallBaseId)
        {
            bool flag = false;
            var trans = selfMotionRepository.DbTransaction;
            try
            {
                Dictionary<string, object> cols1 = new Dictionary<string, object>()
                    {
                        { nameof(RB_Coupon_SelfMotion.Status),1},
                        { nameof(RB_Coupon_SelfMotion.UpdateDate),DateTime.Now},
                    };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Coupon_SelfMotion.ID),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Coupon_SelfMotion.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Coupon_SelfMotion.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
                };
                flag = selfMotionRepository.Update(cols1, wheres1);

                Dictionary<string, object> cols = new Dictionary<string, object>()
                    {
                        { nameof(RB_Coupon_SelfMotionMember.Status),1},
                        { nameof(RB_Coupon_SelfMotionMember.UpdateDate),DateTime.Now},
                    };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Coupon_SelfMotionMember.SelfMotionId),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Coupon_SelfMotionMember.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Coupon_SelfMotionMember.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
                };
                selfMotionMemberRepository.Update(cols, wheres);


                selfMotionRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelDiscountSelfMotion");
                selfMotionRepository.DBSession.Rollback("DelDiscountSelfMotion");
                return false;
            }
            return flag;
        }


        #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_DiscountCoupon_Extend> GetUseCouponList(int pageIndex, int pageSize, out long rowCount, RB_Member_DiscountCoupon_Extend query)
        {
            return memberCouponRepository.GetUseCouponList(pageIndex, pageSize, out rowCount, query);
        }
        #endregion


        #region 优惠券发放统计


        /// <summary>
        /// 数据统计-积分收支
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<MemberCoupon_Query> GetCouponStatisticslList(int pageIndex, int pageSize, out long rowCount, MemberCoupon_Query query)
        {
            return memberCouponRepository.GetCouponStatisticslList(pageIndex, pageSize, out rowCount, query);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_DiscountCoupon_Extend> GetTotalIntegral(RB_Member_DiscountCoupon_Extend dmodel)
        {
            return memberCouponRepository.GetExportIntegraStatisticslList(dmodel);

        }

        /// <summary>
        /// 数据统计-积分收支
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<MemberCoupon_Query> GetExportCouponStatisticslList(MemberCoupon_Query query)
        {
            return memberCouponRepository.GetExportCouponStatisticslList(query);
        }
        #endregion


        #region 小程序个人中心-领劵中心

        /// <summary>
        /// 领劵中心优惠券
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_DiscountCoupon_Extend> GetAllCouponList(int pageIndex, int pageSize, out long rowCount, RB_DiscountCoupon_Extend query)
        {
            var list = discountCouponRepository.GetAllCouponList(pageIndex, pageSize, out rowCount, query);

            //获取特定商品或者分类的数据
            string Ids = string.Join(",", list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ID));
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                query.UseType = Common.Enum.MarketingCenter.UseTypeEnum.Category;
                var listProduct = productRepository.GetListByDiscountCouponIds(query, Ids);
                foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category))
                {
                    item.ProductList = new List<RB_DiscountCoupon_Product_Extend>();
                    item.ProductList = listProduct.Where(x => x.DiscountCouponId == item.ID).ToList();
                }
            }
            Ids = string.Join(",", list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ID));
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                query.UseType = Common.Enum.MarketingCenter.UseTypeEnum.Product;
                var listProduct = productRepository.GetListByDiscountCouponIds(query, Ids);
                foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product))
                {
                    item.ProductList = new List<RB_DiscountCoupon_Product_Extend>();
                    item.ProductList = listProduct.Where(x => x.DiscountCouponId == item.ID).ToList();
                }
            }
            return list;
        }
        #endregion


        #region 会员优惠券
        /// <summary>
        /// 会员优惠券
        /// </summary>
        /// <returns></returns>
        public List<RB_Member_DiscountCoupon_Extend> GetMemberDiscountCouponList(RB_Member_DiscountCoupon_Extend query)
        {
            return memberCouponRepository.GetList(query);
        }




        /// <summary>
        /// 我的优惠券
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_DiscountCoupon_Extend> GetMemberDisCouponList(int pageIndex, int pageSize, out long rowCount, RB_DiscountCoupon_Extend query)
        {
            var list = discountCouponRepository.GetMemberDisCouponList(pageIndex, pageSize, out rowCount, query);
            //获取特定商品或者分类的数据
            string Ids = string.Join(",", list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ID));
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                query.UseType = Common.Enum.MarketingCenter.UseTypeEnum.Category;
                var listProduct = productRepository.GetListByDiscountCouponIds(query, Ids);
                foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category))
                {
                    item.ProductList = new List<RB_DiscountCoupon_Product_Extend>();
                    item.ProductList = listProduct.Where(x => x.DiscountCouponId == item.ID).ToList();
                }
            }
            Ids = string.Join(",", list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ID));
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                query.UseType = Common.Enum.MarketingCenter.UseTypeEnum.Product;
                var listProduct = productRepository.GetListByDiscountCouponIds(query, Ids);
                foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product))
                {
                    item.ProductList = new List<RB_DiscountCoupon_Product_Extend>();
                    item.ProductList = listProduct.Where(x => x.DiscountCouponId == item.ID).ToList();
                }
            }
            return list;
        }
        #endregion

        #region 自动发放给会员优惠券
        /// <summary>
        /// 自动给会员发放优惠券
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="getType">1-分享，2-购买并付款，3-新人领券</param>
        /// <returns></returns>
        public bool AutoCoupon(RB_DiscountCoupon_Extend model)
        {

            //先查找会员是否存在
            var memberUserModel = member_UserRepository.GetEntity(model.UserId);
            if (memberUserModel == null)
            {
                return false;
            }
            //根据发放类型获取对应的优惠券信息
            var couponList = discountCouponRepository.GetSelfmotionCouponList(model);
            if (couponList != null && couponList.Any(x => x.TotalNum == -1 || ((x.TotalNum - x.ReceiveNum) > 0)))//存在满足条件的优惠券可以发放
            {
                bool isReceive = false;
                //查询已发放的优惠券信息
                var memberCouponList = memberCouponRepository.GetAutoMemberCouponPageList(new RB_Member_DiscountCoupon_Extend { UserId = model.UserId, GetType = model.TriggerType, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                foreach (var item in couponList.Where(x => x.TotalNum == -1 || ((x.TotalNum - x.ReceiveNum) > 0)))//判断当前优惠券是否已超过领取数
                {
                    int membercouponCoun = memberCouponList.Where(x => x.CouponId == item.ID).Count();
                    if (!isReceive && membercouponCoun < item.GrantNum)//此次没有领取，并且当前优惠券没有超过领取数量
                    {
                        var trans = memberCouponRepository.DbTransaction;
                        try
                        {
                            RB_Member_DiscountCoupon nowMemberCoupon = new RB_Member_DiscountCoupon
                            {
                                Id = 0,
                                TenantId = item.TenantId,
                                MallBaseId = item.MallBaseId,
                                Status = 0,
                                CreateDate = System.DateTime.Now,
                                UserId = item.UserId,
                                Description = item.TriggerType == 1 ? "分享自动发放优惠券" : (item.TriggerType == 2 ? "购买并付款自动发放优惠券" : "新人领劵自动发放优惠券"),
                                Remarks = item.TriggerType == 1 ? "分享" : (item.TriggerType == 2 ? "购买并付款" : "新人领劵"),
                                UseState = 0,
                                CouponId = item.ID,
                                StartDate = item.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon ? System.DateTime.Now : item.StartDate,
                                EndDate = item.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon ? System.DateTime.Now.AddDays(item.IndateDay) : item.EndDate,
                                GetType = item.TriggerType,
                                UseType = item.UseType,
                                MinConsumePrice = item.MinConsumePrice,
                                DiscountsPrice = item.DiscountsPrice,
                                MaxDiscountsPrice = item.MaxDiscountsPrice,
                                CouponType = item.CouponType,
                                Name = item.Name
                            };

                            isReceive = memberCouponRepository.Insert(nowMemberCoupon, trans) > 0;
                            if (isReceive)//更新当前优惠券的领取数量
                            {
                                Dictionary<string, object> cols1;

                                if (item.TotalNum != -1)
                                {
                                    cols1 = new Dictionary<string, object>()
                                    {
                                        { nameof(RB_DiscountCoupon.ReceiveNum),item.ReceiveNum+1},
                                        { nameof(RB_DiscountCoupon.TotalNum),item.TotalNum - 1},
                                        { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                                    };
                                }
                                else
                                {
                                    cols1 = new Dictionary<string, object>()
                                    {
                                        { nameof(RB_DiscountCoupon.ReceiveNum),item.ReceiveNum+1},
                                        { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                                    };
                                }
                                List<WhereHelper> wheres1 = new List<WhereHelper>()
                                {
                                    new WhereHelper(){
                                            FiledName=nameof(RB_DiscountCoupon.ID),
                                            FiledValue=item.ID,
                                            OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                            FiledName=nameof(RB_DiscountCoupon.TenantId),
                                            FiledValue=item.TenantId,
                                            OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                            FiledName=nameof(RB_DiscountCoupon.MallBaseId),
                                            FiledValue=item.MallBaseId,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                discountCouponRepository.Update(cols1, wheres1, trans);
                            }
                            memberCouponRepository.DBSession.Commit();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "AutoCoupon");
                            memberCouponRepository.DBSession.Rollback("AutoCoupon");
                            return false;
                        }
                    }
                }
            }
            return false;
        }
        #endregion

    }
}
