using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Enum;
using Mall.Common.Enum.Goods;
using Mall.Common.Enum.User;
using Mall.Common.Plugin;
using Mall.Model.Entity.Finance;
using Mall.Model.Entity.Product;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.Education;
using Mall.Model.Extend.Finance;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Education;
using Mall.Repository.Finance;
using Mall.Repository.GuideCar;
using Mall.Repository.MarketingCenter;
using Mall.Repository.Product;
using Mall.Repository.User;
using Mall.ThirdCore.Message;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 订单处理层 v2
    /// </summary>
    public partial class OrderModule
    {
        /// <summary>
        /// 用户课程卡
        /// </summary>
        private RB_Education_MemberCouponRepository education_MemberCouponRepository = new RB_Education_MemberCouponRepository();
        /// <summary>
        /// 课程卡实体
        /// </summary>
        private RB_Education_CouponRepository education_CouponRepository = new RB_Education_CouponRepository();
        /// <summary>
        /// 课程卡适配
        /// </summary>
        private RB_Education_CouponProductRepository education_CouponProductRepository = new RB_Education_CouponProductRepository();
        /// <summary>
        /// 课程卡使用
        /// </summary>
        private RB_Education_MemberUseCouponRepository education_MemberUseCouponRepository = new RB_Education_MemberUseCouponRepository();



        /// <summary>
        /// 获取小程序结算页面详情
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult GetAppletCourseSettlementInfo(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            if (demodel.SmallShopsId == 0)
            {
                demodel.SmallShopsId = umodel.SmallShopId;
            }
            //积分
            Model.Entity.MarketingCenter.RB_Integral_Settings integralModel = new Model.Entity.MarketingCenter.RB_Integral_Settings();
            if (umodel.Integral > 0)
            {
                integralModel = integral_SettingsRepository.GetIntegralSettingsList(new Model.Entity.MarketingCenter.RB_Integral_Settings() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            }

            List<object> DList = new List<object>();
            decimal TotalGoodsMoney = 0, TotalGoodsOriginalMoney = 0, TotalGoodsSellMoney = 0;//  总商品价格  总原价  总售价
            
            decimal member_discount = 0;//总会员优惠
            decimal Total_integral_price = 0;//总积分金额
            int Total_use_integral = 0;//总积分
            decimal CouponsMoney = 0;//优惠总金额
            decimal EducationMoney = 0;//课程卡抵扣金额
            int EducationNum = 0;//课程卡抵扣数量
            bool IsPointsDeduction = false;//是否有商品可使用积分抵扣
            
            List<object> goods_list = new List<object>();
            if (demodel.DetailList.Any())
            {
                string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetSingleList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var mpriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                
                //返佣
                var DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
                if (demodel.DetailList.Where(x => x.SeparateDistribution == 1).Any())
                {
                    string goodsIds = string.Join(",", demodel.DetailList.Where(x => x.SeparateDistribution == 1).Select(x => x.GoodsId));
                    DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                #region 优惠卷初始化
                List<RB_Member_DiscountCoupon_Extend> cList = new List<RB_Member_DiscountCoupon_Extend>();
                List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend> dcList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend>();
                List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend> dcpList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend>();
                if (demodel.User_Coupon_Id > 0)
                {
                    demodel.CouponsIds = demodel.User_Coupon_Id.ToString();
                    if (!string.IsNullOrEmpty(demodel.CouponsIds))
                    {
                        cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 0, Ids = demodel.CouponsIds, UserId = umodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        if (cList.Any())
                        {
                            string cIds = string.Join(",", cList.Select(x => x.CouponId).Distinct());
                            dcList = discountCouponRepository.GetDiscountCouponList(new Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend() { CouponIds = cIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                            dcpList = discountCoupon_ProductRepository.GetListByDiscountCouponIds(new Model.Entity.MarketingCenter.RB_DiscountCoupon() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, cIds, true);
                            if (dcList.Any())
                            {
                                foreach (var item in cList)
                                {
                                    if (item.CouponId > 0)
                                    {
                                        if (!dcList.Where(x => x.ID == item.CouponId).Any())
                                        {
                                            return ApiResult.Failed("优惠券不存在，请核实后再试");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion

                #region 课程卡初始化
                List<RB_Education_MemberCoupon_Extend> eList = new List<RB_Education_MemberCoupon_Extend>();
                List<RB_Education_Coupon_Extend> deList = new List<RB_Education_Coupon_Extend>();
                List<RB_Education_CouponProduct_Extend> edcpList = new List<RB_Education_CouponProduct_Extend>();
                if (demodel.Use_Education_Id > 0)
                {
                    if (demodel.User_Coupon_Id > 0) {
                        return ApiResult.Failed("课程卡与优惠券不能同时使用");
                    }
                    if (demodel.Use_Integral > 0) {
                        return ApiResult.Failed("课程卡与积分抵扣不能同时使用");
                    }
                    eList = education_MemberCouponRepository.GetList(new RB_Education_MemberCoupon_Extend() { Ids = (demodel.Use_Education_Id ?? 0).ToString(), UserId = umodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (eList.Any())
                    {
                        var educationModel = eList.FirstOrDefault();
                        if (educationModel.HeXiao <= educationModel.UseHeXiao) {
                            return ApiResult.Failed("课程卡剩余次数不足");
                        }
                        string cIds = string.Join(",", eList.Select(x => x.CouponId).Distinct());
                        deList = education_CouponRepository.GetDiscountCouponList(new RB_Education_Coupon_Extend() { CouponIds = cIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                        edcpList = education_CouponProductRepository.GetListByDiscountCouponIds(new Model.Entity.Education.RB_Education_Coupon() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, cIds, true);
                        if (deList.Any())
                        {
                            foreach (var item in eList)
                            {
                                if (item.CouponId > 0)
                                {
                                    if (!deList.Where(x => x.ID == item.CouponId).Any())
                                    {
                                        return ApiResult.Failed("课程卡不存在，请核实后再试");
                                    }
                                }
                            }
                        }
                    }   
                }
                #endregion
                List<RB_Goods_CouponModel> GoodsCouponList = new List<RB_Goods_CouponModel>();//商品优惠卷 价格（每个商品优惠的价格）

                #region 微店价格
                RB_SmallShops_Info_Extend smallModel = new RB_SmallShops_Info_Extend();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (demodel.SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(demodel.SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = demodel.SmallShopsId, GoodsIds = GoodsIds });
                }
                #endregion
                //初始化值
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    if (gmodel.GoodsClassify != 2)
                    {
                        return ApiResult.Failed("有非教育类商品");
                    }
                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();

                    #region 图片
                    gmodel.CoverImage = "";
                    //轮播
                    gmodel.CarouselImageList = new List<RB_ImageCommonModel>();
                    if (!string.IsNullOrEmpty(gmodel.CarouselImage) && gmodel.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(gmodel.CarouselImage);
                        //轮播图
                        foreach (var qitem in CarouselIdList)
                        {
                            gmodel.CarouselImageList.Add(new RB_ImageCommonModel()
                            {
                                Id = 0,
                                Name = "",
                                Path = qitem
                            });
                        }
                        //封面图
                        gmodel.CoverImage = CarouselIdList[0];

                    }
                    #endregion

                    #region 会员价格
                    gmodel.MemberPrice = gmodel.SellingPrice ?? 0;
                    List<object> discounts = new List<object>();
                    if (umodel.MemberGrade > 0)
                    {
                        if (gmodel.EnjoyMember == 1 && gmodel.SeparateSetMember == 1)
                        {
                            gmodel.MemberPrice = mpriceList.Where(x => x.GoodsId == item.GoodsId && x.MemberGrade == umodel.MemberGrade && x.SpecificationSort == item.SpecificationSort).FirstOrDefault()?.MemberPrice ?? 0;
                            if (demodel.SmallShopsId > 0)
                            {
                                if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.GoodsId && x.UpPrice > 0).Any())
                                {
                                    var sspModel = smallPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            gmodel.MemberPrice += Math.Ceiling((gmodel.MemberPrice) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            gmodel.MemberPrice += (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                gmodel.MemberPrice += Math.Ceiling((gmodel.MemberPrice) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                gmodel.MemberPrice += (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //求会员等级折扣
                            var gradeModel = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { Grade = umodel.MemberGrade, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                            gmodel.MemberPrice = Math.Round((gmodel.SellingPrice ?? 0) * (gradeModel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                        }

                        discounts.Add(new
                        {
                            name = "会员优惠价格",
                            value = (gmodel.MemberPrice * (item.Number ?? 0)) - ((gmodel.SellingPrice ?? 0) * (item.Number ?? 0))
                        });
                        member_discount += (gmodel.MemberPrice * (item.Number ?? 0)) - ((gmodel.SellingPrice ?? 0) * (item.Number ?? 0));
                    }
                    #endregion

                    item.Final_Price = gmodel.MemberPrice * (item.Number ?? 0);

                    #region  积分
                    if (umodel.Integral > 0 && gmodel.PointsDeduction > 0 && integralModel.IntegralNum > 0)
                    {
                        IsPointsDeduction = true;
                        decimal SingleMaxMoney = 0, MultMaxMoney = 0;
                        if (gmodel.PointsDeductionType == 1)
                        {
                            SingleMaxMoney = Math.Round(gmodel.MemberPrice * (gmodel.PointsDeduction ?? 0) / 100, 2, MidpointRounding.AwayFromZero);
                            MultMaxMoney = Math.Round(gmodel.MemberPrice * (item.Number ?? 0) * (gmodel.PointsDeduction ?? 0) / 100, 2, MidpointRounding.AwayFromZero);
                        }
                        if (gmodel.IsMultipleDeduction == 1)
                        {
                            //可以多件商品可累计抵扣
                            if (gmodel.PointsDeductionType == 1)
                            {
                                int MaxInterral = Convert.ToInt32(MultMaxMoney * integralModel.IntegralNum);
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                            else
                            {
                                int MaxInterral = Convert.ToInt32((gmodel.PointsDeduction ?? 0) * integralModel.IntegralNum * (item.Number ?? 0));
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                        }
                        else
                        {
                            //单件商品
                            if (gmodel.PointsDeductionType == 1)
                            {
                                int MaxInterral = Convert.ToInt32(SingleMaxMoney * integralModel.IntegralNum);
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                            else
                            {
                                int MaxInterral = Convert.ToInt32((gmodel.PointsDeduction ?? 0) * integralModel.IntegralNum);
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                        }
                    }

                    decimal integral_price = 0;
                    int use_integral = 0;
                    if (demodel.Use_Integral == 1)
                    {
                        integral_price = item.IntegralMoney ?? 0;
                        use_integral = item.IntegralNumber ?? 0;

                        item.Final_Price -= integral_price;
                    }
                    #endregion

                    #region 优惠券
                    if (demodel.User_Coupon_Id > 0)
                    {
                        var ccmodel = cList.Where(x => x.Id == demodel.User_Coupon_Id).FirstOrDefault();
                        string couponItem = (ccmodel?.CouponId ?? 0).ToString();
                        if (!string.IsNullOrEmpty(couponItem))
                        {
                            var dcModel = dcList.Where(x => x.ID == Convert.ToInt32(couponItem)).FirstOrDefault();
                            if (dcModel == null)
                            {
                                return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                            }
                            dcModel.DiscountsPrice = dcModel.DiscountsPrice == 0 ? 10 : dcModel.DiscountsPrice;
                            if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category)  //指定分类
                            {
                                var categoryList1 = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (categoryList.Select(x => x.Id).Where(x => categoryList1.Contains(x)).Any())
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                            else if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)//指定商品
                            {
                                var goodsList = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (goodsList.Contains(item.GoodsId ?? 0))
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                            else
                            {
                                GoodsCouponList.Add(new RB_Goods_CouponModel()
                                {
                                    GoodsId = item.GoodsId ?? 0,
                                    Key = item.SpecificationSort,
                                    TotalMoney = item.Final_Price ?? 0,
                                    CouponMoney = 0
                                });
                            }
                        }

                    }
                    #endregion

                    #region 课程卡
                    if (demodel.Use_Education_Id > 0)
                    {
                        var ccmodel = eList.Where(x => x.Id == demodel.Use_Education_Id).FirstOrDefault();
                        string couponItem = (ccmodel?.CouponId ?? 0).ToString();
                        if (!string.IsNullOrEmpty(couponItem))
                        {
                            var dcModel = deList.Where(x => x.ID == Convert.ToInt32(couponItem)).FirstOrDefault();
                            if (dcModel == null)
                            {
                                return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                            }
                            if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category)  //指定分类
                            {
                                var categoryList1 = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (categoryList.Select(x => x.Id).Where(x => categoryList1.Contains(x)).Any())
                                {
                                    if (dcModel.MaxDiscountsPrice == 0 || dcModel.MaxDiscountsPrice >= (item.Final_Price ?? 0))
                                    {
                                        GoodsCouponList.Add(new RB_Goods_CouponModel()
                                        {
                                            GoodsId = item.GoodsId ?? 0,
                                            Key = item.SpecificationSort,
                                            TotalMoney = item.Final_Price ?? 0,
                                            CouponMoney = 0
                                        });
                                    }
                                }
                            }
                            else if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)//指定商品
                            {
                                var goodsList = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (goodsList.Contains(item.GoodsId ?? 0))
                                {
                                    if (dcModel.MaxDiscountsPrice == 0 || dcModel.MaxDiscountsPrice >= (item.Final_Price ?? 0))
                                    {
                                        GoodsCouponList.Add(new RB_Goods_CouponModel()
                                        {
                                            GoodsId = item.GoodsId ?? 0,
                                            Key = item.SpecificationSort,
                                            TotalMoney = item.Final_Price ?? 0,
                                            CouponMoney = 0
                                        });
                                    }
                                }
                            }
                            else
                            {
                                if (dcModel.MaxDiscountsPrice == 0 || dcModel.MaxDiscountsPrice >= (item.Final_Price ?? 0))
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                        }
                    }
                    #endregion

                    Total_integral_price += (item.IntegralMoney ?? 0);
                    Total_use_integral += (item.IntegralNumber ?? 0);
                    TotalGoodsMoney += item.Final_Price ?? 0;
                    TotalGoodsOriginalMoney += (gmodel.OriginalPrice ?? 0) * (item.Number ?? 0);
                    TotalGoodsSellMoney += gmodel.MemberPrice * (item.Number ?? 0);
                    item.Unit_Price = gmodel.SellingPrice ?? 0;
                    item.Original_Price = gmodel.OriginalPrice ?? 0;
                    item.MemberPrice = gmodel.MemberPrice;
                    item.IntegralMoney = integral_price;
                    item.IntegralNumber = use_integral;
                    item.Discounts = discounts;
                    item.CategoryIdList = categoryList.Select(x => x.CategoryId ?? 0).ToList();
                }

                if (demodel.User_Coupon_Id > 0 && GoodsCouponList.Any())
                {
                    decimal FinalMoney = GoodsCouponList.Sum(x => x.TotalMoney);
                    var ccmodel = cList.Where(x => x.Id == demodel.User_Coupon_Id).FirstOrDefault();
                    var dcModel = dcList.Where(x => x.ID == (ccmodel?.CouponId ?? 0)).FirstOrDefault();
                    if (dcModel == null)
                    {
                        return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                    }
                    if (dcModel.MinConsumePrice > 0)
                    {
                        if (FinalMoney < dcModel.MinConsumePrice)
                        {
                            FinalMoney = 0;
                        }
                    }
                    if (dcModel.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.FullReduction && FinalMoney > 0)
                    {
                        CouponsMoney = dcModel.DiscountsPrice;
                    }
                    else if (dcModel.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount && FinalMoney > 0)
                    {
                        decimal disMoney = Math.Round(FinalMoney * (10 - dcModel.DiscountsPrice) / 10, 2, MidpointRounding.AwayFromZero);
                        if (dcModel.MaxDiscountsPrice > 0 && dcModel.MaxDiscountsPrice < disMoney)
                        {
                            disMoney = dcModel.MaxDiscountsPrice;
                        }
                        CouponsMoney = disMoney;
                    }
                    //每个商品优惠券分摊金额
                    if (CouponsMoney > 0)
                    {
                        foreach (var item in GoodsCouponList)
                        {
                            item.CouponMoney = Math.Round((item.TotalMoney / FinalMoney) * CouponsMoney, 2, MidpointRounding.AwayFromZero);
                        }
                        if (CouponsMoney != GoodsCouponList.Sum(x => x.CouponMoney))
                        {
                            //四舍五入存在差值
                            decimal diffMoney = CouponsMoney - GoodsCouponList.Sum(x => x.CouponMoney);
                            var gcModel = GoodsCouponList.OrderBy(x => x.CouponMoney).Take(1).FirstOrDefault();
                            gcModel.CouponMoney += diffMoney;
                        }
                    }
                }
                if (demodel.Use_Education_Id > 0 && GoodsCouponList.Any()) {
                    var ccmodel = eList.Where(x => x.Id == demodel.Use_Education_Id).FirstOrDefault();
                    GoodsCouponList = GoodsCouponList.OrderBy(x => x.TotalMoney).Take(ccmodel.HeXiao - ccmodel.UseHeXiao).ToList();
                }
                //赋值
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }

                    decimal couponMoney = 0;//优惠金额
                    if (demodel.User_Coupon_Id > 0)
                    {
                        var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                        if (couponModel != null)
                        {
                            couponMoney = couponModel.CouponMoney;
                            TotalGoodsMoney -= couponMoney;//总价格需减去优惠券金额
                        }
                    }
                    bool IsUseEducation = false;
                    if (demodel.Use_Education_Id > 0) {
                        var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                        if (couponModel != null) {
                            EducationNum += 1;
                            EducationMoney += couponModel.TotalMoney;
                            TotalGoodsMoney -= couponModel.TotalMoney;//总价格需减去课程卡金额
                            IsUseEducation = true;
                        }
                    }

                    goods_list.Add(new
                    {
                        id = gmodel.Id,
                        name = gmodel.Name,
                        categoryIdList = item.CategoryIdList,
                        num = item.Number,
                        forehead_integral = gmodel.PointsDeduction,
                        forehead_integral_type = gmodel.PointsDeductionType,
                        accumulative = gmodel.IsMultipleDeduction,//累计多件抵扣
                        unit_price = item.Unit_Price,
                        total_original_price = (item.Original_Price ?? 0) * (item.Number ?? 0),
                        total_price = (item.Unit_Price ?? 0) * (item.Number ?? 0),//优惠券（有平摊情况） 积分抵扣 （默认从第一个商品抵扣）
                        goods_attr = new
                        {
                            id = 0,
                            goods_id = gmodel.Id,
                            price = item.Unit_Price ?? 0,
                            original_price = item.Original_Price ?? 0,
                            pic_url = gmodel.CoverImage,
                            individual_share = umodel?.IsDistributor ?? 2,// 是否分销商
                            share_type = gmodel.SeparateDistributionMoneyType,//分销佣金类型,
                            member_price = item.MemberPrice,
                            integral_price = demodel.Use_Integral == 1 ? item.IntegralMoney : 0,//积分抵扣金额
                            use_integral = demodel.Use_Integral == 1 ? item.IntegralNumber : 0,
                            couponMoney,
                            is_use_education = IsUseEducation,
                            name = gmodel.Name,
                            cover_pic = gmodel.CoverImage,
                            detail = gmodel.GoodsDetails,
                            number = item.Number,
                            goods_share_level = DistributionCommissionList.Where(x => x.GoodsId == gmodel.Id).Select(x => new
                            {
                                share_commission_first = x.OneCommission,
                                share_commission_second = x.TwoCommission,
                                share_commission_third = x.ThreeCommission,
                                level = x.DistributorGrade
                            }),
                            attr_setting_type = gmodel.SeparateDistributionType,
                            course_score = gmodel.CourseScore
                        },
                        discounts = item.Discounts,
                        member_discount = ((item.Unit_Price ?? 0) * (item.Number ?? 0)) - (item.MemberPrice * (item.Number ?? 0)),
                        cover_pic = gmodel.CoverImage,
                        is_level_alone = gmodel.SeparateSetMember,//是否单独设置会员价
                        is_level = gmodel.EnjoyMember,//是否销售会员价格
                        marketingLogo = gmodel.MarketingLogo
                    });
                }
            }

            #region 其他封装
            List<object> mch_list = new List<object>();

            var minModel = miniProgramRepository.GetEntity(demodel.MallBaseId);
            //积分
            var IntegralObj = new
            {
                can_use = IsPointsDeduction,
                use = demodel.Use_Integral == 1 ? true : false,
                use_num = Total_use_integral,
                deduction_price = Total_integral_price
            };

            #region 提示无上级不返佣
            bool PromptNoSuperiorFY = false;
            var disbaseModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if ((disbaseModel?.IsEnableFXGrade ?? 2) == 1 && (disbaseModel?.IsEnableNoSuperiorFY ?? 1) == 2)
            {
                if ((umodel.SuperiorId ?? 0) == 0)
                {
                    PromptNoSuperiorFY = true;
                }
            }
            #endregion

            mch_list.Add(new
            {
                mch = new
                {
                    id = minModel?.MallBaseId ?? 0,
                    name = minModel?.MallName ?? ""
                },
                goods_list,
                remark = "",
                total_goods_price = TotalGoodsSellMoney,
                total_goods_original_price = TotalGoodsOriginalMoney,
                member_discount,
                coupon = new
                {
                    enabled = true,
                    use = CouponsMoney > 0 && demodel.User_Coupon_Id > 0 ? true : false,
                    coupon_discount = CouponsMoney,
                    user_coupon_id = CouponsMoney > 0 ? demodel.User_Coupon_Id ?? 0 : 0
                },
                integral = IntegralObj,
                education = new {
                    enabled = true,
                    use = demodel.Use_Education_Id > 0 ? true : false,
                    use_education_id = demodel.Use_Education_Id ?? 0,
                    education_money = EducationMoney,
                    education_num = EducationNum //抵扣几套课程
                },
                total_price = TotalGoodsMoney,
            });

            List<string> template_message_list = new List<string>();
            if (minModel != null)
            {
                if (!string.IsNullOrWhiteSpace(minModel.OrderSuccessTpl))
                {
                    template_message_list.Add(minModel.OrderSuccessTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderCancelTpl))
                {
                    template_message_list.Add(minModel.OrderCancelTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderDeliverGoodsTpl))
                {
                    template_message_list.Add(minModel.OrderDeliverGoodsTpl);
                }
            }
            var Robj = new
            {
                mch_list,
                promptNoSuperiorFY = PromptNoSuperiorFY,
                total_price = TotalGoodsMoney,
                price_enable = true,
                template_message_list 
            };
            #endregion
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 网课下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult SetAppletCourseOrderInfo(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            if (demodel.SmallShopsId == 0)
            {
                demodel.SmallShopsId = umodel.SmallShopId;
            }
            if (umodel.Blacklist == 1)
            {
                return ApiResult.Failed("您在黑名单状态无法下单，请联系管理员核实");
            }
            
            decimal TotalMoney = 0;
            string GoodsIds = "";
            int TotalIntegralNumber = 0;//总使用积分
            decimal TotalIntegralMoney = 0;//总使用积分抵扣金额
            List<RB_Goods_CouponModel> GoodsCouponList = new List<RB_Goods_CouponModel>();//商品优惠卷 价格（每个商品优惠的价格）
            decimal CouponsMoney = 0;//优惠卷验证
            decimal EducationMoney = 0;//课程卡抵扣金额
            int EducationNum = 0;//课程卡抵扣数量
            #region 优惠卷初始化
            List<RB_Member_DiscountCoupon_Extend> cList = new List<RB_Member_DiscountCoupon_Extend>();
            List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend> dcList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend>();
            List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend> dcpList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend>();
            demodel.CouponsIds = "";
            bool IsCommissionCoupons = true;// 是否通用优惠券  2020-08-13 ld
            if (demodel.User_Coupon_Id > 0)
            {
                demodel.CouponsIds = demodel.User_Coupon_Id.ToString();
                if (!string.IsNullOrEmpty(demodel.CouponsIds))
                {
                    cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 0, Ids = demodel.CouponsIds, UserId = umodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (cList.Any())
                    {
                        string cIds = string.Join(",", cList.Select(x => x.CouponId).Distinct());
                        dcList = discountCouponRepository.GetDiscountCouponList(new Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend() { CouponIds = cIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                        dcpList = discountCoupon_ProductRepository.GetListByDiscountCouponIds(new Model.Entity.MarketingCenter.RB_DiscountCoupon() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, cIds, true);
                        if (dcList.Any())
                        {
                            foreach (var item in cList)
                            {
                                if (item.CouponId > 0)
                                {
                                    if (!dcList.Where(x => x.ID == item.CouponId).Any())
                                    {
                                        return ApiResult.Failed("优惠券不存在，请核实后再试");
                                    }
                                }
                            }

                            if (dcList.Where(x => x.SmallShopId > 0).Any())
                            {
                                IsCommissionCoupons = false;
                            }
                        }
                    }
                }
            }
            #endregion

            #region 课程卡初始化
            List<RB_Education_MemberCoupon_Extend> eList = new List<RB_Education_MemberCoupon_Extend>();
            List<RB_Education_Coupon_Extend> deList = new List<RB_Education_Coupon_Extend>();
            List<RB_Education_CouponProduct_Extend> edcpList = new List<RB_Education_CouponProduct_Extend>();
            if (demodel.Use_Education_Id > 0)
            {
                if (demodel.User_Coupon_Id > 0)
                {
                    return ApiResult.Failed("课程卡与优惠券不能同时使用");
                }
                if (demodel.Use_Integral > 0)
                {
                    return ApiResult.Failed("课程卡与积分抵扣不能同时使用");
                }
                eList = education_MemberCouponRepository.GetList(new RB_Education_MemberCoupon_Extend() { Ids = (demodel.Use_Education_Id ?? 0).ToString(), UserId = umodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                if (eList.Any())
                {
                    var educationModel = eList.FirstOrDefault();
                    if (educationModel.HeXiao <= educationModel.UseHeXiao)
                    {
                        return ApiResult.Failed("课程卡剩余次数不足");
                    }
                    string cIds = string.Join(",", eList.Select(x => x.CouponId).Distinct());
                    deList = education_CouponRepository.GetDiscountCouponList(new RB_Education_Coupon_Extend() { CouponIds = cIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                    edcpList = education_CouponProductRepository.GetListByDiscountCouponIds(new Model.Entity.Education.RB_Education_Coupon() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, cIds, true);
                    if (deList.Any())
                    {
                        foreach (var item in eList)
                        {
                            if (item.CouponId > 0)
                            {
                                if (!deList.Where(x => x.ID == item.CouponId).Any())
                                {
                                    return ApiResult.Failed("课程卡不存在，请核实后再试");
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            if (demodel.DetailList.Any())
            {
                //积分
                Model.Entity.MarketingCenter.RB_Integral_Settings integralModel = new Model.Entity.MarketingCenter.RB_Integral_Settings();
                if (demodel.Use_Integral == 1 && umodel.Integral > 0)
                {
                    integralModel = integral_SettingsRepository.GetIntegralSettingsList(new Model.Entity.MarketingCenter.RB_Integral_Settings() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                }
                GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetListForCommission(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, 2);
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var mpriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                #region 微店价格
                RB_SmallShops_Info_Extend smallModel = new RB_SmallShops_Info_Extend();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (demodel.SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(demodel.SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = demodel.SmallShopsId, GoodsIds = GoodsIds });
                }
                #endregion

                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        return ApiResult.Failed("有商品不存在或者商品已失效");
                    }
                    if (gmodel.GoodsClassify != 2) {
                        return ApiResult.Failed("有非网课类商品");
                    }
                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();

                    item.CommissionPrice = gmodel.Commission;// 粉象 返佣金额
                    item.CostMoney = (gmodel.CostPrice ?? 0);
                    item.Specification = "[]";
                    item.SpecificationSort = "0";

                    item.PresentFXGrade = gmodel.PresentFXGrade ?? 0;//赠送粉象分销等级
                    item.PresentFXMonth = gmodel.PresentFXMonth ?? 0;

                    item.CategoryIdList = categoryList.Select(x => x.CategoryId ?? 0).ToList();              

                    #region 规格
                    item.SmallShopsCostPrice = gmodel.SellingPrice ?? 0;
                    if (demodel.SmallShopsId > 0)
                    {
                        if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.GoodsId && x.UpPrice > 0).Any())
                        {
                            var sspModel = smallPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == "").FirstOrDefault();
                            if (sspModel != null)
                            {
                                //单商品设置的
                                if (sspModel.PriceType == 1)
                                {
                                    gmodel.SellingPrice += Math.Ceiling((gmodel.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                }
                                else if (sspModel.PriceType == 2)
                                {
                                    gmodel.SellingPrice += (sspModel.UpPrice ?? 0);
                                }
                            }
                            else
                            {
                                if ((smallModel.UpPrice ?? 0) > 0)
                                {
                                    if (smallModel.PriceType == 1)
                                    {
                                        gmodel.SellingPrice += Math.Ceiling((gmodel.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (smallModel.PriceType == 2)
                                    {
                                        gmodel.SellingPrice += (smallModel.UpPrice ?? 0);
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region 会员价格
                    gmodel.MemberPrice = gmodel.SellingPrice ?? 0;
                    if (umodel.MemberGrade > 0)
                    {
                        if (gmodel.EnjoyMember == 1 && gmodel.SeparateSetMember == 1)
                        {
                            gmodel.MemberPrice = mpriceList.Where(x => x.GoodsId == item.GoodsId && x.MemberGrade == umodel.MemberGrade && x.SpecificationSort == item.SpecificationSort).FirstOrDefault()?.MemberPrice ?? 0;
                            item.IsMemberPrice = 1;
                            item.SmallShopsCostPrice = gmodel.MemberPrice;
                            if (demodel.SmallShopsId > 0)
                            {
                                if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.GoodsId && x.UpPrice > 0).Any())
                                {
                                    var sspModel = smallPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            gmodel.MemberPrice += Math.Ceiling((gmodel.MemberPrice) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            gmodel.MemberPrice += (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                gmodel.MemberPrice += Math.Ceiling((gmodel.MemberPrice) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                gmodel.MemberPrice += (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //求会员等级折扣
                            var gradeModel = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { Grade = umodel.MemberGrade, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                            gmodel.MemberPrice = Math.Round((gmodel.SellingPrice ?? 0) * (gradeModel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            item.SmallShopsCostPrice = Math.Round((item.SmallShopsCostPrice ?? 0) * (gradeModel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            item.DiscountRate = gradeModel?.Discount ?? 10;
                        }
                    }

                    if (umodel.MemberGrade > 0)
                    {
                        item.Final_Price = gmodel.MemberPrice * (item.Number ?? 0);
                    }
                    else
                    {
                        item.Final_Price = (gmodel.SellingPrice ?? 0) * (item.Number ?? 0);
                    }
                    #endregion

                    #region 直播返佣
                    item.LiveCommission = 0;
                    item.LiveFinanceIds = "";
                    if (gmodel.IsLiveGoods == 1)
                    {
                        item.LiveCommission = (item.CommissionPrice / 4) * (item.Number ?? 0);
                    }
                    #endregion

                    item.SmallShopsCostPrice = (item.SmallShopsCostPrice ?? 0) * (item.Number ?? 0);

                    item.Unit_Price = gmodel.SellingPrice ?? 0;
                    item.Original_Price = (item.Unit_Price) * (item.Number);

                    #region  积分
                    if (umodel.Integral > 0 && gmodel.PointsDeduction > 0 && integralModel.IntegralNum > 0)
                    {
                        decimal SingleMaxMoney = 0, MultMaxMoney = 0;
                        if (gmodel.PointsDeductionType == 1)
                        {
                            SingleMaxMoney = Math.Round(gmodel.MemberPrice * (gmodel.PointsDeduction ?? 0) / 100, 2, MidpointRounding.AwayFromZero);
                            MultMaxMoney = Math.Round(gmodel.MemberPrice * (item.Number ?? 0) * (gmodel.PointsDeduction ?? 0) / 100, 2, MidpointRounding.AwayFromZero);
                        }
                        if (gmodel.IsMultipleDeduction == 1)
                        {
                            //可以多件商品可累计抵扣
                            if (gmodel.PointsDeductionType == 1)
                            {
                                int MaxInterral = Convert.ToInt32(MultMaxMoney * integralModel.IntegralNum);
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                            else
                            {
                                int MaxInterral = Convert.ToInt32((gmodel.PointsDeduction ?? 0) * integralModel.IntegralNum * (item.Number ?? 0));
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                        }
                        else
                        {
                            //单件商品
                            if (gmodel.PointsDeductionType == 1)
                            {
                                int MaxInterral = Convert.ToInt32(SingleMaxMoney * integralModel.IntegralNum);
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                            else
                            {
                                int MaxInterral = Convert.ToInt32((gmodel.PointsDeduction ?? 0) * integralModel.IntegralNum);
                                //最多可抵扣积分
                                if (umodel.Integral > MaxInterral)
                                {
                                    item.IntegralNumber = MaxInterral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(MaxInterral) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral -= MaxInterral;
                                }
                                else
                                {
                                    item.IntegralNumber = umodel.Integral;
                                    item.IntegralMoney = Math.Round(Convert.ToDecimal(umodel.Integral ?? 0) / integralModel.IntegralNum, 2, MidpointRounding.AwayFromZero);
                                    umodel.Integral = 0;
                                }
                            }
                        }
                    }
                    if (demodel.Use_Integral == 1)
                    {
                        TotalIntegralNumber += (item.IntegralNumber ?? 0);
                        TotalIntegralMoney += (item.IntegralMoney ?? 0);
                        item.Final_Price -= (item.IntegralMoney ?? 0);
                        item.SmallShopsCostPrice -= (item.IntegralMoney ?? 0);
                    }
                    #endregion

                    #region 优惠券
                    if (demodel.User_Coupon_Id > 0)
                    {
                        var ccmodel = cList.Where(x => x.Id == demodel.User_Coupon_Id).FirstOrDefault();
                        string couponItem = (ccmodel?.CouponId ?? 0).ToString();
                        if (!string.IsNullOrEmpty(couponItem))
                        {
                            var dcModel = dcList.Where(x => x.ID == Convert.ToInt32(couponItem)).FirstOrDefault();
                            if (dcModel == null)
                            {
                                return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                            }
                            dcModel.DiscountsPrice = dcModel.DiscountsPrice == 0 ? 10 : dcModel.DiscountsPrice;
                            if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category)  //指定分类
                            {
                                var categoryList1 = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (categoryList.Select(x => x.Id).Where(x => categoryList1.Contains(x)).Any())
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                            else if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)//指定商品
                            {
                                var goodsList = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (goodsList.Contains(item.GoodsId ?? 0))
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                            else
                            {
                                GoodsCouponList.Add(new RB_Goods_CouponModel()
                                {
                                    GoodsId = item.GoodsId ?? 0,
                                    Key = item.SpecificationSort,
                                    TotalMoney = item.Final_Price ?? 0,
                                    CouponMoney = 0
                                });
                            }
                        }

                    }
                    #endregion

                    #region 课程卡
                    if (demodel.Use_Education_Id > 0)
                    {
                        var ccmodel = eList.Where(x => x.Id == demodel.Use_Education_Id).FirstOrDefault();
                        string couponItem = (ccmodel?.CouponId ?? 0).ToString();
                        if (!string.IsNullOrEmpty(couponItem))
                        {
                            var dcModel = deList.Where(x => x.ID == Convert.ToInt32(couponItem)).FirstOrDefault();
                            if (dcModel == null)
                            {
                                return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                            }
                            if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category)  //指定分类
                            {
                                var categoryList1 = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (categoryList.Select(x => x.Id).Where(x => categoryList1.Contains(x)).Any())
                                {
                                    if (dcModel.MaxDiscountsPrice == 0 || dcModel.MaxDiscountsPrice >= (item.Final_Price ?? 0))
                                    {
                                        GoodsCouponList.Add(new RB_Goods_CouponModel()
                                        {
                                            GoodsId = item.GoodsId ?? 0,
                                            Key = item.SpecificationSort,
                                            TotalMoney = item.Final_Price ?? 0,
                                            CouponMoney = 0
                                        });
                                    }
                                }
                            }
                            else if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)//指定商品
                            {
                                var goodsList = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (goodsList.Contains(item.GoodsId ?? 0))
                                {
                                    if (dcModel.MaxDiscountsPrice == 0 || dcModel.MaxDiscountsPrice >= (item.Final_Price ?? 0))
                                    {
                                        GoodsCouponList.Add(new RB_Goods_CouponModel()
                                        {
                                            GoodsId = item.GoodsId ?? 0,
                                            Key = item.SpecificationSort,
                                            TotalMoney = item.Final_Price ?? 0,
                                            CouponMoney = 0
                                        });
                                    }
                                }
                            }
                            else
                            {
                                if (dcModel.MaxDiscountsPrice == 0 || dcModel.MaxDiscountsPrice >= (item.Final_Price ?? 0))
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                        }
                    }
                    #endregion

                    TotalMoney += (item.Final_Price ?? 0);
                    item.OrderType = gmodel.GoodsType;
                    item.GoodsName = gmodel.Name;
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(gmodel.CarouselImage) && gmodel.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(gmodel.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                    item.SeparateDistribution = gmodel.SeparateDistribution;
                    item.SeparateDistributionType = gmodel.SeparateDistributionType;
                    item.SeparateDistributionMoneyType = gmodel.SeparateDistributionMoneyType;
                    item.IntegralPresent = gmodel.IntegralPresent;
                    item.IntegralPresentType = gmodel.IntegralPresentType;

                }

                if (demodel.User_Coupon_Id > 0 && GoodsCouponList.Any())
                {
                    decimal FinalMoney = GoodsCouponList.Sum(x => x.TotalMoney);
                    var ccmodel = cList.Where(x => x.Id == demodel.User_Coupon_Id).FirstOrDefault();
                    var dcModel = dcList.Where(x => x.ID == (ccmodel?.CouponId ?? 0)).FirstOrDefault();
                    if (dcModel == null)
                    {
                        return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                    }
                    if (dcModel.MinConsumePrice > 0)
                    {
                        if (FinalMoney < dcModel.MinConsumePrice)
                        {
                            FinalMoney = 0;
                        }
                    }
                    if (dcModel.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.FullReduction && FinalMoney > 0)
                    {
                        CouponsMoney = dcModel.DiscountsPrice;
                    }
                    else if (dcModel.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount && FinalMoney > 0)
                    {
                        decimal disMoney = Math.Round(FinalMoney * (10 - dcModel.DiscountsPrice) / 10, 2, MidpointRounding.AwayFromZero);
                        if (dcModel.MaxDiscountsPrice > 0 && dcModel.MaxDiscountsPrice < disMoney)
                        {
                            disMoney = dcModel.MaxDiscountsPrice;
                        }
                        CouponsMoney = disMoney;
                    }
                    //每个商品优惠券分摊金额
                    if (CouponsMoney > 0)
                    {
                        foreach (var item in GoodsCouponList)
                        {
                            item.CouponMoney = Math.Round((item.TotalMoney / FinalMoney) * CouponsMoney, 2, MidpointRounding.AwayFromZero);
                        }
                        if (CouponsMoney != GoodsCouponList.Sum(x => x.CouponMoney))
                        {
                            //四舍五入存在差值
                            decimal diffMoney = CouponsMoney - GoodsCouponList.Sum(x => x.CouponMoney);
                            var gcModel = GoodsCouponList.OrderBy(x => x.CouponMoney).Take(1).FirstOrDefault();
                            gcModel.CouponMoney += diffMoney;
                        }
                    }
                }
                if (demodel.Use_Education_Id > 0 && GoodsCouponList.Any())
                {
                    var ccmodel = eList.Where(x => x.Id == demodel.Use_Education_Id).FirstOrDefault();
                    GoodsCouponList = GoodsCouponList.OrderBy(x => x.TotalMoney).Take(ccmodel.HeXiao - ccmodel.UseHeXiao).ToList();
                }

                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    item.SupplierId = gmodel.SupplierId;
                    item.CouponMoney = 0;
                    if (demodel.User_Coupon_Id > 0)
                    {
                        var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                        if (couponModel != null)
                        {
                            item.CouponMoney = couponModel.CouponMoney;
                            TotalMoney -= (item.CouponMoney ?? 0);//总价格需减去优惠券金额
                            item.Final_Price -= (item.CouponMoney ?? 0);
                            if (IsCommissionCoupons)
                            {
                                //通用优惠券
                                item.SmallShopsCostPrice -= (item.CouponMoney ?? 0);
                            }
                        }
                    }
                    item.EducationCouponId = 0;
                    if (demodel.Use_Education_Id > 0)
                    {
                        var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                        if (couponModel != null)
                        {
                            EducationMoney += couponModel.TotalMoney;
                            EducationNum += 1;
                            item.EducationCouponId = demodel.Use_Education_Id;
                        }
                    }

                    item.FreightMoney = 0;

                    item.CommentGiveIntegral = 0;
                    if (gmodel.IntegralComment > 0)
                    {
                        if (gmodel.IntegralCommentType == 1)
                        {
                            item.CommentGiveIntegral = Convert.ToInt32(Math.Floor((gmodel.IntegralComment ?? 0) * (item.Final_Price ?? 0) / 100));
                        }
                        else
                        {
                            item.CommentGiveIntegral = Convert.ToInt32((gmodel.IntegralComment ?? 0) * (item.Number ?? 0));
                        }
                    }
                }
            }
            if (demodel.EducationMoney != EducationMoney)
            {
                return ApiResult.Failed("课程卡抵扣金额不正确");
            }
            if (CouponsMoney != demodel.CouponMoney)
            {
                return ApiResult.Failed("优惠金额计算有误");
            }
            //验证总额
            if (demodel.Income != (TotalMoney - EducationMoney))
            {
                return ApiResult.Failed("订单合计金额不正确");
            }
            demodel.PreferPrice = TotalMoney + CouponsMoney;

            #region 手续费计算
            decimal ServiceCharge = Convert.ToDecimal(Config.SettlementRate) / 100;
            if (ServiceCharge > 0)
            {
                decimal TotalFee = Math.Round((demodel.Income ?? 0) * ServiceCharge, 2, MidpointRounding.AwayFromZero);
                if (demodel.DetailList.Any())
                {
                    int dcount = demodel.DetailList.Count();
                    decimal avgFee = Math.Round(TotalFee / dcount, 2, MidpointRounding.AwayFromZero);
                    foreach (var item in demodel.DetailList)
                    {
                        item.ServiceCharge = avgFee;
                    }
                    if (avgFee * dcount != TotalFee)
                    {
                        //多余的  直接算在第一个商品里
                        var detailmodel = demodel.DetailList.FirstOrDefault();
                        detailmodel.ServiceCharge += (TotalFee - avgFee * dcount);
                    }
                }
            }
            #endregion

            var trans = goods_OrderRepository.DbTransaction;
            try
            {
                Random R = new Random();
                int Rstr = R.Next(111, 999);
                demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                demodel.PaymentWay = OrderPaymentTypeEnum.OnlinePayment;//先默认在线支付
                demodel.Remark ??= "";
                demodel.ApplyForCancelStatus ??= 0;
                if (demodel.Income == 0)
                {
                    demodel.OrderStatus = OrderStatusEnum.Completed;
                    demodel.PaymentTime = DateTime.Now;
                    demodel.DeliveryTime = DateTime.Now;
                    demodel.ReceivingTime = DateTime.Now;
                    demodel.FinishTime = DateTime.Now;
                }
                int OrderId = goods_OrderRepository.Insert(demodel, trans);
                if (OrderId > 0)
                {
                    #region 公司比例
                    demodel.CompanyProfitRate = 0;
                    demodel.CompanyId = 0;
                    var pUserId = member_UserRepository.GetMemberFristParentren(demodel.UserId ?? 0);
                    if (pUserId > 0)
                    {
                        var pumodel = member_UserRepository.GetEntity(pUserId);
                        demodel.CompanyProfitRate = (pumodel?.CompanyProfitRate ?? 0);
                        demodel.CompanyId = pUserId;
                    }
                    #endregion
                    //插入订单明细+ 商品库存更新 
                    InsertOrderDetail(demodel, trans, OrderId, new List<FreeShippingGoodsDetail>());

                    //用户订单数增加
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Member_User_Extend.OrderNum),(umodel.OrderNum??0)+1}
                    };

                    //优惠券使用
                    if (cList.Any())
                    {
                        foreach (var item in cList)
                        {
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_DiscountCoupon_Extend.UseDate),DateTime.Now},
                                { nameof(RB_Member_DiscountCoupon_Extend.UseState),1}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_DiscountCoupon_Extend.Id),
                                      FiledValue=item.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            member_CouponRepository.Update(keyValues1, wheres1, trans);
                            umodel.CouponsNum = (umodel.CouponsNum ?? 0) - 1;
                        }
                        if (umodel.CouponsNum < 0) { umodel.CouponsNum = 0; }
                        keyValues.Add(nameof(RB_Member_User_Extend.CouponsNum), umodel.CouponsNum);
                    }
                    //积分
                    if (demodel.Use_Integral == 1 && TotalIntegralNumber > 0)
                    {
                        keyValues.Add(nameof(RB_Member_User_Extend.Integral), (umodel.Integral ?? 0));
                        member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                        {
                            Id = 0,
                            CreateDate = DateTime.Now,
                            Description = "订单使用积分抵扣" + TotalIntegralMoney + "元，订单号：" + demodel.OrderNo,
                            Image = 0,
                            Integral = TotalIntegralNumber,
                            MallBaseId = demodel.MallBaseId,
                            PlatformType = demodel.OrderSource,
                            Remarks = "",
                            TenantId = demodel.TenantId,
                            Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
                            UserId = demodel.UserId,
                            OrderId = OrderId
                        }, trans);
                    }

                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Member_User_Extend.Id),
                              FiledValue=umodel.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_UserRepository.Update(keyValues, wheres, trans);

                    #region 课程卡使用
                    if (demodel.Use_Education_Id > 0 && EducationNum > 0) {
                        education_MemberUseCouponRepository.Insert(new Model.Entity.Education.RB_Education_MemberUseCoupon()
                        {
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            MemberCouponId = demodel.Use_Education_Id,
                            OrderId = OrderId,
                            Remarks = "",
                            Status = 0,
                            TenantId = demodel.TenantId,
                            UseDate = DateTime.Now,
                            UserId = demodel.UserId,
                            UseHeXiao = EducationNum
                        }, trans);
                        var educationModel = eList.FirstOrDefault();
                        if (educationModel != null) {
                            //更新用户课程卡 已使用数量
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Education_MemberCoupon_Extend.UseHeXiao),educationModel.UseHeXiao + EducationNum}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Education_MemberCoupon_Extend.Id),
                                      FiledValue=educationModel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            education_MemberCouponRepository.Update(keyValues1, wheres1, trans);
                        }
                    }
                    #endregion

                    //来自购物车的话  需清除购物车数据
                    if (demodel.IsFormShoppingCart == 1)
                    {
                        foreach (var cartItem in demodel.ShoppingCartIdList)
                        {
                            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                { nameof(RB_Goods_ShoppingCart.Status),1},
                                { nameof(RB_Goods_ShoppingCart.UpdateDate),DateTime.Now}
                            };
                            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.Id),
                                        FiledValue=cartItem,
                                        OperatorEnum=OperatorEnum.IN
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.UserId),
                                        FiledValue=demodel.UserId,
                                        OperatorEnum=OperatorEnum.IN
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.TenantId),
                                        FiledValue=demodel.TenantId,
                                        OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.MallBaseId),
                                        FiledValue=demodel.MallBaseId,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_ShoppingCartRepository.Update(keyValues2, wheres2);
                        }
                    }
                    //下线
                    if (umodel.DownlineCondition == Common.Enum.User.DistrbutorReferralsEnum.SCXD && umodel.IsBeDownline == 2)
                    {
                        //首次下单成为下线
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            {nameof(RB_Member_User_Extend.SuperiorId),umodel.WaitSuperiorId },
                            {nameof(RB_Member_User_Extend.IsBeDownline),1 },
                            {nameof(RB_Member_User_Extend.BeDownlineDate),DateTime.Now },
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                  FiledValue=umodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        member_UserRepository.Update(keyValues1, wheres1, trans);
                    }

                    //任务执行返佣  失败查看日志，手动返佣(空闲可增加手动返佣接口)
                    if (demodel.User_Coupon_Id > 0 && demodel.CouponMoney > 0)
                    {
                        demodel.CouponDestription = "使用" + (IsCommissionCoupons ? "通用" : "店铺") + "优惠券抵扣";
                    }
                    Task.Run(() => InsertOrderCommission(demodel, umodel, GoodsIds, OrderId));
                    //记录日志
                    goods_LogRepository.Insert(new RB_Goods_Log()
                    {
                        Id = 0,
                        Type = 1,
                        SourceId = OrderId,
                        Content = "新增课程订单",
                        CreateDate = DateTime.Now,
                        MallBaseId = demodel.MallBaseId,
                        TenantId = demodel.TenantId
                    });
                }
                goods_OrderRepository.DBSession.Commit();
                return ApiResult.Success("", new { OrderId });
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetAppletGoodsOrderInfo");
                goods_OrderRepository.DBSession.Rollback("SetAppletGoodsOrderInfo");
                return ApiResult.Failed();
            }
        }


        #region 电商订单线下付款
        public bool SetOrderOfflinePayment(RB_Goods_Order_Extend orderModel, int tenantId, int mallBaseId, int empId)
        {
            //修改订单状态
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_Order.OrderStatus),OrderStatusEnum.WaitSendGoods},
                { nameof(RB_Goods_Order.OrderSource),UserSourceEnum.ERP},
                { nameof(RB_Goods_Order.PaymentTime),orderModel.CreateDate}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.OrderId),
                      FiledValue=orderModel.OrderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //修改订单明细 其他收入
                var list = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderModel.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
                foreach (var item in list) {
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        { nameof(RB_Goods_OrderDetail.YSMoney),0},
                        { nameof(RB_Goods_OrderDetail.ServiceCharge),0}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderDetail.Id),
                              FiledValue=item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    goods_OrderDetailRepository.Update(keyValues1, wheres1);
                }
                //记录日志
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Id = 0,
                    Type = 1,
                    SourceId = orderModel.OrderId,
                    Content = "修改订单为线下付款，EmpId:" + empId,
                    CreateDate = DateTime.Now,
                    MallBaseId = mallBaseId,
                    TenantId = tenantId
                });
            }
            return flag;
        }
        #endregion
    }
}
