using Mall.AOP.CustomerAttribute;
using Mall.Common;
using Mall.Common.API;
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.Entity.User;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.Education;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.Reserve;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Customer;
using Mall.Repository.Finance;
using Mall.Repository.GuideCar;
using Mall.Repository.MarketingCenter;
using Mall.Repository.Product;
using Mall.Repository.Reserve;
using Mall.Repository.User;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client.Framing.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 商品处理层
    /// </summary>
    public partial class OrderModule
    {

        private readonly RB_WeChatPublicAccountModule weChatPublicAccountModule = new RB_WeChatPublicAccountModule();
        /// <summary>
        /// 素材管理
        /// </summary>
        private readonly RB_Material_InfoRepository material_InfoRepository = new RB_Material_InfoRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Product_CategoryRepository product_CategoryRepository = new RB_Product_CategoryRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Goods_CategoryRepository goods_CategoryRepository = new RB_Goods_CategoryRepository();
        /// <summary>
        /// 商品规格
        /// </summary>
        private readonly RB_Goods_SpecificationRepository goods_SpecificationRepository = new RB_Goods_SpecificationRepository();
        /// <summary>
        /// 商品规格值
        /// </summary>
        private readonly RB_Goods_SpecificationValueRepository goods_SpecificationValueRepository = new RB_Goods_SpecificationValueRepository();
        /// <summary>
        /// 商品优惠仓储类
        /// </summary>
        private readonly RB_Goods_PreferentialRepository RB_Goods_PreferentialRepository = new RB_Goods_PreferentialRepository();
        /// <summary>
        /// 商品规格价格
        /// </summary>
        private readonly RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new RB_Goods_SpecificationPriceRepository();
        /// <summary>
        /// 分销商等级
        /// </summary>
        private readonly RB_Distributor_GradeRepository distributor_GradeRepository = new RB_Distributor_GradeRepository();
        /// <summary>
        /// 分销基础配置
        /// </summary>
        private readonly RB_Distributor_BasicsRepository distributor_BasicsRepository = new RB_Distributor_BasicsRepository();
        /// <summary>
        /// 会员等级
        /// </summary>
        private readonly RB_Member_GradeRepository member_GradeRepository = new RB_Member_GradeRepository();
        /// <summary>
        /// 商品分销佣金
        /// </summary>
        private readonly RB_Goods_DistributionCommissionRepository goods_DistributionCommissionRepository = new RB_Goods_DistributionCommissionRepository();
        /// <summary>
        /// 商品会员价格
        /// </summary>
        private readonly RB_Goods_MemberPriceRepository goods_MemberPriceRepository = new RB_Goods_MemberPriceRepository();
        /// <summary>
        /// 运费
        /// </summary>
        private readonly RB_Logistics_RulesRepository logistics_RulesRepository = new RB_Logistics_RulesRepository();
        private readonly RB_Logistics_RulesRegionRepository logistics_RulesRegionRepository = new RB_Logistics_RulesRegionRepository();
        private readonly RB_Logistics_RulesPriceRepository logistics_RulesPriceRepository = new RB_Logistics_RulesPriceRepository();
        /// <summary>
        /// 订单商品
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 订单明细
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 区域
        /// </summary>
        private readonly Rb_destinationRepository destinationRepository = new Rb_destinationRepository();
        /// <summary>
        /// 订单快递
        /// </summary>
        private readonly RB_Goods_OrderExpressRepository goods_OrderExpressRepository = new RB_Goods_OrderExpressRepository();
        /// <summary>
        /// 订单快递关联
        /// </summary>
        private readonly RB_Goods_ExpressRelevanceRepository goods_ExpressRelevanceRepository = new RB_Goods_ExpressRelevanceRepository();
        /// <summary>
        /// 会员
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// ERP 同业积分
        /// </summary>
        private readonly RB_Customer_IntegralRepository customer_IntegralRepository = new RB_Customer_IntegralRepository();
        /// <summary>
        /// 用户余额
        /// </summary>
        private readonly RB_Member_BalanceRepository member_BalanceRepository = new RB_Member_BalanceRepository();
        /// <summary>
        /// 分销商
        /// </summary>
        private readonly RB_Distributor_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();
        /// <summary>
        /// 快递表
        /// </summary>
        private readonly RB_Logistics_ExpressRepository logistics_ExpressRepository = new RB_Logistics_ExpressRepository();
        /// <summary>
        /// 返佣
        /// </summary>
        private readonly RB_Goods_OrderCommissionRepository goods_OrderCommissionRepository = new RB_Goods_OrderCommissionRepository();
        /// <summary>
        /// 日志
        /// </summary>
        private readonly RB_Goods_LogRepository goods_LogRepository = new RB_Goods_LogRepository();
        /// <summary>
        /// 购物车
        /// </summary>
        private readonly RB_Goods_ShoppingCartRepository goods_ShoppingCartRepository = new RB_Goods_ShoppingCartRepository();
        /// <summary>
        /// 收货地址
        /// </summary>
        private readonly RB_Member_ShippingAddressRepository member_ShippingAddressRepository = new RB_Member_ShippingAddressRepository();
        /// <summary>
        /// 优惠卷
        /// </summary>
        private readonly RB_Member_CouponRepository member_CouponRepository = new RB_Member_CouponRepository();
        private readonly RB_DiscountCouponRepository discountCouponRepository = new RB_DiscountCouponRepository();
        private readonly RB_DiscountCoupon_ProductRepository discountCoupon_ProductRepository = new RB_DiscountCoupon_ProductRepository();
        /// <summary>
        /// 用户储值卡
        /// </summary>
        private readonly RB_Member_DepositBuyRepository member_DepositBuyRepository = new RB_Member_DepositBuyRepository();
        /// <summary>
        /// 储值卡流水
        /// </summary>
        private readonly RB_Member_DepositBalanceRepository member_DepositBalanceRepository = new RB_Member_DepositBalanceRepository();
        /// <summary>
        /// 售后订单列表
        /// </summary>
        private readonly RB_Goods_OrderAfterSaleRepository goods_OrderAfterSaleRepository = new RB_Goods_OrderAfterSaleRepository();
        /// <summary>
        /// 售后订单流程
        /// </summary>
        private readonly RB_Goods_OrderAfterSaleLogRepository goods_OrderAfterSaleLogRepository = new RB_Goods_OrderAfterSaleLogRepository();
        /// <summary>
        /// 公司收货地址
        /// </summary>
        private readonly RB_Logistics_DeliveryRepository logistics_DeliveryRepository = new RB_Logistics_DeliveryRepository();
        /// <summary>
        /// 评论模板
        /// </summary>
        private readonly RB_Goods_CommentTemplateRepository goods_CommentTemplateRepository = new RB_Goods_CommentTemplateRepository();
        /// <summary>
        /// 商品评论
        /// </summary>
        private readonly RB_Goods_CommentRepository goods_CommentRepository = new RB_Goods_CommentRepository();
        /// <summary>
        /// 用户积分
        /// </summary>
        private readonly RB_Member_IntegralRepository member_IntegralRepository = new RB_Member_IntegralRepository();
        /// <summary>
        /// 积分规则
        /// </summary>
        private readonly RB_Integral_SettingsRepository integral_SettingsRepository = new RB_Integral_SettingsRepository();
        /// <summary>
        /// 小程序
        /// </summary>
        private readonly RB_MiniProgramRepository miniProgramRepository = new RB_MiniProgramRepository();
        /// <summary>
        /// 订单支付
        /// </summary>
        private readonly RB_Goods_Online_TradeRepository goods_Online_TradeRepository = new RB_Goods_Online_TradeRepository();
        /// <summary>
        /// 小程序基础
        /// </summary>
        private readonly RB_MallBaseRepository mallBaseRepository = new RB_MallBaseRepository();
        /// <summary>
        /// 字典
        /// </summary>
        private readonly Rb_DictvalueRepository dictvalueRepository = new Rb_DictvalueRepository();

        /// <summary>
        /// 和平返佣
        /// </summary>
        private readonly RB_Distributor_HPCommissionRepository distributor_HPCommissionRepository = new RB_Distributor_HPCommissionRepository();
        /// <summary>
        /// 和平返佣比例
        /// </summary>
        private readonly RB_Distributor_HPGradeRatioRepository distributor_HPGradeRatioRepository = new RB_Distributor_HPGradeRatioRepository();
        /// <summary>
        /// 和平等级
        /// </summary>
        private readonly RB_Distributor_HPGradeInfoRepository distributor_HPGradeInfoRepository = new RB_Distributor_HPGradeInfoRepository();
        /// <summary>
        /// 分销提现
        /// </summary>
        private readonly RB_Distributor_RemitRepository distributor_RemitRepository = new RB_Distributor_RemitRepository();
        /// <summary>
        /// 商品限购区域
        /// </summary>
        private readonly RB_Goods_AreaRepository goods_AreaRepository = new RB_Goods_AreaRepository();
        /// <summary>
        /// 财务单据规则
        /// </summary>
        private readonly RB_Finance_ConfigurineRepository financeConfigurineRepository = new RB_Finance_ConfigurineRepository();
        /// <summary>
        /// 粉象返佣
        /// </summary>
        private readonly RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();
        /// <summary>
        /// 推荐供应商返佣
        /// </summary>
        private readonly RB_Goods_OrderIntroductionRepository goods_OrderIntroductionRepository = new RB_Goods_OrderIntroductionRepository();
        /// <summary>
        /// vip购买记录
        /// </summary>
        private readonly RB_Vip_BuyRepository vip_BuyRepository = new RB_Vip_BuyRepository();

        /// <summary>
        /// vip购买返佣
        /// </summary>
        private readonly RB_VipBuy_CommissionRepository vipBuy_CommissionRepository = new RB_VipBuy_CommissionRepository();

        /// <summary>
        /// 供应商
        /// </summary>
        private readonly RB_SupplierRepository supplierRepository = new RB_SupplierRepository();

        /// <summary>
        /// 推荐供应商返佣比例
        /// </summary>
        private readonly RB_SupplierCommissionRepository supplierCommissionRepository = new RB_SupplierCommissionRepository();

        /// <summary>
        /// 分类包邮规则仓储层对象
        /// </summary>
        private readonly RB_FreeShippingRepository freeShippingRepository = new RB_FreeShippingRepository();

        /// <summary>
        /// 全局包邮记录
        /// </summary>
        private readonly RB_Goods_OrderDetailFreeShippingRepository orderDetailFreeShippingRepository = new RB_Goods_OrderDetailFreeShippingRepository();
        /// <summary>
        /// 微店基础
        /// </summary>
        private readonly RB_MicroShop_BasicsRepository microShop_BasicsRepository = new RB_MicroShop_BasicsRepository();
        /// <summary>
        /// 微店基础
        /// </summary>
        private readonly RB_SmallShops_CustomRepository smallShops_CustomRepository = new RB_SmallShops_CustomRepository();
        /// <summary>
        /// 微店
        /// </summary>
        private readonly RB_SmallShops_InfoRepository smallShops_InfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 微店商品价格
        /// </summary>
        private readonly RB_SmallShops_PriceRepository smallShops_PriceRepository = new RB_SmallShops_PriceRepository();
        /// <summary>
        /// 微店佣金
        /// </summary>
        private readonly RB_SmallShops_CommissionRepository smallShops_CommissionRepository = new RB_SmallShops_CommissionRepository();
        /// <summary>
        /// 财务单据
        /// </summary>
        private readonly RB_FinanceRepository financeRepository = new RB_FinanceRepository();
        /// <summary>
        /// 活动
        /// </summary>
        private readonly RB_Goods_ActivityRepository goods_ActivityRepository = new RB_Goods_ActivityRepository();

        /// <summary>
        /// 微店返佣
        /// </summary>
        private readonly RB_SmallShops_CommissionRepository smallShopsCommissionRepository = new RB_SmallShops_CommissionRepository();
        /// <summary>
        /// 微店提现
        /// </summary>
        private readonly RB_SmallShops_RemitRepository smallShops_RemitRepository = new RB_SmallShops_RemitRepository();
        /// <summary>
        /// 微店信息
        /// </summary>
        private readonly RB_SmallShops_InfoRepository smallShopsInfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 商品可预定日期
        /// </summary>
        private readonly RB_Goods_TargetDateRepository goods_TargetDateRepository = new RB_Goods_TargetDateRepository();
        /// <summary>
        /// 司导-基础
        /// </summary>
        private readonly RB_GuideCar_BaseRepository guideCar_BaseRepository = new RB_GuideCar_BaseRepository();
        /// <summary>
        /// 司导-导游
        /// </summary>
        private readonly RB_GuideCar_GuideRepository guideCar_GuideRepository = new RB_GuideCar_GuideRepository();
        /// <summary>
        /// 司导-车辆
        /// </summary>
        private readonly RB_GuideCar_CarRepository guideCar_CarRepository = new RB_GuideCar_CarRepository();
        /// <summary>
        /// 司导站点
        /// </summary>
        private readonly RB_GuideCar_SiteRepository guideCar_SiteRepository = new RB_GuideCar_SiteRepository();
        /// <summary>
        /// 车辆颜色
        /// </summary>
        private readonly RB_GuideCar_CarColorRepository guideCar_CarColorRepository = new RB_GuideCar_CarColorRepository();
        /// <summary>
        /// 快递配置
        /// </summary>
        private readonly RB_Express_ConfigRepository express_ConfigRepository = new RB_Express_ConfigRepository();

        /// <summary>
        /// 教育订单对应的老师
        /// </summary>
        private readonly RB_Goods_WK_TeacherRepository goodsWKTeacherRepository = new RB_Goods_WK_TeacherRepository();
        /// <summary>
        /// 教育对应的订单课程卡
        /// </summary>
        private readonly Repository.Education.RB_Education_MemberCouponRepository educationMemberCouponRepository = new Repository.Education.RB_Education_MemberCouponRepository();

        /// <summary>
        /// 套餐卡仓储层对象
        /// </summary>
        private readonly RB_Reserve_MemberCouponRepository reserveMemberCouponRepository = new RB_Reserve_MemberCouponRepository();

        /// <summary>
        /// 服务人员仓储层对象
        /// </summary>
        private readonly RB_Reserve_ServicePersonalRepository reserve_ServicePersonalRepository = new RB_Reserve_ServicePersonalRepository();

        /// <summary>
        /// 门店仓储层对象
        /// </summary>
        private readonly RB_StoresRepository storesRepository = new RB_StoresRepository();

        /// <summary>
        ///  不可开发票商品信息记录表  
        ///</summary>
        private readonly RB_Invoice_RecordDetailRepository invoiceRecordDetailRepository = new RB_Invoice_RecordDetailRepository();

        /// <summary>
        ///  不可开发票提现信息记录表  
        ///</summary>
        private readonly RB_Invoice_Online_TradeRepository invoiceOnlineTradeRepository = new RB_Invoice_Online_TradeRepository();

        /// <summary>
        ///  不可开发票提现信息记录表  
        ///</summary>
        private readonly RB_OrderGoods_LogRepository orderGoodsLogRepository = new RB_OrderGoods_LogRepository();
        /// <summary>
        /// 管理端通知
        /// </summary>
        private readonly RB_Message_NoticeRepository message_NoticeRepository = new RB_Message_NoticeRepository();

        /// <summary>
        /// 教育创建人
        /// </summary>
        private readonly Repository.Education.RB_AccountRepository RB_AccountRepository = new Repository.Education.RB_AccountRepository();

        /// <summary>
        /// 教育销售
        /// </summary>
        private readonly Repository.Education.RB_Education_EduSellRepository education_EduSellRepository = new Repository.Education.RB_Education_EduSellRepository();

        /// <summary>
        /// 关联物品仓储层对象
        /// </summary>
        private readonly Repository.Product.RB_Goods_RelevanceRepository goods_RelevanceRepository = new RB_Goods_RelevanceRepository();


        /// <summary>
        /// 关联商品仓储层对象
        /// </summary>
        private readonly Repository.TradePavilion.RB_Custom_FormRepository custom_FormRepository = new Repository.TradePavilion.RB_Custom_FormRepository();


        /// <summary>
        /// 评论标签仓储层对象
        /// </summary>
        private readonly RB_Comment_LabelRepository comment_LabelRepository = new RB_Comment_LabelRepository();

        #region 购物车

        /// <summary>
        /// 获取购物车分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_ShoppingCart_Extend> GetGoodsShoppingCartPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                count = 0;
                return new List<RB_Goods_ShoppingCart_Extend>();
            }
            if (demodel.SmallShopsId == 0)
            {
                demodel.SmallShopsId = umodel.SmallShopId;
            }
            var list = goods_ShoppingCartRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string goodsIds = string.Join(",", list.Select(x => x.GoodsId));
                var speciList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciVList = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_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 categoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                string categoryIds = string.Join(",", categoryList.Select(x => x.CategoryId).Distinct());
                var freeShippingList = freeShippingRepository.GetFreeShippingListByCategoryIds(new RB_FreeShipping_Extend { MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId, CategoryIds = categoryIds });

                //商品关联信息列表
                string relationIds = string.Join(",", list.Where(qitem => qitem.RelationId > 0).Select(qitem => qitem.RelationId));
                List<RB_Goods_Relevance_Extend> goodsRelevanceList = new List<RB_Goods_Relevance_Extend>();
                if (!string.IsNullOrEmpty(relationIds))
                {
                    goodsRelevanceList = goods_RelevanceRepository.GetGoodsRelevanceListRepository(new RB_Goods_Relevance_Extend() { QRelevanceIds = relationIds });
                }

                #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
                #region 课程购买
                List<RB_Goods_Order_Extend> CourseOrderList = new List<RB_Goods_Order_Extend>();
                if (demodel.GoodsClassify == 2)
                {
                    CourseOrderList = goods_OrderRepository.GetCourseOrderIsPay(GoodsIds: goodsIds, UserId: demodel.UserId ?? 0);
                }
                #endregion
                foreach (var item in list)
                {
                    item.EduData = goodsRepository.ParsingEduJsonRepository(item.EduJsonData);
                    item.GoodsRelevanceList = goodsRelevanceList?.Where(qitem => qitem.RelevanceId == item.RelationId)?.ToList() ?? new List<RB_Goods_Relevance_Extend>();
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                    //验证规格是否已失效
                    if (item.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            item.GoodsStatus = 3;
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            item.GoodsStatus = 3;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            item.GoodsStatus = 3;
                        }
                    }
                    //验证课程是否已下单
                    if (demodel.GoodsClassify == 2)
                    {
                        var coModel = CourseOrderList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                        if (coModel != null)
                        {
                            item.GoodsStatus = 3;
                        }
                    }
                    //规格赋值
                    item.SpecificationList = new List<string>();
                    if (item.GoodsStatus != 3)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            item.SpecificationList.Add("规格:" + item.DefaultSpecificationName);
                            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)
                                        {
                                            item.Price += Math.Ceiling(item.Price * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            item.Price += (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                item.Price += Math.Ceiling(item.Price * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                item.Price += (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            var KeyArr = item.SpecificationSort.Split(':');
                            for (var i = 0; i < KeyArr.Length; i++)
                            {
                                if (!string.IsNullOrEmpty(KeyArr[i]))
                                {
                                    var sModel = speciList.Where(x => x.GoodsId == item.GoodsId).ToList()[i];
                                    var svModel = speciVList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationId == sModel.Id && x.Sort == Convert.ToInt32(KeyArr[i])).FirstOrDefault();
                                    if (sModel != null && svModel != null)
                                    {
                                        item.SpecificationList.Add(sModel.Name + ":" + svModel.Name);
                                        if (i == 0 && !string.IsNullOrEmpty(svModel.Image))
                                        {
                                            item.CoverImage = svModel.Image;
                                        }
                                    }
                                }
                            }
                            var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                            item.Price = speciPModel?.SellingPrice ?? 0;
                            item.InventoryNum = speciPModel?.InventoryNum ?? 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)
                                        {
                                            item.Price += Math.Ceiling(item.Price * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            item.Price += (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                item.Price += Math.Ceiling(item.Price * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                item.Price += (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //会员价格
                        if (umodel.MemberGrade > 0)
                        {
                            if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                            {
                                item.Price = 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)
                                            {
                                                item.Price += Math.Ceiling(item.Price * (sspModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (sspModel.PriceType == 2)
                                            {
                                                item.Price += (sspModel.UpPrice ?? 0);
                                            }
                                        }
                                        else
                                        {
                                            if ((smallModel.UpPrice ?? 0) > 0)
                                            {
                                                if (smallModel.PriceType == 1)
                                                {
                                                    item.Price += Math.Ceiling(item.Price * (smallModel.UpPrice ?? 0) / 100);
                                                }
                                                else if (smallModel.PriceType == 2)
                                                {
                                                    item.Price += (smallModel.UpPrice ?? 0);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //求会员等级折扣
                                var gradeModel = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { Grade = umodel.MemberGrade, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                                item.Price = Math.Round(item.Price * (gradeModel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                    }

                    if (freeShippingList != null && freeShippingList.Any() && ((item.FullNumPinkage ?? 0) == 0) && ((item.FullMoneyPinkage ?? 0) == 0))
                    {
                        var nowcategory = categoryList.Where(x => x.GoodsId == item.GoodsId).Select(x => x.CategoryId);

                        var fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                        {
                            fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        }
                        if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                        {
                            fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        }
                        if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                        {
                            fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        }
                        item.FreeShippingModel = (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0) ? new RB_FreeShipping_Extend() : fullNumPinkageModel;
                    }
                    else
                    {
                        item.FreeShippingModel = new RB_FreeShipping_Extend();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult SetGoodsShoppingCartGetInfo(RB_Goods_ShoppingCart_Extend demodel)
        {
            bool flag;
            var gmodel = goodsRepository.GetEntity(demodel.GoodsId);
            if (gmodel.IsCustomSpecification == 1)
            {
                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.GoodsId, SpecificationSort = demodel.SpecificationSort, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                if (!speciPList.Any())
                {
                    return ApiResult.ParamIsNull("商品规格不正确");
                }
            }
            else
            {
                if (demodel.SpecificationSort != "")
                {
                    return ApiResult.ParamIsNull("商品规格不正确");
                }
            }

            var scList = goods_ShoppingCartRepository.GetList(new RB_Goods_ShoppingCart_Extend() { GoodsId = demodel.GoodsId, UserId = demodel.UserId, SpecificationSort = demodel.SpecificationSort, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            if (scList.Any())
            {
                //更新数量
                var scModel = scList.FirstOrDefault();
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {

                    { nameof(RB_Goods_ShoppingCart.UpdateDate),DateTime.Now},
                    { nameof(RB_Goods_ShoppingCart.RelationId),demodel.RelationId},
                };
                if (demodel.TenantId != 27)
                {
                    keyValues.Add(nameof(RB_Goods_ShoppingCart.Number), scModel.Number + demodel.Number);
                }
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                         FiledName=nameof(RB_Goods_ShoppingCart.Id),
                         FiledValue=scModel.Id,
                         OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = goods_ShoppingCartRepository.Update(keyValues, wheres);
            }
            else
            {
                flag = goods_ShoppingCartRepository.Insert(new RB_Goods_ShoppingCart()
                {
                    Id = 0,
                    MallBaseId = demodel.MallBaseId,
                    CreateDate = DateTime.Now,
                    GoodsId = demodel.GoodsId,
                    Number = demodel.Number,
                    SpecificationSort = demodel.SpecificationSort,
                    Status = 0,
                    TenantId = demodel.TenantId,
                    UpdateDate = DateTime.Now,
                    UserId = demodel.UserId,
                    RelationId = demodel.RelationId,
                }) > 0;
            }
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置购物车数量
        /// </summary>
        /// <param name="shoppingCartId"></param>
        /// <param name="number"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetGoodsShoppingCartNumGetInfo(int shoppingCartId, int number, int tenantId, int mallBaseId)
        {
            //更新数量            
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_ShoppingCart.Number),number}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_ShoppingCart.Id),
                        FiledValue=shoppingCartId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_ShoppingCart.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_ShoppingCart.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goods_ShoppingCartRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <param name="shoppingCartIds"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelGoodsShoppingCartInfo(string shoppingCartIds, int userId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_ShoppingCart.Status),1},
                { nameof(RB_Goods_ShoppingCart.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_ShoppingCart.Id),
                        FiledValue=shoppingCartIds,
                        OperatorEnum=OperatorEnum.IN
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_ShoppingCart.UserId),
                        FiledValue=userId,
                        OperatorEnum=OperatorEnum.IN
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_ShoppingCart.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_ShoppingCart.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goods_ShoppingCartRepository.Update(keyValues, wheres);
        }

        #endregion

        #region 小程序

        /// <summary>
        /// 小程序我的订单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Order_Extend> GetAppletGoodsMyOrderPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetOrderPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                }
                string areaIds1 = string.Join(",", list.Select(x => x.Province ?? 0).Distinct());
                string areaIds2 = string.Join(",", list.Select(x => x.City ?? 0).Distinct());
                string areaIds3 = string.Join(",", list.Select(x => x.District ?? 0).Distinct());
                string areaIds = "0";
                if (!string.IsNullOrEmpty(areaIds1))
                {
                    areaIds += "," + areaIds1;
                }
                if (!string.IsNullOrEmpty(areaIds2))
                {
                    areaIds += "," + areaIds2;
                }
                if (!string.IsNullOrEmpty(areaIds3))
                {
                    areaIds += "," + areaIds3;
                }
                var arealist = destinationRepository.GetDictvalueListForIds(areaIds);
                foreach (var item in list)
                {

                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                    if (item.DetailList.Where(x => x.PresentFXGrade > 0).Any())
                    {
                        item.PresentFXGrade = 1;
                    }
                    item.DistrictAddress = (arealist.Where(x => x.ID == item.Province).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.City).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.District).FirstOrDefault()?.Name ?? "");

                    if (item.MallBaseId == 19)
                    {
                        //620  20元的运费以及其他费用，商品总价600,2个商品，1-全款，1-订金60%；300*(1-(60/100))=120;
                        //620-120-0=500
                        decimal payIncome = (item.Income.Value) - (item?.PayIncome ?? 0);//实际应付金额-已支付金额

                        if ((item?.PayIncome ?? 0) == 0)//支付定金金额
                        {
                            decimal depositMoney = Math.Round(item.DetailList.Where(x => x.DepositRatio > 0).Sum(x => (1 - (x.DepositRatio / 100)) * (x.Final_Price ?? 0)), 2);
                            payIncome = payIncome - depositMoney;//最终应付金额-定金-退款
                        }
                        item.GoodsDepositMoney = Math.Round(item.DetailList.Where(x => x.DepositRatio > 0).Sum(x => ((x.DepositRatio / 100)) * (x.Final_Price ?? 0)), 2);
                        item.ResultPayMoney = payIncome;
                    }
                    else
                    {
                        item.ResultPayMoney = item.Income ?? 0;
                    }

                }
            }
            return list;
        }

        /// <summary>
        /// 获取我的订单数量统计
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletGoodsOrderNumStatistics(int userId, int tenantId, int mallBaseId)
        {
            //订单状态
            List<RB_Goods_Order_Extend> olist = goods_OrderRepository.GetAppletGoodsOrderNumStatistics(userId, tenantId, mallBaseId);
            //待评价
            int WaitCommentNum = goods_OrderRepository.GetAppletGoodsOrderWaitCommentNum(userId, tenantId, mallBaseId);
            //售后处理中
            int AfterSaleNum = goods_OrderRepository.GetAppletGoodsOrderAfterSaleNum(userId, tenantId, mallBaseId);

            return ApiResult.Success("", new
            {
                NonPayment = olist.Where(x => x.OrderStatus == OrderStatusEnum.NonPayment).FirstOrDefault()?.OrderNum ?? 0,
                WaitSendGoods = olist.Where(x => x.OrderStatus == OrderStatusEnum.WaitSendGoods).FirstOrDefault()?.OrderNum ?? 0,
                WaitReceiving = olist.Where(x => x.OrderStatus == OrderStatusEnum.WaitReceiving).FirstOrDefault()?.OrderNum ?? 0,
                WaitCommentNum,
                AfterSaleNum
            });
        }

        /// <summary>
        /// 获取我的订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletMyOrderInfo(int orderId, int userId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null || model.UserId != userId)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }
            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            var goodsRelevanceList = new List<RB_Goods_Relevance_Extend>();
            if (dlist.Any())
            {
                string orderDetailIds = string.Join(",", dlist.Select(x => x.Id));
                string goodIds = string.Join(",", dlist.Select(qitem => qitem.GoodsId));
                goodsRelevanceList = goods_RelevanceRepository.GetGoodsRelevanceListRepository(new RB_Goods_Relevance_Extend() { QGoodsIds = goodIds });
                var oasList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetailIds = orderDetailIds, TenantId = tenantId, MallBaseId = mallBaseId }, false);
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsApplyForAfterSale = 2;
                    if (oasList.Where(x => x.OrderDetialId == item.Id).Any())
                    {
                        item.IsApplyForAfterSale = 1;
                    }
                    if (item.PresentFXGrade > 0)
                    {
                        model.PresentFXGrade = 1;
                    }
                }
                if (model.MallBaseId == 19)
                {
                    //620  20元的运费以及其他费用，商品总价600,2个商品，1-全款，1-订金60%；300*(1-(60/100))=120;
                    //620-120-0=500
                    decimal payIncome = (model.Income.Value) - (model?.PayIncome ?? 0);//实际应付金额-已支付金额
                    if ((model?.PayIncome ?? 0) == 0)//支付定金金额
                    {
                        decimal depositMoney = Math.Round(dlist.Where(x => x.DepositRatio > 0).Sum(x => (1 - (x.DepositRatio / 100)) * (x.Final_Price ?? 0)), 2);
                        payIncome = payIncome - depositMoney;//最终应付金额-定金-退款
                    }
                    model.GoodsDepositMoney = Math.Round(dlist.Where(x => x.DepositRatio > 0).Sum(x => ((x.DepositRatio / 100)) * (x.Final_Price ?? 0)), 2);
                    model.ResultPayMoney = payIncome;
                }
                else
                {
                    model.ResultPayMoney = model.Income ?? 0;
                }
            }
            model.DetailList = dlist;
            //地址
            model.DistrictAddress = (destinationRepository.GetEntity(model.Province)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.City)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.District)?.Name ?? "");
            //物流
            var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });

            //是否可以申请售后
            var mallModel = mallBaseRepository.GetEntity(mallBaseId);
            model.IsCanApplyForAfterSale = 2;
            if (model.OrderStatus == OrderStatusEnum.WaitReceiving)
            {
                model.IsCanApplyForAfterSale = 1;
            }
            else if (model.OrderStatus == OrderStatusEnum.Received || model.OrderStatus == OrderStatusEnum.Completed)
            {
                if (mallModel != null && mallModel.AfterTime > 0 && model.ReceivingTime.HasValue)
                {
                    if (model.ReceivingTime.Value.AddDays(mallModel.AfterTime) > DateTime.Now)
                    {
                        model.IsCanApplyForAfterSale = 1;
                    }
                }
            }

            //获取订阅消息
            var miniModel = miniProgramRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId }).FirstOrDefault();

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.OrderCancelTpl))
                {
                    template_message_list.Add(miniModel.OrderCancelTpl);
                }
            }
            List<object> resultList = new List<object>();
            List<Model.Extend.TradePavilion.FormDataItem> listFormData = new List<Model.Extend.TradePavilion.FormDataItem>();
            foreach (var item in model.DetailList)
            {
                var EduData = goodsRepository.ParsingEduJsonRepository(item.EduJsonData);
                var tempList = goodsRelevanceList?.Where(qitem => qitem.GoodsId == item.GoodsId)?.ToList();
                if (!string.IsNullOrWhiteSpace(item.CustomFormInfo) && listFormData?.Count == 0)
                {
                    listFormData = AnalyzeFormComponent(item.CustomFormInfo, isGetAnswer: true);
                }

                resultList.Add(new
                {
                    DetailId = item.Id,
                    item.GoodsId,
                    item.GoodsName,
                    item.CoverImagePath,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(item.Specification),
                    item.Number,
                    item.Final_Price,
                    item.IsComment,
                    item.IsApplyForAfterSale,
                    item.FreeShippingRemarks,
                    EduData,
                    GoodsRelevanceList = tempList,
                    item.IntegralMoney
                });
            }
            decimal IntegralMoney = model.DetailList?.Sum(x => x.IntegralMoney ?? 0) ?? 0;
            return ApiResult.Success("", new
            {
                template_message_list,
                model.OrderId,
                CustomFormInfo = listFormData,
                model.OrderNo,
                model.OrderStatus,
                model.VersionSource,
                OrderStatusName = model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.PaymentWay,
                PaymentWayName = model.PaymentWay.GetEnumName(),
                model.DeliveryMethod,
                DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                PreferPrice = (model.PreferPrice ?? 0) + IntegralMoney,
                model.Income,
                PayIncome = model.PayIncome ?? 0,
                model.ResultPayMoney,
                model.GoodsDepositMoney,
                model.CouponMoney,
                model.FreightMoney,
                model.DepositId,
                model.DepositMoney,
                model.Consignee,
                model.Mobile,
                model.DistrictAddress,
                model.ShoppingAddress,
                DeductionCommission = model.DeductionCommission ?? 0,
                IsHaveExpress = erlist.Any() ? 1 : 2,
                DetailList = resultList,
                model.IsApplyForCancel,
                model.RejectRemark,
                model.IsCanApplyForAfterSale,
                model.PresentFXGrade,
                model.BuyerMessage,
                model.OrderEduType,
                IntegralMoney
            });
        }

        /// <summary>
        /// 获取线下服务我的订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetOfflineMyOrderModule(int orderId, int userId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null || model.UserId != userId)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }
            //门店实体信息
            var storeModel = new RB_Stores();
            if (model.StoresId > 0)
            {
                storeModel = storesRepository.GetEntity(model.StoresId);
            }
            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (dlist.Any())
            {
                string orderDetailIds = string.Join(",", dlist.Select(x => x.Id));
                var oasList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetailIds = orderDetailIds, TenantId = tenantId, MallBaseId = mallBaseId }, false);
                string servicePersions = string.Join(",", dlist.Select(x => x.ServicepersonalId));
                var serviceList = reserve_ServicePersonalRepository.GetServicePersonalList(new Model.Extend.Reserve.RB_Reserve_ServicePersonal_Extend()
                {
                    QIds = servicePersions
                });
                List<RB_Reserve_MemberCoupon_Extend> educationCouponList = new List<RB_Reserve_MemberCoupon_Extend>();
                //查询订单详情对应的课程卡信息
                string educationCouponIds = string.Join(",", dlist.Where(x => x.EducationCouponId > 0).Select(x => x.EducationCouponId).Distinct());
                if (!string.IsNullOrWhiteSpace(educationCouponIds))
                {
                    educationCouponList = reserveMemberCouponRepository.GetList(new RB_Reserve_MemberCoupon_Extend { TenantId = tenantId, MallBaseId = mallBaseId, Ids = educationCouponIds });
                }
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsApplyForAfterSale = 2;
                    if (oasList.Where(x => x.OrderDetialId == item.Id).Any())
                    {
                        item.IsApplyForAfterSale = 1;
                    }
                    if (item.PresentFXGrade > 0)
                    {
                        model.PresentFXGrade = 1;
                    }
                    item.ServicepersonalName = serviceList?.Where(qitem => qitem.ID == item.ServicepersonalId)?.FirstOrDefault()?.Name ?? "";
                    item.ReserveCouponList = educationCouponList.Where(x => x.Id == item.EducationCouponId).ToList();// 2020-10-11 订单详情对应的套餐卡
                }
            }
            model.DetailList = dlist;

            //是否可以申请售后
            var mallModel = mallBaseRepository.GetEntity(mallBaseId);
            model.IsCanApplyForAfterSale = 2;
            if (model.OrderStatus == OrderStatusEnum.WaitReceiving)
            {
                model.IsCanApplyForAfterSale = 1;
            }
            else if (model.OrderStatus == OrderStatusEnum.Received || model.OrderStatus == OrderStatusEnum.Completed)
            {
                if (mallModel != null && mallModel.AfterTime > 0 && model.ReceivingTime.HasValue)
                {
                    if (model.ReceivingTime.Value.AddDays(mallModel.AfterTime) > DateTime.Now)
                    {
                        model.IsCanApplyForAfterSale = 1;
                    }
                }
            }

            //获取订阅消息
            var miniModel = miniProgramRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId }).FirstOrDefault();
            List<string> template_message_list = new List<string>();
            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.OrderCancelTpl))
                {
                    template_message_list.Add(miniModel.OrderCancelTpl);
                }
            }

            return ApiResult.Success("", new
            {
                template_message_list,
                model.OrderId,
                model.OrderNo,
                model.OrderStatus,
                OrderStatusName = model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.PaymentWay,
                PaymentWayName = model.PaymentWay.GetEnumName(),
                model.PreferPrice,
                model.Income,
                model.CouponMoney,
                EducationMoney = (model?.EducationMoney ?? 0),
                model.Consignee,
                model.Mobile,
                model.ShoppingAddress,
                DetailList = model.DetailList.Select(x => new
                {
                    DetailId = x.Id,
                    x.GoodsId,
                    x.GoodsName,
                    x.CoverImagePath,
                    x.Number,
                    x.Final_Price,
                    x.IsComment,
                    x.IsApplyForAfterSale,
                    x.FreeShippingRemarks,
                    x.ServiceDate,
                    x.ServiceTime,
                    x.GoodServiceTime,
                    x.ServicepersonalName,
                    MemberEducationCouponList = x?.ReserveCouponList.Select(z => new
                    {
                        z.Name,
                        z.UseHeXiao,
                        z.HeXiao
                    }),
                }),
                model.IsApplyForCancel,
                model.RejectRemark,
                model.IsCanApplyForAfterSale,
                model.PresentFXGrade,
                model.BuyerMessage,
                model.Remark,
                model.CancelRemark,
                storeName = storeModel?.Name,
                storeAddress = storeModel?.Address
            });
        }

        /// <summary>
        /// 获取我的订单快递信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetAppletMyOrderExpressInfo(int orderId, int tenantId, int mallBaseId)
        {
            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (dlist.Any())
            {
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                }
            }
            //物流
            var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            List<RB_Goods_OrderExpress_Extend> oeList = new List<RB_Goods_OrderExpress_Extend>();
            if (erlist.Any())
            {
                oeList = goods_OrderExpressRepository.GetList(new RB_Goods_OrderExpress_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderExpressIds = string.Join(",", erlist.Select(x => x.OrderExpressId)) });
                foreach (var item in oeList)
                {
                    if (item.Type == 1)
                    {
                        item.ExpressName = logistics_ExpressRepository.GetEntity(item.ExpressId)?.Name ?? "";
                    }
                    else
                    {
                        item.ExpressName = item.Remark;
                    }
                }
            }
            return oeList.Select(x => new
            {
                x.Id,
                x.ExpressId,
                x.ExpressName,
                x.ExpressNumber,
                x.PostCode,
                x.Remark,
                x.Type,
                GoodsList = GetGoodsListForExpress(dlist, erlist, x.Id).Select(z => new
                {
                    z.Id,
                    z.CoverImagePath,
                    z.GoodsName
                })
            });
        }

        /// <summary>
        /// 获取售后页面
        /// </summary>
        /// <param name="orderDetailId"></param>
        /// <returns></returns>
        public ApiResult GetAppletMyOrderAfterSaleInfo(int orderDetailId)
        {
            var dModel = goods_OrderDetailRepository.GetEntity<RB_Goods_OrderDetail_Extend>(orderDetailId);
            if (dModel == null)
            {
                return ApiResult.Failed("未查询到订单商品信息");
            }
            dModel.CoverImagePath = dModel.CoverImage;
            var omodel = goods_OrderRepository.GetEntity(dModel.OrderId);
            if (omodel == null)
            {
                return ApiResult.Failed("未查询到订单信息");
            }
            decimal Final_Price = (dModel.Final_Price ?? 0) - dModel.DepositMoney;
            decimal PayIncome = Final_Price;
            if (omodel.TenantId == 29)
            {//620    已支付300+20+180=500;
                if (omodel.PayIncome < omodel.Income)//支付的订金
                {

                    PayIncome = (dModel.Final_Price ?? 0) - ((dModel.Final_Price ?? 0) * (1 - (dModel.DepositRatio / 100)));
                }
            }
            else
            {
                if (omodel.Income < Final_Price)
                {
                    Final_Price = omodel.Income ?? 0;
                }
            }

            //获取订阅消息
            var miniModel = miniProgramRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId }).FirstOrDefault();

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.AuditResultTpl))
                {
                    template_message_list.Add(miniModel.AuditResultTpl);
                }
            }

            return ApiResult.Success("", new
            {
                template_message_list,
                DetailId = dModel.Id,
                dModel.CoverImagePath,
                dModel.GoodsId,
                dModel.GoodsName,
                SpecificationList = JsonConvert.DeserializeObject<List<string>>(dModel.Specification),
                dModel.Number,
                Final_Price,
                PayIncome,
                dModel.FreightMoney
            });
        }



        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Online_Trade_Extend> GetGoodsOnlineTradeList(RB_Goods_Online_Trade_Extend dmodel)
        {
            return goods_Online_TradeRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取小程序结算页面详情
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult GetAppletGoodsSettlementInfo(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            //获取用户的默认收货地址
            var defModel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { UserId = demodel.UserId, IsDefault = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            List<int> disList = new List<int>();
            if (defModel == null)
            {
                defModel = new RB_Member_ShippingAddress_Extend();
            }
            else
            {
                string areaIds = (defModel.Province ?? 0) + "," + (defModel.City ?? 0) + "," + (defModel.District ?? 0);
                var arealist = destinationRepository.GetDictvalueListForIds(areaIds);
                defModel.DistrictAddress = (arealist.Where(x => x.ID == defModel.Province).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == defModel.City).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == defModel.District).FirstOrDefault()?.Name ?? "");

                disList.Add(defModel.Province ?? 0);
                disList.Add(defModel.City ?? 0);
                disList.Add(defModel.District ?? 0);
            }
            List<object> DList = new List<object>();
            decimal TotalExpress = 0;
            int DefFreightId = 0;
            if (demodel.DetailList.Any())
            {
                string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var speciList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciVList = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_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 });
                List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend> rulesList = new List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend> regionList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend>();
                if (gList.Any() && defModel.Id > 0)
                {
                    List<int> FreightIdList = new List<int>();
                    if (gList.Where(x => x.FreightId > 0).Any())
                    {
                        FreightIdList.AddRange(gList.Where(x => x.FreightId > 0).Select(x => x.FreightId ?? 0).ToList());
                    }
                    if (gList.Where(x => x.FreightId == 0).Any())
                    {
                        //查询默认
                        DefFreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault()?.ID ?? 0;
                        FreightIdList.Add(DefFreightId);
                    }

                    if (FreightIdList.Any())
                    {
                        rulesList = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { RulesIds = string.Join(",", FreightIdList), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        priceList = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, RulesIds = string.Join(",", FreightIdList) });
                        if (priceList.Any())
                        {
                            string priceIds = string.Join(",", priceList.Select(x => x.ID));
                            regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, PriceIds = priceIds });
                        }
                    }

                }
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    var categoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    gmodel.CoverImage = "";
                    if (!string.IsNullOrEmpty(gmodel.CarouselImage) && gmodel.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(gmodel.CarouselImage);
                        //封面图
                        gmodel.CoverImage = CarouselIdList[0];
                    }
                    int GoodsWeight = gmodel.GoodsWeight ?? 0;//商品重量
                    #region 规格
                    //验证规格是否已失效
                    if (gmodel.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                    }

                    //规格赋值
                    gmodel.SpecificationNameList = new List<string>();

                    if (string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        gmodel.SpecificationNameList.Add("规格:" + gmodel.DefaultSpecificationName);
                        if (item.Number > gmodel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    else
                    {
                        var KeyArr = item.SpecificationSort.Split(':');
                        for (var i = 0; i < KeyArr.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(KeyArr[i]))
                            {
                                var sModel = speciList.Where(x => x.GoodsId == item.GoodsId).ToList()[i];
                                var svModel = speciVList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationId == sModel.Id && x.Sort == Convert.ToInt32(KeyArr[i])).FirstOrDefault();
                                gmodel.SpecificationNameList.Add(sModel.Name + ":" + svModel.Name);
                            }
                        }
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        gmodel.SellingPrice = speciPModel?.SellingPrice ?? 0;
                        gmodel.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        GoodsWeight = speciPModel?.GoodsWeight ?? 0;
                        if (item.Number > speciPModel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    #endregion
                    //会员价格
                    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;
                        }
                        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);
                        }
                    }
                    //运费
                    decimal Express = 0;
                    if (defModel.Id > 0)
                    {
                        int FreightId2 = gmodel.FreightId ?? 0;
                        if (gmodel.FreightId == 0)
                        {
                            FreightId2 = DefFreightId;
                        }
                        if (FreightId2 > 0)
                        {
                            var rulesModel = rulesList.Where(x => x.ID == FreightId2).FirstOrDefault();
                            List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList2 = priceList.Where(x => x.RulesId == FreightId2).ToList();
                            if (priceList2.Any())
                            {
                                var priceIds = priceList2.Select(x => x.ID).ToList();
                                var regionList2 = regionList.Where(x => priceIds.Contains(x.RulesPriceId)).ToList();

                                var regionModel = regionList2.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                                if (regionModel != null)
                                {
                                    var pmodel = priceList2.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                                    if (pmodel != null && rulesModel != null)
                                    {
                                        if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                        {
                                            //按件计费
                                            if (item.Number <= pmodel.First)
                                            {
                                                Express = pmodel.FirstPrice;
                                            }
                                            else
                                            {
                                                if (pmodel.Second > 0)
                                                {
                                                    if (((item.Number ?? 0) - pmodel.First) % pmodel.Second == 0)
                                                    {
                                                        Express = pmodel.FirstPrice + (((item.Number ?? 0) - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                    }
                                                    else
                                                    {
                                                        Express = pmodel.FirstPrice + (((item.Number ?? 0) - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                    }
                                                }
                                                else
                                                {
                                                    Express = pmodel.FirstPrice;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //重量计费
                                            int TotalW = (item.Number ?? 0) * GoodsWeight;
                                            if (TotalW <= pmodel.First)
                                            {
                                                Express = pmodel.FirstPrice;
                                            }
                                            else
                                            {
                                                if (pmodel.Second > 0)
                                                {
                                                    if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                                    {
                                                        Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                    }
                                                    else
                                                    {
                                                        Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                    }
                                                }
                                                else
                                                {
                                                    Express = pmodel.FirstPrice;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    DList.Add(new
                    {
                        item.GoodsId,
                        GoodsName = gmodel.Name,
                        gmodel.CoverImage,
                        CategoryList = categoryList.Select(x => new
                        {
                            x.Id,
                            x.CategoryName
                        }),
                        SpecificationList = gmodel.SpecificationNameList,
                        item.SpecificationSort,
                        item.Number,
                        SellingPrice = (gmodel.SellingPrice ?? 0) * (item.Number ?? 0),
                        MemberPrice = gmodel.MemberPrice * (item.Number ?? 0),
                        MemberDiscount = gmodel.MemberPrice * (item.Number ?? 0) - (gmodel.SellingPrice ?? 0) * (item.Number ?? 0),
                        Express
                    });
                    TotalExpress += Express;
                }
            }
            return ApiResult.Success("", new
            {
                ShippingAddressModel = new
                {
                    defModel.Id,
                    defModel.Name,
                    defModel.Mobile,
                    defModel.DistrictAddress,
                    defModel.Address,
                    defModel.Province,
                    defModel.City,
                    defModel.District
                },
                DetailList = DList,
                TotalExpress,
                umodel.MemberGrade,
                DeliveryMethod = (int)OrderDeliveryMethodEnum.ExpressDistribution,
                Level_Show = umodel.MemberGrade > 0 ? 1 : 2
            });
        }



        #region 自定义表单解析
        /// <summary>
        /// 解析表单组件
        /// </summary>
        /// <param name="formData"></param>
        /// <param name="isGetAnswer"></param>
        /// <returns></returns>
        public List<Model.Extend.TradePavilion.FormDataItem> AnalyzeFormComponent(string formData, bool isGetAnswer = false)
        {
            List<Model.Extend.TradePavilion.FormDataItem> dataList = new List<Model.Extend.TradePavilion.FormDataItem>();
            if (!string.IsNullOrEmpty(formData))
            {
                JArray jArray = JArray.Parse(formData);
                if (jArray != null && jArray.Count > 0)
                {
                    foreach (var jItem in jArray)
                    {
                        JObject jObj = JObject.Parse(jItem.ToString());
                        Model.Extend.TradePavilion.FormDataItem dataItem = new Model.Extend.TradePavilion.FormDataItem()
                        {
                            CompKey = jObj.GetStringValue("CompKey"),
                            CompData = new object(),
                            isCked = false,
                        };
                        if (!string.IsNullOrEmpty(dataItem.CompKey))
                        {
                            string compData = jObj.GetStringValue("CompData");
                            switch (dataItem.CompKey)
                            {
                                //单行文本
                                case "SingleLineText":
                                    Model.Extend.TradePavilion.TextItem txtItem = GetTextItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        txtItem.TextValue = "";
                                    }
                                    dataItem.CompData = txtItem;
                                    break;
                                //多行文本
                                case "MultiLineText":
                                    Model.Extend.TradePavilion.TextItem multiItem = GetTextItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        multiItem.TextValue = "";
                                    }
                                    dataItem.CompData = multiItem;
                                    break;
                                //下拉框
                                case "DorpDownList":
                                    Model.Extend.TradePavilion.SelectItem selectItem = GetSelectItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        selectItem.OptionValue = "";
                                    }
                                    dataItem.CompData = selectItem;
                                    break;
                                //图片上传组件
                                case "ImageUploadComp":
                                    Model.Extend.TradePavilion.UploadItem imgItem = GetUploadItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        imgItem.FileList = new List<string>();
                                    }
                                    dataItem.CompData = imgItem;
                                    break;
                                //视频上传组件
                                case "VideoUploadComp":
                                    Model.Extend.TradePavilion.UploadItem videoItem = GetUploadItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        videoItem.FileList = new List<string>();
                                    }
                                    dataItem.CompData = videoItem;
                                    break;
                                //通用上传组件
                                case "CommonUploadComp":
                                    Model.Extend.TradePavilion.UploadItem commonUpload = GetUploadItem(compData);
                                    if (!isGetAnswer)
                                    {
                                        commonUpload.FileList = new List<string>();
                                    }
                                    dataItem.CompData = commonUpload;
                                    break;
                            }
                            dataList.Add(dataItem);
                        }
                    }
                }
            }
            return dataList;
        }

        /// <summary>
        /// 获取文本框信息
        /// </summary>
        /// <param name="CompData"></param>
        /// <returns></returns>
        private Model.Extend.TradePavilion.TextItem GetTextItem(string CompData)
        {
            JObject textObj = JObject.Parse(CompData);
            Model.Extend.TradePavilion.TextItem txtItem = new Model.Extend.TradePavilion.TextItem()
            {
                Name = textObj.GetStringValue("Name"),
                WordsLength = textObj.GetInt("WordsLength"),
                IsRequire = textObj.GetBoolValue("IsRequire"),
                Remark = textObj.GetStringValue("Remark"),
                TextValue = textObj.GetStringValue("TextValue"),
            };
            return txtItem;
        }

        /// <summary>
        /// 获取下拉框信息
        /// </summary>
        /// <param name="CompData"></param>
        /// <returns></returns>
        private Model.Extend.TradePavilion.SelectItem GetSelectItem(string CompData)
        {
            JObject dropdownObj = JObject.Parse(CompData);
            Model.Extend.TradePavilion.SelectItem selectItem = new Model.Extend.TradePavilion.SelectItem()
            {
                Name = dropdownObj.GetStringValue("Name"),
                IsMultiple = dropdownObj.GetBoolValue("IsMultiple"),
                IsRequire = dropdownObj.GetBoolValue("IsRequire"),
                OptionList = new List<Model.Extend.TradePavilion.SelectOption>(),
                Remark = dropdownObj.GetStringValue("Remark"),
            };
            if (selectItem.IsMultiple)
            {
                List<int> valueList = Common.ConvertHelper.StringToList(dropdownObj.GetStringValue("OptionValue").Split(','));
                if (valueList != null && valueList.Count > 0)
                {
                    selectItem.OptionValue = string.Join(",", valueList);
                }
            }
            else
            {
                selectItem.OptionValue = dropdownObj.GetStringValue("OptionValue");
            }
            var optionList = JArray.Parse(dropdownObj.GetStringValue("OptionList"));
            if (optionList != null && optionList.Count > 0)
            {
                foreach (var oItem in optionList)
                {
                    JObject optionObj = JObject.Parse(oItem.ToString());
                    Model.Extend.TradePavilion.SelectOption option = new Model.Extend.TradePavilion.SelectOption()
                    {
                        Id = optionObj.GetInt("Id"),
                        Name = optionObj.GetStringValue("Name"),
                    };
                    selectItem.OptionList.Add(option);
                }
            }
            return selectItem;
        }

        /// <summary>
        /// 获取上传配置信息
        /// </summary>
        /// <param name="CompData"></param>
        /// <returns></returns>
        private Model.Extend.TradePavilion.UploadItem GetUploadItem(string CompData)
        {
            JObject uploadObj = JObject.Parse(CompData);
            Model.Extend.TradePavilion.UploadItem uploadItem = new Model.Extend.TradePavilion.UploadItem()
            {
                Name = uploadObj.GetStringValue("Name"),
                FileCount = uploadObj.GetInt("FileCount"),
                FileType = uploadObj.GetStringValue("FileType"),
                FileSizeLimit = uploadObj.GetInt("FileSizeLimit"),
                Remark = uploadObj.GetStringValue("Remark"),
                FileList = new List<string>(),
            };
            if (!string.IsNullOrEmpty(uploadObj.GetStringValue("FileList")))
            {
                try
                {
                    uploadItem.FileList = JsonHelper.DeserializeObject<List<string>>(uploadObj.GetStringValue("FileList"));
                }
                catch
                {

                }
            }
            return uploadItem;
        }
        #endregion

        /// <summary>
        /// 获取小程序结算页面详情
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult GetAppletGoodsSettlementInfoForZY(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.CustomerChildrenId > 0) {
                //绑定erp同业积分
                var cmodel = customer_IntegralRepository.GetCustomerInfo(umodel.CustomerChildrenId);
                if (cmodel != null && cmodel.IntegralUse != 2) {
                    decimal intergralNum = customer_IntegralRepository.GetCustomerIntegralSurplus(umodel.CustomerId, cmodel.IntegralUse == 0 ? umodel.CustomerChildrenId : 0);
                    umodel.Integral = Convert.ToInt32(intergralNum);
                }
            }

            //积分
            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();
            }

            #region 快递列表
            var mallbaseModel = mallBaseRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_MallBase_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            var Delivery = new object();
            if (!string.IsNullOrEmpty(mallbaseModel?.DeliverWay))
            {
                var DelivertList = EnumHelper.GetEnumList(typeof(OrderDeliveryMethodEnum));
                string[] arr = mallbaseModel?.DeliverWay.Split(',');
                var send_type_list = new List<object>();
                foreach (var item in arr)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        var delmodel = DelivertList.Where(x => x.Value == item).FirstOrDefault();
                        send_type_list.Add(new
                        {
                            name = delmodel.Key,
                            value = delmodel.Value
                        });
                    }
                }
                if (arr.Any() && demodel.DeliveryMethod == 0)
                {//设置默认发货方式
                    var delmodel = DelivertList.Where(x => x.Value == arr[0]).FirstOrDefault();
                    demodel.DeliveryMethod = (OrderDeliveryMethodEnum)Convert.ToInt32(delmodel.Value);
                }
                Delivery = new
                {
                    send_type = demodel.DeliveryMethod,
                    disabled = false,
                    send_type_list
                };
            }
            #endregion

            //获取用户的默认收货地址
            RB_Member_ShippingAddress_Extend defModel;
            if (demodel.AddressId > 0)
            {
                defModel = member_ShippingAddressRepository.GetEntity<RB_Member_ShippingAddress_Extend>(demodel.AddressId);
            }
            else
            {
                defModel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { UserId = demodel.UserId, IsDefault = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            }
            defModel ??= new RB_Member_ShippingAddress_Extend();
            List<int> disList = new List<int>();
            //地址
            if (defModel.Id > 0)
            {
                string areaIds = (defModel.Province ?? 0) + "," + (defModel.City ?? 0) + "," + (defModel.District ?? 0);
                var arealist = destinationRepository.GetDictvalueListForIds(areaIds);

                defModel.PName = (arealist.Where(x => x.ID == defModel.Province).FirstOrDefault()?.Name ?? "");
                defModel.CName = (arealist.Where(x => x.ID == defModel.City).FirstOrDefault()?.Name ?? "");
                defModel.DName = (arealist.Where(x => x.ID == defModel.District).FirstOrDefault()?.Name ?? "");
                defModel.DistrictAddress = defModel.PName + " " + defModel.CName + " " + defModel.DName;

                disList.Add(defModel.Province ?? 0);
                disList.Add(defModel.City ?? 0);
                disList.Add(defModel.District ?? 0);
            }
            List<object> DList = new List<object>();
            decimal TotalExpress = 0, TotalGoodsMoney = 0, TotalGoodsOriginalMoney = 0, TotalGoodsSellMoney = 0, DepositMoney = 0;//总快递费  总商品价格  总原价  总售价   订金金额
            int DefFreightId = 0;
            decimal member_discount = 0;//总会员优惠
            decimal Total_integral_price = 0;//总积分金额
            int Total_use_integral = 0;//总积分
            decimal CouponsMoney = 0;//优惠总金额
            bool IsPointsDeduction = false;//是否有商品可使用积分抵扣
            bool address_enable = true;//地址Ok
            bool IsDepositUse = false;//是否可以使用储值卡
            decimal TotalDepositMoney = 0, OldDepositMoney = 0;//储值卡抵扣金额   原储值卡金额
            List<object> goods_list = new List<object>();
            List<FreeShippingGoodsDetail> SatisfiedGoodsList = new List<FreeShippingGoodsDetail>();//可包邮的商品
            #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;
                }
            }

            bool IsDeductionCommission = false;//是否抵扣佣金
            decimal TotalDeductionCommission = 0;//粉象购买抵扣佣金
            #endregion
            if (demodel.DetailList.Any())
            {
                string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));

                List<RB_Goods_Preferential_Extend> goodsPreferentialList = new List<RB_Goods_Preferential_Extend>();

                if (!string.IsNullOrWhiteSpace(GoodsIds))
                {
                    goodsPreferentialList = RB_Goods_PreferentialRepository.GetGoodsPreferentialListRepostory(new RB_Goods_Preferential_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, QGoodsIds = GoodsIds });
                }

                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                //HK 2022-10-11新增教育关联商品
                var goodsRelevanceList = goods_RelevanceRepository.GetGoodsRelevanceListRepository(new RB_Goods_Relevance_Extend() { QGoodsIds = GoodsIds });
                var speciList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciVList = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_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 AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                #region 查询外部设置区域限购
                List<int> RAreaList = new List<int>();
                var RulesAreaModel = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { RulesType = Common.Enum.MallBase.RulesTypeEnum.AreaBuy, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                if (RulesAreaModel != null && RulesAreaModel.IsOpenMinPrice == 1)
                {
                    var RegionAreaList = logistics_RulesRegionRepository.GetListForSingle(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { RulesPriceId = RulesAreaModel.ID, RulesType = Common.Enum.MallBase.RulesTypeEnum.AreaBuy, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (RegionAreaList.Any())
                    {
                        //允许以下区域购买
                        RAreaList = RegionAreaList.Select(x => x.RegionId).Distinct().ToList();
                    }
                }

                #endregion
                //返佣
                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 });
                }

                List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend> rulesList = new List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend> regionList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend>();
                List<Model.Extend.TradePavilion.RB_Custom_Form_Extend> customFormList = new List<Model.Extend.TradePavilion.RB_Custom_Form_Extend>();
                if (gList.Any() && defModel.Id > 0)
                {
                    List<int> FreightIdList = new List<int>();
                    if (gList.Where(x => x.FreightId > 0).Any())
                    {
                        FreightIdList.AddRange(gList.Where(x => x.FreightId > 0).Select(x => x.FreightId ?? 0).ToList());
                    }
                    if (gList.Where(x => x.FreightId == 0).Any())
                    {
                        //查询默认
                        DefFreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault()?.ID ?? 0;
                        FreightIdList.Add(DefFreightId);
                    }

                    if (FreightIdList.Any())
                    {
                        rulesList = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { RulesIds = string.Join(",", FreightIdList), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        priceList = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, RulesIds = string.Join(",", FreightIdList) });
                        if (priceList.Any())
                        {
                            string priceIds = string.Join(",", priceList.Select(x => x.ID));
                            regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, PriceIds = priceIds });
                        }
                    }

                }


                #region 获取商品的自定义表单
                if (gList != null && gList.Any())
                {
                    string formsIds = string.Join(",", gList.Where(x => x.FormsId > 1).Select(x => x.FormsId));
                    if (!string.IsNullOrWhiteSpace(formsIds))
                    {
                        customFormList = custom_FormRepository.GetCustomFormByIdsListRepository(new Model.Extend.TradePavilion.RB_Custom_Form_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, formsIds);
                        //   var dataList = AnalyzeFormComponent(customFormModel.FormData, isGetAnswer: false);
                    }
                    else
                    {
                        customFormList = custom_FormRepository.GetCustomFormByIdsListRepository(new Model.Extend.TradePavilion.RB_Custom_Form_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, Config.CustomerFormId);
                    }
                }
                #endregion

                #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
                List<RB_Goods_CouponModel> GoodsCouponList = new List<RB_Goods_CouponModel>();//商品优惠卷 价格（每个商品优惠的价格）
                List<int> YFCategoryList = new List<int>();//全局适配 分类

                #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

                #region 储值卡
                var depositModel = new RB_Member_DepositBuy_Extend();
                if ((mallbaseModel?.DepositFun ?? 0) == 1)
                {
                    //查询是否开启储值卡使用
                    IsDepositUse = true;
                    if (demodel.Use_Deposit_Id > 0)
                    {
                        depositModel = member_DepositBuyRepository.GetEntity<RB_Member_DepositBuy_Extend>(demodel.Use_Deposit_Id);
                        if (depositModel == null || depositModel.Status == 0 || depositModel.SendStatus != 0)
                        {
                            return ApiResult.Failed("储值卡不存在，请核实后再试");
                        }
                        if (depositModel.UserId != umodel.Id)
                        {
                            return ApiResult.Failed("储值卡使用有误，请核实后再试");
                        }
                        if (depositModel.SurplusPrice <= 0)
                        {
                            return ApiResult.Failed("储值卡金额不足，请核实后再试");
                        }
                        OldDepositMoney = depositModel.SurplusPrice;
                    }
                }
                #endregion
                //初始化值
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();

                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    int GoodsWeight = gmodel.GoodsWeight ?? 0;//商品重量
                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();
                    if ((mallbaseModel?.IsFreeShipping ?? 0) == 1 && (gmodel.FullMoneyPinkage ?? 0) == 0 && (gmodel.FullNumPinkage ?? 0) == 0)
                    {
                        YFCategoryList.AddRange(categoryList.Select(x => x.CategoryId ?? 0).ToList());
                    }

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

                    }
                    #endregion

                    #region 规格
                    //验证规格是否已失效
                    if (gmodel.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                    }

                    item.CommissionPrice = gmodel.Commission;
                    //规格赋值
                    //gmodel.SpecificationNameList = new List<string>();
                    item.SpecificationNameList = new List<string>();
                    List<object> attr_list = new List<object>();
                    if (string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        gmodel.SpecificationNameList.Add("规格:" + gmodel.DefaultSpecificationName);
                        if (item.Number > gmodel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                        attr_list = new List<object>(){ new
                        {
                            attr_group_name = "规格",
                            attr_group_id = 0,
                            attr_id = 0,
                            attr_name = gmodel.DefaultSpecificationName
                        } };

                        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);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        var KeyArr = item.SpecificationSort.Split(':');
                        for (var i = 0; i < KeyArr.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(KeyArr[i]))
                            {
                                var sModel = speciList.Where(x => x.GoodsId == item.GoodsId).ToList()[i];
                                var svModel = speciVList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationId == sModel.Id && x.Sort == Convert.ToInt32(KeyArr[i])).FirstOrDefault();
                                if (svModel != null)
                                {
                                    item.SpecificationNameList.Add(sModel.Name + ":" + svModel.Name);
                                    attr_list.Add(new
                                    {
                                        attr_group_name = sModel.Name,
                                        attr_group_id = sModel.Sort,
                                        attr_id = svModel.Id,
                                        attr_name = svModel.Name
                                    });
                                    if (i == 0 && !string.IsNullOrEmpty(svModel.Image))
                                    {
                                        item.CoverImage = svModel.Image;//规格图片赋值
                                    }
                                }
                            }
                        }
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        gmodel.SellingPrice = speciPModel?.SellingPrice ?? 0;
                        gmodel.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        gmodel.GoodsNumbers = speciPModel?.GoodsNumbers ?? "";
                        GoodsWeight = speciPModel?.GoodsWeight ?? 0;
                        if (item.Number > speciPModel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                        item.CommissionPrice = speciPModel?.Commission ?? 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.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;
                    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);

                    item.NorGoodsMoney = item.Final_Price ?? 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 优惠券
                    //decimal CouponsMoney = 0;
                    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

                    //绑定物品价格
                    var tempRelevancePrice = goodsRelevanceList?.Where(qitem => qitem.GoodsId == gmodel.Id)?.Sum(qitem => qitem.RelevancePrice) ?? 0;

                    Total_integral_price += (item.IntegralMoney ?? 0);
                    Total_use_integral += (item.IntegralNumber ?? 0);
                    TotalGoodsMoney += (item.Final_Price ?? 0) + tempRelevancePrice;

                    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.GoodsWeight = GoodsWeight;
                    item.IntegralMoney = integral_price;
                    item.IntegralNumber = use_integral;
                    item.Attr_list = attr_list;
                    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;
                        }
                    }
                }

                #region 处理全局包邮
                List<RB_FreeShipping_Extend> freeShippingList = new List<RB_FreeShipping_Extend>();
                var SatisfiedGoodsListAll = new List<FreeShippingGoodsDetail>();
                if (YFCategoryList.Any())
                {
                    YFCategoryList = YFCategoryList.Distinct().ToList();
                    string categoryIds = string.Join(",", YFCategoryList);
                    freeShippingList = freeShippingRepository.GetFreeShippingListByCategoryIds(new RB_FreeShipping_Extend { MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId, CategoryIds = categoryIds });
                }
                #endregion

                #region 购买抵扣佣金
                if ((disbaseModel?.IsEnableFXGrade ?? 2) == 1)
                {
                    if (((disbaseModel?.IsEnableNoSuperiorFY ?? 1) == 1) || ((disbaseModel?.IsEnableNoSuperiorFY ?? 1) == 2 && (umodel.SuperiorId ?? 0) > 0))
                    {
                        //验证用户必须是分销商 最低普通会员 不是以普通会员处理
                        var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = umodel.Id, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                        if (disModel != null)
                        {
                            if (disModel.FXGradeId > 0)
                            {
                                var FXModel = distributor_FXGradeRepository.GetEntity(disModel.FXGradeId);
                                //购买直接抵扣佣金
                                if (FXModel != null && FXModel.CommissionType == 2)
                                {
                                    IsDeductionCommission = true;
                                    //开始慢慢找   注 同级返佣数量  返佣建子表可以无限级返佣了   --2020/10/16 未使用课程卡的才能返佣
                                    var DetailList = demodel.DetailList.Where(x => x.CommissionPrice > 0 && (x.EducationCouponId ?? 0) == 0).ToList();
                                    foreach (var item in DetailList)
                                    {
                                        if ((item.PresentFXGrade ?? 0) > 0)
                                        {
                                            //是赠送VIP等级的  暂直接表示 反购买VIP佣金  2020-08-03  ld
                                            continue;
                                        }

                                        //第一个进来  按等级的返佣比例给佣金
                                        decimal DcommionMoney = 0;
                                        if (FXModel.DecimalType == 1)
                                        {
                                            DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0) / 100);
                                        }
                                        else
                                        {
                                            DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0)) / 100;
                                        }

                                        item.TCommissionMoney = DcommionMoney * (item.Number ?? 0);
                                    }

                                    TotalDeductionCommission = DetailList.Sum(x => x.TCommissionMoney);
                                }
                            }
                        }
                        else
                        {
                            LogHelper.Write("粉象返佣 用户分销商信息不存在：UserId:" + umodel.Id);
                        }
                    }
                }
                #endregion

                List<int> ExpressGoodsId = new List<int>();
                //赋值
                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.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                    }

                    decimal couponMoney = 0;//优惠金额
                    var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                    if (couponModel != null)
                    {
                        couponMoney = couponModel.CouponMoney;
                        TotalGoodsMoney -= couponMoney;//总价格需减去优惠券金额
                    }

                    if (goodsPreferentialList != null && goodsPreferentialList.Any())
                    {
                        if (item.Number > 0)//教育订单判断是否有优惠
                        {
                            var nowGoodsPreferentialList = goodsPreferentialList.Where(x => x.GoodsId == item.GoodsId).ToList();
                            if (nowGoodsPreferentialList != null && nowGoodsPreferentialList.Any())
                            {
                                decimal goodsCouponsMoney = 0;
                                foreach (var itemPreferential in nowGoodsPreferentialList.OrderByDescending(x => (int)x.PriceDiscountType))
                                {
                                    if (itemPreferential.PriceDiscountType == CoursePriceDiscountEnum.DoubleJoin && item.Number > 1)
                                    {
                                        goodsCouponsMoney = (item.Unit_Price ?? 0) * ((itemPreferential.PriceMoney) / Convert.ToDecimal(100)) * (item.Number ?? 0);
                                        break;
                                    }
                                    else if (itemPreferential.PriceDiscountType == CoursePriceDiscountEnum.SingleJoin)
                                    {
                                        goodsCouponsMoney = (item.Unit_Price ?? 0) * ((itemPreferential.PriceMoney) / Convert.ToDecimal(100)) * (item.Number ?? 0);
                                        break;
                                    }
                                    else if (itemPreferential.PriceDiscountType == CoursePriceDiscountEnum.BuySend)
                                    {
                                        int joinNum = (item.Number ?? 0) / (itemPreferential.BuyNum + itemPreferential.SendNum) * itemPreferential.BuyNum + (item.Number ?? 0) % (itemPreferential.BuyNum + itemPreferential.SendNum);
                                        goodsCouponsMoney = (item.Unit_Price ?? 0) * (item.Number ?? 0) - (item.Unit_Price ?? 0) * joinNum;
                                        break;
                                    }
                                }
                                if (goodsCouponsMoney > 0)
                                {
                                    couponMoney += goodsCouponsMoney;
                                    item.CouponMoney += goodsCouponsMoney;
                                    TotalGoodsMoney -= goodsCouponsMoney;//总价格需减去优惠券金额
                                                                         //item.Final_Price -= goodsCouponsMoney;
                                    CouponsMoney += goodsCouponsMoney;
                                }
                            }
                        }
                    }

                    #region 运费
                    decimal Express = 0;
                    string FreeShippingDescription = "";
                    bool FreeShipping_Use = false;
                    bool ExpressIsReckon = false;//多规格情况，同一商品
                    if (defModel.Id > 0 && demodel.DeliveryMethod == OrderDeliveryMethodEnum.ExpressDistribution)
                    {
                        //计算总和  
                        int exNum = demodel.DetailList.Where(x => x.GoodsId == item.GoodsId).Sum(x => x.Number ?? 0);
                        decimal exMoney = demodel.DetailList.Where(x => x.GoodsId == item.GoodsId).Sum(x => x.NorGoodsMoney);
                        if (!((gmodel.FullNumPinkage > 0 && exNum >= gmodel.FullNumPinkage) || (gmodel.FullMoneyPinkage > 0 && exMoney >= gmodel.FullMoneyPinkage)))
                        {
                            if ((gmodel.FullMoneyPinkage ?? 0) == 0 && (gmodel.FullNumPinkage ?? 0) == 0 && YFCategoryList.Any())
                            {
                                //查找全局包邮规则
                                if (freeShippingList != null && freeShippingList.Any())
                                {
                                    var fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                                    {
                                        fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    }
                                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                                    {
                                        fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    }
                                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                                    {
                                        fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    }
                                    if (fullNumPinkageModel != null)
                                    {
                                        //看所有商品是否满足该规则
                                        var sglist = SatisfiedGoodsList.Where(x => x.FreeShipping == fullNumPinkageModel.ID).ToList();
                                        var nosglist = SatisfiedGoodsList.Where(x => x.FreeShipping != fullNumPinkageModel.ID).ToList();
                                        if (sglist.Any())
                                        {
                                            //看着商品是否包含在这里面
                                            if (sglist.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).Any())
                                            {
                                                FreeShipping_Use = true;
                                                FreeShippingDescription = sglist.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault().Name;
                                            }
                                        }
                                        else
                                        {
                                            //根据  查询出所有的订单商品
                                            var SatisfiedGoodsList2 = new List<FreeShippingGoodsDetail>();
                                            foreach (var qitem in demodel.DetailList)
                                            {
                                                var qgmodel = gList.Where(x => x.Id == qitem.GoodsId).FirstOrDefault();
                                                if (qgmodel != null && qgmodel.GoodsStatus == 1 && (qgmodel.FullMoneyPinkage ?? 0) == 0 && (qgmodel.FullNumPinkage ?? 0) == 0)
                                                {
                                                    if (!nosglist.Where(x => x.GoodsId == qitem.GoodsId && x.SpecificationKey == qitem.SpecificationSort).Any())
                                                    {
                                                        var fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        if (fpkModel == null || fpkModel.ID <= 0)
                                                        {
                                                            fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        }
                                                        if (fpkModel == null || fpkModel.ID <= 0)
                                                        {
                                                            fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        }
                                                        if (fpkModel == null || fpkModel.ID <= 0)
                                                        {
                                                            fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        }
                                                        if (fpkModel != null && fpkModel.ID == fullNumPinkageModel.ID)
                                                        {
                                                            //是同一包邮规则里的
                                                            string Name = fullNumPinkageModel.Name;
                                                            if (fullNumPinkageModel.FullNumPinkage > 0)
                                                            {
                                                                Name += "：满" + fullNumPinkageModel.FullNumPinkage + "件包邮";
                                                            }
                                                            else if (fullNumPinkageModel.FullMoneyPinkage > 0)
                                                            {
                                                                Name += "：满" + fullNumPinkageModel.FullMoneyPinkage + "元包邮";
                                                            }
                                                            SatisfiedGoodsList2.Add(new FreeShippingGoodsDetail()
                                                            {
                                                                FreeShipping = fullNumPinkageModel.ID,
                                                                Name = Name,
                                                                GoodsId = qitem.GoodsId ?? 0,
                                                                SpecificationKey = qitem.SpecificationSort,
                                                                Number = qitem.Number ?? 0,
                                                                Money = qitem.NorGoodsMoney
                                                            });
                                                        }
                                                    }
                                                }
                                            }
                                            if (SatisfiedGoodsList2.Any())
                                            {
                                                //看是否满足包邮
                                                if (fullNumPinkageModel.FullNumPinkage > 0)
                                                {
                                                    if (SatisfiedGoodsList2.Sum(x => x.Number) >= fullNumPinkageModel.FullNumPinkage)
                                                    {
                                                        FreeShipping_Use = true;
                                                        SatisfiedGoodsList.AddRange(SatisfiedGoodsList2);
                                                    }
                                                }
                                                else if (fullNumPinkageModel.FullMoneyPinkage > 0)
                                                {
                                                    if (SatisfiedGoodsList2.Sum(x => x.Money) >= fullNumPinkageModel.FullMoneyPinkage)
                                                    {
                                                        FreeShipping_Use = true;
                                                        SatisfiedGoodsList.AddRange(SatisfiedGoodsList2);
                                                    }
                                                }
                                                SatisfiedGoodsListAll.AddRange(SatisfiedGoodsList2);
                                            }

                                            //看着商品是否包含在这里面
                                            if (SatisfiedGoodsList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).Any())
                                            {
                                                FreeShippingDescription = SatisfiedGoodsList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault().Name;
                                            }
                                        }

                                        if (FreeShipping_Use == false)
                                        {

                                            FreeShippingDescription = SatisfiedGoodsListAll.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault()?.Name ?? "";
                                        }
                                    }
                                }
                            }
                            if (FreeShipping_Use == false)
                            {
                                int FreightId2 = gmodel.FreightId ?? 0;
                                if (gmodel.FreightId == 0)
                                {
                                    FreightId2 = DefFreightId;
                                }
                                if (FreightId2 > 0)
                                {
                                    var rulesModel = rulesList.Where(x => x.ID == FreightId2).FirstOrDefault();
                                    List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList2 = priceList.Where(x => x.RulesId == FreightId2).ToList();
                                    if (priceList2.Any())
                                    {
                                        var priceIds = priceList2.Select(x => x.ID).ToList();
                                        var regionList2 = regionList.Where(x => priceIds.Contains(x.RulesPriceId)).ToList();

                                        var regionModel = regionList2.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                                        if (regionModel != null)
                                        {
                                            var pmodel = priceList2.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                                            if (pmodel != null && rulesModel != null)
                                            {
                                                if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                                {
                                                    //按件计费
                                                    if (exNum <= pmodel.First)
                                                    {
                                                        Express = pmodel.FirstPrice;
                                                    }
                                                    else
                                                    {
                                                        if (pmodel.Second > 0)
                                                        {
                                                            if ((exNum - pmodel.First) % pmodel.Second == 0)
                                                            {
                                                                Express = pmodel.FirstPrice + ((exNum - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                            }
                                                            else
                                                            {
                                                                Express = pmodel.FirstPrice + ((exNum - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            Express = pmodel.FirstPrice;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    //重量计费
                                                    int TotalW = exNum * (item.GoodsWeight ?? 0);
                                                    if (TotalW <= pmodel.First)
                                                    {
                                                        Express = pmodel.FirstPrice;
                                                    }
                                                    else
                                                    {
                                                        if (pmodel.Second > 0)
                                                        {
                                                            if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                                            {
                                                                Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                            }
                                                            else
                                                            {
                                                                Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            Express = pmodel.FirstPrice;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (exNum != item.Number)
                                {
                                    if (!ExpressGoodsId.Contains(item.GoodsId ?? 0))
                                    {
                                        ExpressGoodsId.Add(item.GoodsId ?? 0);
                                    }
                                    else
                                    {
                                        ExpressIsReckon = true;
                                    }
                                }
                            }
                        }
                    }
                    if (!ExpressIsReckon)
                    {
                        TotalExpress += Express;
                        item.Final_Price += Express;
                        item.Express = Express;
                        TotalGoodsMoney += Express;
                    }
                    #endregion

                    #region 储值卡抵扣
                    if (IsDepositUse && demodel.Use_Deposit_Id > 0 && depositModel.SurplusPrice > 0)
                    {
                        decimal CurrentMoney = (item.Final_Price ?? 0) - item.TCommissionMoney;
                        if (CurrentMoney > depositModel.SurplusPrice)
                        {
                            item.Final_Price = CurrentMoney - depositModel.SurplusPrice;
                            item.DepositMoney = depositModel.SurplusPrice;
                            depositModel.SurplusPrice = 0;
                            TotalDepositMoney += item.DepositMoney;
                        }
                        else
                        {
                            item.Final_Price = 0;
                            item.DepositMoney = CurrentMoney;
                            depositModel.SurplusPrice -= CurrentMoney;
                            TotalDepositMoney += item.DepositMoney;
                        }
                    }
                    #endregion

                    var areaGoods = AreaList.Where(x => x.GoodsId == item.GoodsId).ToList();
                    bool address_disabled = false;
                    if (demodel.DeliveryMethod != OrderDeliveryMethodEnum.VerificationShop)
                    {
                        if (gmodel.IsAreaBuy == 1 && areaGoods.Any())
                        {
                            if (!areaGoods.Where(x => disList.Contains(x.AreaId ?? 0)).Any())
                            {
                                address_disabled = true;
                                address_enable = false;
                            }
                        }
                        else
                        {
                            //验证基础设置区域购买
                            if (RAreaList.Any())
                            {
                                if (!RAreaList.Where(x => disList.Contains(x)).Any())
                                {
                                    address_disabled = true;
                                    address_enable = false;
                                }
                            }
                        }
                    }
                    var tempLogo = new MarketingLogoItem();
                    if (!string.IsNullOrEmpty(gmodel?.MarketingLogo))
                    {
                        try
                        {
                            tempLogo = Common.Plugin.JsonHelper.DeserializeObject<MarketingLogoItem>(gmodel?.MarketingLogo);
                        }
                        catch
                        {
                            tempLogo = new MarketingLogoItem();
                        }
                    }
                    //进阶小课堂扩展字段
                    var eduData = goodsRepository.ParsingEduJsonRepository(gmodel.EduJsonData);
                    Model.Extend.TradePavilion.RB_Custom_Form_Extend customFormModel = new Model.Extend.TradePavilion.RB_Custom_Form_Extend();
                    if (customFormList != null && customFormList.Any())
                    {
                        customFormModel = customFormList?.FirstOrDefault(x => x.Id == gmodel.FormsId);
                        if ((customFormModel?.Id ?? 0) == 0)
                        {
                            customFormModel = customFormList?.FirstOrDefault();
                        }
                    }
                    item.DepositRatio = gmodel.DepositRatio;//2024-02-22 add by:W
                    goods_list.Add(new
                    {
                        id = gmodel.Id,
                        name = gmodel.Name,
                        categoryIdList = item.CategoryIdList,
                        specificationNameList = item.SpecificationNameList,
                        GoodsRelevanceList = goodsRelevanceList?.Where(qitem => qitem.GoodsId == gmodel.Id)?.ToList(),
                        num = item.Number,
                        EduData = eduData,
                        EduTeacherId = gmodel?.EduTeacherId ?? 0,
                        forehead_integral = gmodel.PointsDeduction,
                        forehead_integral_type = gmodel.PointsDeductionType,
                        accumulative = gmodel.IsMultipleDeduction,//累计多件抵扣
                        address_disabled,
                        pieces = gmodel.FullNumPinkage,//满件包邮
                        forehead = gmodel.FullMoneyPinkage,//满额包邮
                        freeShippingDescription = FreeShippingDescription,
                        freeShipping_Use = FreeShipping_Use,
                        freight_id = gmodel.FreightId,
                        express_price = item.Express,
                        deduction_commission = item.TCommissionMoney,
                        deposit_price = item.DepositMoney,
                        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,
                            depositRatio = item.DepositRatio,//2024-02-22 add by:W
                            sign_id = item.SpecificationSort,
                            stock = gmodel.InventoryNum,
                            price = item.Unit_Price ?? 0,
                            original_price = item.Original_Price ?? 0,
                            no = gmodel.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url = item.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,
                            name = gmodel.Name,
                            cover_pic = item.CoverImage,
                            detail = gmodel.GoodsDetails,
                            pic_list = gmodel.CarouselImageList.Select(x => new
                            {
                                id = x.Id,
                                pic_url = x.Path
                            }),
                            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
                        },
                        attr_list = item.Attr_list,
                        discounts = item.Discounts,
                        member_discount = ((item.Unit_Price ?? 0) * (item.Number ?? 0)) - (item.MemberPrice * (item.Number ?? 0)),
                        cover_pic = item.CoverImage,
                        is_level_alone = gmodel.SeparateSetMember,//是否单独设置会员价
                        is_level = gmodel.EnjoyMember,//是否销售会员价格
                        sign = "",
                        confine_order_count = gmodel.LimitBuyOrderNum,//限制订单数量
                        form_id = gmodel.FormsId,//表单id
                        form_data_json = (customFormModel?.Id ?? 0) > 1 ? AnalyzeFormComponent(customFormModel.FormData, isGetAnswer: false) : new List<Model.Extend.TradePavilion.FormDataItem>(),
                        marketingLogo = JsonHelper.Serialize(tempLogo),
                    });
                }
            }

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

            var minModel = miniProgramRepository.GetEntity(demodel.MallBaseId);
            //满足全局包邮的规则
            List<object> PinkageList = new List<object>();
            if (SatisfiedGoodsList.Any())
            {
                var Names = SatisfiedGoodsList.Select(x => x.Name).Distinct().ToList();
                foreach (var item in Names)
                {
                    int TNumber = SatisfiedGoodsList.Where(x => x.Name == item).Sum(x => x.Number);
                    decimal TMoney = SatisfiedGoodsList.Where(x => x.Name == item).Sum(x => x.Money);
                    PinkageList.Add(new
                    {
                        Name = item,
                        TNumber,
                        TMoney
                    });
                }
            }
            if (OldDepositMoney >= (TotalGoodsMoney - TotalDeductionCommission))
            {
                //为了防止运费出现四舍五入不平均问题，只要全额抵扣的就重新赋下值
                TotalDepositMoney = (TotalGoodsMoney - TotalDeductionCommission);
            }
            TotalGoodsMoney = TotalGoodsMoney - TotalDeductionCommission - TotalDepositMoney;//总额 - 抵扣佣金 - 储值卡抵扣金额
            mch_list.Add(new
            {
                mch = new
                {
                    id = minModel?.MallBaseId ?? 0,
                    name = minModel?.MallName ?? ""
                },
                goods_list,
                pinkageList = PinkageList,
                express_price = TotalExpress,
                remark = "",
                total_goods_price = TotalGoodsSellMoney,
                total_goods_original_price = TotalGoodsOriginalMoney,
                member_discount,
                coupon = new
                {
                    enabled = true,
                    use = CouponsMoney > 0 && demodel.User_Coupon_Id > 0,
                    coupon_discount = CouponsMoney,
                    user_coupon_id = CouponsMoney > 0 ? demodel.User_Coupon_Id ?? 0 : 0
                },
                integral = new
                {
                    can_use = IsPointsDeduction,
                    use = demodel.Use_Integral == 1,
                    use_num = Total_use_integral,
                    deduction_price = Total_integral_price
                },
                deposit = new
                {
                    can_use = IsDepositUse,
                    use = TotalDepositMoney > 0 && demodel.Use_Deposit_Id > 0,
                    deposit_price = TotalDepositMoney,
                    use_deposit_id = TotalDepositMoney > 0 ? demodel.Use_Deposit_Id : 0
                },
                delivery = Delivery,
                store_select_enable = true,
                total_price = TotalGoodsMoney,
                is_deduction_commission = IsDeductionCommission,
                deduction_commission = TotalDeductionCommission
            });

            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);
                }
            }
            decimal depositMoney = 0;
            if (umodel.MallBaseId == 19)
            {
                depositMoney = demodel.DetailList?.Where(x => x.DepositRatio > 0).Sum(x => (1 - (x.DepositRatio / 100)) * (x.Final_Price ?? 0)) ?? 0;
            }
            var Robj = new
            {
                mch_list,
                promptNoSuperiorFY = PromptNoSuperiorFY,
                total_price = TotalGoodsMoney,
                pay_total_price = (TotalGoodsMoney - depositMoney),
                price_enable = true,
                address = new
                {
                    id = defModel?.Id ?? 0,
                    user_id = demodel.UserId,
                    name = defModel?.Name ?? "",
                    province_id = defModel?.Province ?? 0,
                    province = defModel?.PName ?? "",
                    city_id = defModel?.City ?? 0,
                    city = defModel?.CName ?? "",
                    district_id = defModel?.District ?? 0,
                    district = defModel?.DName ?? "",
                    mobile = defModel?.Mobile ?? "",
                    detail = defModel?.Address ?? "",
                    is_default = defModel?.IsDefault ?? 2,
                    lonlat = defModel?.Lonlat
                },
                address_enable,
                template_message_list
            };
            #endregion
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 获取结算页面 快递修改后 快递费用
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult GetAppletGoodsSettlementExpress(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            //获取用户的默认收货地址
            var defModel = member_ShippingAddressRepository.GetEntity(demodel.ShoppingAddressId);
            List<int> disList = new List<int>();
            if (defModel == null)
            {
                return ApiResult.Failed("收货地址不存在");
            }
            else
            {
                disList.Add(defModel.Province ?? 0);
                disList.Add(defModel.City ?? 0);
                disList.Add(defModel.District ?? 0);
            }
            List<object> DList = new List<object>();
            decimal TotalExpress = 0;
            int DefFreightId = 0;
            if (demodel.DetailList.Any())
            {
                string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend> rulesList = new List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend> regionList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend>();
                if (gList.Any() && defModel.Id > 0)
                {
                    List<int> FreightIdList = new List<int>();
                    if (gList.Where(x => x.FreightId > 0).Any())
                    {
                        FreightIdList.AddRange(gList.Where(x => x.FreightId > 0).Select(x => x.FreightId ?? 0).ToList());
                    }
                    if (gList.Where(x => x.FreightId == 0).Any())
                    {
                        //查询默认
                        DefFreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault()?.ID ?? 0;
                        FreightIdList.Add(DefFreightId);
                    }

                    if (FreightIdList.Any())
                    {
                        rulesList = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { RulesIds = string.Join(",", FreightIdList), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        priceList = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, RulesIds = string.Join(",", FreightIdList) });
                        if (priceList.Any())
                        {
                            string priceIds = string.Join(",", priceList.Select(x => x.ID));
                            regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, PriceIds = priceIds });
                        }
                    }

                }
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    int GoodsWeight = gmodel.GoodsWeight ?? 0;//商品重量
                    #region 规格
                    //验证规格是否已失效
                    if (gmodel.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            continue;
                        }
                    }

                    if (!string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        GoodsWeight = speciPModel?.GoodsWeight ?? 0;
                        if (item.Number > speciPModel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    else
                    {
                        if (item.Number > gmodel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    #endregion
                    //运费
                    decimal Express = 0;
                    if (defModel.Id > 0)
                    {
                        int FreightId2 = gmodel.FreightId ?? 0;
                        if (gmodel.FreightId == 0)
                        {
                            FreightId2 = DefFreightId;
                        }
                        if (FreightId2 > 0)
                        {
                            var rulesModel = rulesList.Where(x => x.ID == FreightId2).FirstOrDefault();
                            List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList2 = priceList.Where(x => x.RulesId == FreightId2).ToList();
                            if (priceList2.Any())
                            {
                                var priceIds = priceList2.Select(x => x.ID).ToList();
                                var regionList2 = regionList.Where(x => priceIds.Contains(x.RulesPriceId)).ToList();

                                var regionModel = regionList2.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                                if (regionModel != null)
                                {
                                    var pmodel = priceList2.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                                    if (pmodel != null && rulesModel != null)
                                    {
                                        if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                        {
                                            //按件计费
                                            if (item.Number <= pmodel.First)
                                            {
                                                Express = pmodel.FirstPrice;
                                            }
                                            else
                                            {
                                                if (pmodel.Second > 0)
                                                {
                                                    if (((item.Number ?? 0) - pmodel.First) % pmodel.Second == 0)
                                                    {
                                                        Express = pmodel.FirstPrice + (((item.Number ?? 0) - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                    }
                                                    else
                                                    {
                                                        Express = pmodel.FirstPrice + (((item.Number ?? 0) - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                    }
                                                }
                                                else
                                                {
                                                    Express = pmodel.FirstPrice;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //重量计费
                                            int TotalW = (item.Number ?? 0) * GoodsWeight;
                                            if (TotalW <= pmodel.First)
                                            {
                                                Express = pmodel.FirstPrice;
                                            }
                                            else
                                            {
                                                if (pmodel.Second > 0)
                                                {
                                                    if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                                    {
                                                        Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                    }
                                                    else
                                                    {
                                                        Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                    }
                                                }
                                                else
                                                {
                                                    Express = pmodel.FirstPrice;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    DList.Add(new
                    {
                        item.GoodsId,
                        item.SpecificationSort,
                        Express
                    });
                    TotalExpress += Express;
                }
            }
            return ApiResult.Success("", new
            {
                DetailList = DList,
                TotalExpress
            });
        }

        /// <summary>
        /// 下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult SetAppletGoodsOrderInfo(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            if (umodel.CustomerChildrenId > 0)
            {
                //绑定erp同业积分
                var cmodel = customer_IntegralRepository.GetCustomerInfo(umodel.CustomerChildrenId);
                if (cmodel != null && cmodel.IntegralUse != 2)
                {
                    decimal intergralNum = customer_IntegralRepository.GetCustomerIntegralSurplus(umodel.CustomerId, cmodel.IntegralUse == 0 ? umodel.CustomerChildrenId : 0);
                    umodel.Integral = Convert.ToInt32(intergralNum);
                }
            }
            if (demodel.SmallShopsId == 0)
            {
                demodel.SmallShopsId = umodel.SmallShopId;
            }
            if (umodel.Blacklist == 1)
            {
                return ApiResult.Failed("您在黑名单状态无法下单，请联系管理员核实");
            }
            List<int> disList = new List<int>
            {
                demodel.Province ?? 0,
                demodel.City ?? 0,
                demodel.District ?? 0
            };


            decimal TotalExpress = 0;
            decimal TotalMoney = 0;
            string GoodsIds = "";
            int TotalIntegralNumber = 0;//总使用积分
            decimal TotalIntegralMoney = 0;//总使用积分抵扣金额

            List<RB_Goods_CouponModel> GoodsCouponList = new List<RB_Goods_CouponModel>();//商品优惠卷 价格（每个商品优惠的价格）
            decimal CouponsMoney = 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>();
            List<RB_Goods_Preferential_Extend> goodsPreferentialList = new List<RB_Goods_Preferential_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;
                            }
                        }
                    }
                }
            }
            if (demodel.VersionSource == 1)//教育订单判断是否有优惠
            {
                string goodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                if (!string.IsNullOrWhiteSpace(goodsIds))
                {
                    goodsPreferentialList = RB_Goods_PreferentialRepository.GetGoodsPreferentialListRepostory(new RB_Goods_Preferential_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, QGoodsIds = goodsIds });
                }

            }
            #endregion
            List<FreeShippingGoodsDetail> SatisfiedGoodsList = new List<FreeShippingGoodsDetail>();//可包邮的商品
            var depositModel = new RB_Member_DepositBuy_Extend();//储值卡
            decimal DeductionCommission = 0;//购买抵扣金额
            decimal TotalDepositMoney = 0, OldDepositMoney = 0;//储值卡抵扣金额   使用之前金额
            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();
                }
                int DefFreightId = 0;//默认运费id
                GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                //绑定物品列表
                var goodsRelevanceList = goods_RelevanceRepository.GetGoodsRelevanceListRepository(new RB_Goods_Relevance_Extend()
                {
                    TenantId = demodel.TenantId,
                    MallBaseId = demodel.MallBaseId,
                    QGoodsIds = GoodsIds
                });

                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_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 });
                List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend> rulesList = new List<Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend>();
                List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend> regionList = new List<Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend>();
                if (gList.Any() && demodel.DeliveryMethod == OrderDeliveryMethodEnum.ExpressDistribution)
                {
                    List<int> FreightIdList = new List<int>();
                    if (gList.Where(x => x.FreightId > 0).Any())
                    {
                        FreightIdList.AddRange(gList.Where(x => x.FreightId > 0).Select(x => x.FreightId ?? 0).ToList());
                    }
                    if (gList.Where(x => x.FreightId == 0).Any())
                    {
                        //查询默认
                        DefFreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault()?.ID ?? 0;
                        FreightIdList.Add(DefFreightId);
                    }

                    if (FreightIdList.Any())
                    {
                        rulesList = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { RulesIds = string.Join(",", FreightIdList), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        priceList = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, RulesIds = string.Join(",", FreightIdList) });
                        if (priceList.Any())
                        {
                            string priceIds = string.Join(",", priceList.Select(x => x.ID));
                            regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, PriceIds = priceIds });
                        }
                    }

                }
                var OrderGoodsNumList = new List<RB_Goods_Order_Extend>();
                bool IsLimitOk = false;
                if (gList.Where(x => x.LimitBuyGoodsNum > 0).Any())
                {
                    IsLimitOk = true;
                    string LimitGoodsIds = string.Join(",", gList.Where(x => x.LimitBuyGoodsNum > 0).Select(x => x.Id));
                    //查询用户该商品已下单数量
                    OrderGoodsNumList = goods_OrderRepository.GetUserOrderGoodsNum(demodel.UserId ?? 0, LimitGoodsIds, demodel.TenantId, demodel.MallBaseId);
                }
                var OrderNumList = new List<RB_Goods_Order_Extend>();
                if (gList.Where(x => x.LimitBuyOrderNum > 0).Any())
                {
                    IsLimitOk = true;
                    string LimitGoodsIds = string.Join(",", gList.Where(x => x.LimitBuyOrderNum > 0).Select(x => x.Id));
                    //查询用户该商品已下单数量
                    OrderNumList = goods_OrderRepository.GetUserOrderNum(demodel.UserId ?? 0, LimitGoodsIds, demodel.TenantId, demodel.MallBaseId);
                }
                //验证限购
                if (OrderGoodsNumList.Any() || OrderNumList.Any())
                {
                    List<int> GoodsIdList = demodel.DetailList.Select(x => x.GoodsId ?? 0).Distinct().ToList();
                    foreach (var item in GoodsIdList)
                    {
                        int GoodsNum = demodel.DetailList.Where(x => x.GoodsId == item).Sum(x => x.Number ?? 0);
                        var gmodel = gList.Where(x => x.Id == item).FirstOrDefault();
                        if (gmodel == null || gmodel.GoodsStatus != 1)
                        {
                            return ApiResult.Failed("有商品不存在或者商品已失效");
                        }
                        #region 验证商品限购，订单限购
                        if (gmodel.LimitBuyGoodsNum > 0)
                        {
                            var ogModel = OrderGoodsNumList.Where(x => x.GoodsId == gmodel.Id).FirstOrDefault();
                            if (ogModel != null)
                            {
                                if (ogModel.GoodsTotalNum + GoodsNum > (gmodel.LimitBuyGoodsNum ?? 0))
                                {
                                    return ApiResult.Failed("该商品限购" + (gmodel.LimitBuyGoodsNum ?? 0) + "件，您已购买" + ogModel.GoodsTotalNum + "件");
                                }
                            }
                        }
                        if (gmodel.LimitBuyOrderNum > 0)
                        {
                            var ogModel = OrderNumList.Where(x => x.GoodsId == gmodel.Id).FirstOrDefault();
                            if (ogModel != null)
                            {
                                if (ogModel.OrderNum + 1 > (gmodel.LimitBuyOrderNum ?? 0))
                                {
                                    return ApiResult.Failed("该商品订单限购" + (gmodel.LimitBuyOrderNum ?? 0) + "单，您已购买" + ogModel.OrderNum + "单");
                                }
                            }
                        }

                        #endregion
                    }
                }
                else if (IsLimitOk)
                {
                    List<int> GoodsIdList = demodel.DetailList.Select(x => x.GoodsId ?? 0).Distinct().ToList();
                    foreach (var item in GoodsIdList)
                    {
                        int GoodsNum = demodel.DetailList.Where(x => x.GoodsId == item).Sum(x => x.Number ?? 0);
                        var gmodel = gList.Where(x => x.Id == item).FirstOrDefault();
                        if (gmodel == null || gmodel.GoodsStatus != 1)
                        {
                            return ApiResult.Failed("有商品不存在或者商品已失效");
                        }
                        #region 验证商品限购，订单限购
                        if (gmodel.LimitBuyGoodsNum > 0)
                        {
                            if (GoodsNum > (gmodel.LimitBuyGoodsNum ?? 0))
                            {
                                return ApiResult.Failed("该商品限购" + (gmodel.LimitBuyGoodsNum ?? 0) + "件");
                            }
                        }
                        #endregion
                    }
                }
                List<int> YFCategoryList = new List<int>();//全局适配 分类
                var mallbaseModel = mallBaseRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_MallBase_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();

                #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

                #region 储值卡
                if (demodel.Use_Deposit_Id > 0)
                {
                    if ((mallbaseModel?.DepositFun ?? 0) != 1)
                    {
                        return ApiResult.Failed("未启用储值卡功能，无法使用");
                    }
                    demodel.DepositId = demodel.Use_Deposit_Id;
                    depositModel = member_DepositBuyRepository.GetEntity<RB_Member_DepositBuy_Extend>(demodel.Use_Deposit_Id);
                    if (depositModel == null || depositModel.Status == 0 || depositModel.SendStatus != 0)
                    {
                        return ApiResult.Failed("储值卡不存在，请核实后再试");
                    }
                    if (depositModel.UserId != umodel.Id)
                    {
                        return ApiResult.Failed("储值卡使用有误，请核实后再试");
                    }
                    if (depositModel.SurplusPrice <= 0)
                    {
                        return ApiResult.Failed("储值卡金额不足，请核实后再试");
                    }
                    OldDepositMoney = depositModel.SurplusPrice;
                }
                #endregion

                #region 咖啡劵赠送

                if (demodel.OrderEduType == 1)
                {
                    int BuyNum = demodel.DetailList.FirstOrDefault().Number ?? 0;
                    int PresentCoffeeNum = 0;
                    //抓取获赠咖啡的数量
                    string GiveAway = dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = demodel.MallBaseId, DictKey = "Edu_CoffeeCoupons_GiveAway" }).FirstOrDefault()?.Content ?? "";
                    List<object> giveAwayList = new List<object>();
                    if (!string.IsNullOrEmpty(GiveAway))
                    {
                        var glist = GiveAway.Split("/");
                        foreach (var item in glist)
                        {
                            var slist = item.Split('-');
                            if (slist[0] == BuyNum.ToString())
                            {
                                PresentCoffeeNum = Convert.ToInt32(slist[1]);
                                break;
                            }
                        }
                    }
                    if (demodel.DetailList.Where(x => x.PresentCoffeeNum != PresentCoffeeNum).Any())
                    {
                        return ApiResult.Failed("商品赠送数量不正确");
                    }
                }

                #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.GoodsEduType == 2)
                    {
                        demodel.OrderEduType = 2;//资产商品化
                    }
                    item.MaterialId = gmodel.MaterialId;
                    item.DepositRatio = gmodel.DepositRatio;
                    if (gmodel.PresentFXGrade > 0)
                    {
                        //是赠送VIP商品
                        if (demodel.DetailList.Count() > 1)
                        {
                            //多商品
                            return ApiResult.Failed("VIP商品不能与其他商品同时下单，请先购买VIP商品");
                        }
                        var disModel = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserId = umodel.Id }).FirstOrDefault();
                        if (disModel != null)
                        {
                            var fxgradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = umodel.TenantId, MallBaseId = umodel.MallBaseId });
                            fxgradeList = fxgradeList.Where(x => x.IsGuest == 1 || x.IsGuest == 3).ToList();
                            if (!fxgradeList.Select(x => x.Id).Contains(disModel.FXGradeId ?? 0))
                            {
                                return ApiResult.Failed("您当前等级无法购买VIP商品");
                            }
                        }
                    }
                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();
                    if ((mallbaseModel?.IsFreeShipping ?? 0) == 1 && (gmodel.FullMoneyPinkage ?? 0) == 0 && (gmodel.FullNumPinkage ?? 0) == 0)
                    {
                        YFCategoryList.AddRange(categoryList.Select(x => x.CategoryId ?? 0).ToList());
                    }
                    item.IsNoTax = gmodel.IsNoTax;//2020-11-10 Add by:W 商品是否可以开票
                    item.InventoryNum = gmodel.InventoryNum ?? 0;

                    item.CommissionPrice = gmodel.Commission;// 粉象 返佣金额
                    item.CostMoney = (gmodel.IsCustomSpecification == 2) ? (gmodel.CostPrice ?? 0) : (speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault()?.CostMoney ?? 0);//gmodel.CostPrice ?? 0;

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

                    item.ProductCode = gmodel.GoodsNumbers;
                    item.CategoryIdList = categoryList.Select(x => x.CategoryId ?? 0).ToList();
                    int GoodsWeight = gmodel.GoodsWeight ?? 0;//商品重量                    
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(gmodel.CarouselImage) && gmodel.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(gmodel.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }

                    #region 规格
                    //验证规格是否已失效
                    if (gmodel.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            return ApiResult.Failed("有商品已失效，请重新下单");
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            return ApiResult.Failed("有商品已失效，请重新下单");
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            return ApiResult.Failed("有商品已失效，请重新下单");
                        }
                    }

                    if (!string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        gmodel.SellingPrice = speciPModel?.SellingPrice ?? 0;
                        gmodel.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        GoodsWeight = speciPModel?.GoodsWeight ?? 0;
                        item.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        item.SpeciPriceId = speciPModel?.Id ?? 0;
                        item.ProductCode = speciPModel?.GoodsNumbers ?? "";
                        if (item.Number > speciPModel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                        item.CommissionPrice = speciPModel?.Commission ?? 0;
                        #region 查询规格图片 
                        //2021-08-03 update by:w 因为要把教育规格对应的班级保存起来
                        if (demodel.VersionSource == 1)
                        {
                            var sprcificationList = goods_SpecificationValueRepository.GetSpecificationListImage(item.GoodsId ?? 0, item.SpecificationSort);
                            string simage = sprcificationList.Where(x => !string.IsNullOrWhiteSpace(x.Image)).OrderBy(x => x.Id).FirstOrDefault()?.Image ?? "";
                            if (!string.IsNullOrEmpty(simage))
                            {
                                item.CoverImage = simage;//规格图片赋值
                            }
                            item.ClassId = sprcificationList.OrderBy(x => x.Id).FirstOrDefault()?.ClassId ?? 0;//（班级id）
                        }
                        else
                        {
                            string simage = goods_SpecificationValueRepository.GetSpecificationImage(item.GoodsId ?? 0, item.SpecificationSort);
                            if (!string.IsNullOrEmpty(simage))
                            {
                                item.CoverImage = simage;//规格图片赋值
                            }
                        }

                        #endregion

                        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 == item.SpecificationSort).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);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (item.Number > gmodel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                        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;
                        }
                    }
                    //HK 2022-10-11 新增绑定物品金额
                    var tempRelevancePrice = goodsRelevanceList?.Where(qitem => qitem.GoodsId == gmodel.Id)?.Sum(qitem => qitem.RelevancePrice) ?? 0;
                    if (umodel.MemberGrade > 0)
                    {
                        item.Final_Price = gmodel.MemberPrice * (item.Number ?? 0) + tempRelevancePrice;
                    }
                    else
                    {
                        item.Final_Price = (gmodel.SellingPrice ?? 0) * (item.Number ?? 0) + tempRelevancePrice;
                    }
                    #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.NorGoodsMoney = item.Final_Price ?? 0;//用于计算 运费的  202-08-05 ld
                    item.GoodsWeight = GoodsWeight;

                    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 优惠券
                    //decimal CouponsMoney = 0;
                    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

                    TotalMoney += (item.Final_Price ?? 0);
                    item.OrderType = gmodel.GoodsType;
                    item.GoodsName = gmodel.Name;
                    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;
                        }
                    }
                }
                #region 处理全局包邮
                List<RB_FreeShipping_Extend> freeShippingList = new List<RB_FreeShipping_Extend>();
                if (YFCategoryList.Any())
                {
                    YFCategoryList = YFCategoryList.Distinct().ToList();
                    string categoryIds = string.Join(",", YFCategoryList);
                    freeShippingList = freeShippingRepository.GetFreeShippingListByCategoryIds(new RB_FreeShipping_Extend { MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId, CategoryIds = categoryIds });
                }
                #endregion

                #region 购买抵扣佣金
                var disbaseModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                if ((disbaseModel?.IsEnableFXGrade ?? 2) == 1)
                {
                    if (((disbaseModel?.IsEnableNoSuperiorFY ?? 1) == 1) || ((disbaseModel?.IsEnableNoSuperiorFY ?? 1) == 2 && (umodel.SuperiorId ?? 0) > 0))
                    {
                        //验证用户必须是分销商 最低普通会员 不是以普通会员处理
                        var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = umodel.Id, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                        if (disModel != null)
                        {
                            if (disModel.FXGradeId > 0)
                            {
                                var FXModel = distributor_FXGradeRepository.GetEntity(disModel.FXGradeId);
                                //购买直接抵扣佣金
                                if (FXModel != null && FXModel.CommissionType == 2)
                                {
                                    //开始慢慢找   注 同级返佣数量  返佣建子表可以无限级返佣了   --2020/10/16 未使用课程卡的才能返佣
                                    var DetailList = demodel.DetailList.Where(x => x.CommissionPrice > 0 && (x.EducationCouponId ?? 0) == 0).ToList();
                                    foreach (var item in DetailList)
                                    {
                                        if ((item.PresentFXGrade ?? 0) > 0)
                                        {
                                            //是赠送VIP等级的  暂直接表示 反购买VIP佣金  2020-08-03  ld
                                            continue;
                                        }

                                        //第一个进来  按等级的返佣比例给佣金
                                        decimal DcommionMoney = 0;
                                        if (FXModel.DecimalType == 1)
                                        {
                                            DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0) / 100);
                                        }
                                        else
                                        {
                                            DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0)) / 100;
                                        }

                                        item.DeductionCommission = DcommionMoney * (item.Number ?? 0);
                                    }

                                    DeductionCommission = DetailList.Sum(x => x.DeductionCommission ?? 0);
                                }
                            }
                        }
                        else
                        {
                            LogHelper.Write("粉象返佣 用户分销商信息不存在：UserId:" + umodel.Id);
                        }
                    }
                }
                #endregion
                List<int> ExpressGoodsId = new List<int>();//同商品  多规格
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    if (demodel.OrderEduType == 2)
                    {
                        if (item.MaterialId <= 0)
                        {
                            return ApiResult.Failed("不同板块商品，无法一起下单");
                        }
                    }
                    item.MaterialId = gmodel.MaterialId;
                    item.SupplierId = gmodel.SupplierId;
                    item.DepositRatio = gmodel.DepositRatio;
                    item.CouponMoney = 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);
                        }
                    }

                    if (demodel.VersionSource == 1 && item.Number > 0)//教育订单判断是否有优惠
                    {
                        var nowGoodsPreferentialList = goodsPreferentialList.Where(x => x.GoodsId == item.GoodsId).ToList();
                        if (nowGoodsPreferentialList != null && nowGoodsPreferentialList.Any())
                        {
                            decimal goodsCouponsMoney = 0;
                            foreach (var itemPreferential in nowGoodsPreferentialList.OrderByDescending(x => (int)x.PriceDiscountType))
                            {
                                if (itemPreferential.PriceDiscountType == CoursePriceDiscountEnum.DoubleJoin && item.Number > 1)
                                {
                                    goodsCouponsMoney = (item.Unit_Price ?? 0) * ((itemPreferential.PriceMoney) / Convert.ToDecimal(100)) * (item.Number ?? 0);
                                    break;
                                }
                                else if (itemPreferential.PriceDiscountType == CoursePriceDiscountEnum.SingleJoin)
                                {
                                    goodsCouponsMoney = (item.Unit_Price ?? 0) * ((itemPreferential.PriceMoney) / Convert.ToDecimal(100)) * (item.Number ?? 0);
                                    break;
                                }
                                else if (itemPreferential.PriceDiscountType == CoursePriceDiscountEnum.BuySend)
                                {
                                    int joinNum = (item.Number ?? 0) / (itemPreferential.BuyNum + itemPreferential.SendNum) * itemPreferential.BuyNum + (item.Number ?? 0) % (itemPreferential.BuyNum + itemPreferential.SendNum);
                                    goodsCouponsMoney = (item.Unit_Price ?? 0) * (item.Number ?? 0) - (item.Unit_Price ?? 0) * joinNum;
                                    break;
                                }
                            }
                            if (goodsCouponsMoney > 0)
                            {
                                item.CouponMoney += goodsCouponsMoney;
                                TotalMoney -= goodsCouponsMoney;//总价格需减去优惠券金额
                                item.Final_Price -= goodsCouponsMoney;
                                CouponsMoney += goodsCouponsMoney;
                            }
                        }
                    }


                    #region 运费
                    decimal Express = 0;
                    decimal TExpress = 0;
                    bool ExpressIsReckon = false;
                    if (demodel.DeliveryMethod == OrderDeliveryMethodEnum.ExpressDistribution)
                    {
                        //计算总和  
                        int exNum = demodel.DetailList.Where(x => x.GoodsId == item.GoodsId).Sum(x => x.Number ?? 0);
                        decimal exMoney = demodel.DetailList.Where(x => x.GoodsId == item.GoodsId).Sum(x => x.NorGoodsMoney);
                        if (!((gmodel.FullNumPinkage > 0 && exNum >= gmodel.FullNumPinkage) || (gmodel.FullMoneyPinkage > 0 && exMoney >= gmodel.FullMoneyPinkage)))
                        {
                            bool FreeShipping_Use = false;
                            if ((gmodel.FullMoneyPinkage ?? 0) == 0 && (gmodel.FullNumPinkage ?? 0) == 0 && YFCategoryList.Any())
                            {
                                //查找全局包邮规则
                                if (freeShippingList != null && freeShippingList.Any())
                                {
                                    var fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                                    {
                                        fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    }
                                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                                    {
                                        fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    }
                                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                                    {
                                        fullNumPinkageModel = freeShippingList.Where(x => item.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                    }
                                    if (fullNumPinkageModel != null)
                                    {
                                        //看所有商品是否满足该规则
                                        var sglist = SatisfiedGoodsList.Where(x => x.FreeShipping == fullNumPinkageModel.ID).ToList();
                                        var nosglist = SatisfiedGoodsList.Where(x => x.FreeShipping != fullNumPinkageModel.ID).ToList();
                                        if (sglist.Any())
                                        {
                                            //看着商品是否包含在这里面
                                            if (sglist.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).Any())
                                            {
                                                FreeShipping_Use = true;
                                                item.FreeShippingRemarks = sglist.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault().Name;
                                            }
                                        }
                                        else
                                        {
                                            //根据  查询出所有的订单商品
                                            var SatisfiedGoodsList2 = new List<FreeShippingGoodsDetail>();
                                            foreach (var qitem in demodel.DetailList)
                                            {
                                                var qgmodel = gList.Where(x => x.Id == qitem.GoodsId).FirstOrDefault();
                                                if (qgmodel != null && qgmodel.GoodsStatus == 1 && (qgmodel.FullMoneyPinkage ?? 0) == 0 && (qgmodel.FullNumPinkage ?? 0) == 0)
                                                {
                                                    if (!nosglist.Where(x => x.GoodsId == qitem.GoodsId && x.SpecificationKey == qitem.SpecificationSort).Any())
                                                    {
                                                        var fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        if (fpkModel == null || fpkModel.ID <= 0)
                                                        {
                                                            fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        }
                                                        if (fpkModel == null || fpkModel.ID <= 0)
                                                        {
                                                            fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        }
                                                        if (fpkModel == null || fpkModel.ID <= 0)
                                                        {
                                                            fpkModel = freeShippingList.Where(x => qitem.CategoryIdList.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                                                        }
                                                        if (fpkModel != null && fpkModel.ID == fullNumPinkageModel.ID)
                                                        {
                                                            //是同一包邮规则里的
                                                            string Name = fullNumPinkageModel.Name;
                                                            if (fullNumPinkageModel.FullNumPinkage > 0)
                                                            {
                                                                Name += "：满" + fullNumPinkageModel.FullNumPinkage + "件包邮";
                                                            }
                                                            else if (fullNumPinkageModel.FullMoneyPinkage > 0)
                                                            {
                                                                Name += "：满" + fullNumPinkageModel.FullMoneyPinkage + "元包邮";
                                                            }
                                                            SatisfiedGoodsList2.Add(new FreeShippingGoodsDetail()
                                                            {
                                                                FreeShipping = fullNumPinkageModel.ID,
                                                                Name = Name,
                                                                GoodsId = qitem.GoodsId ?? 0,
                                                                SpecificationKey = qitem.SpecificationSort,
                                                                Number = qitem.Number ?? 0,
                                                                Money = qitem.NorGoodsMoney,
                                                                CategoryId = fullNumPinkageModel.CategoryId
                                                            });
                                                        }
                                                    }
                                                }
                                            }
                                            if (SatisfiedGoodsList2.Any())
                                            {
                                                //看是否满足包邮
                                                if (fullNumPinkageModel.FullNumPinkage > 0)
                                                {
                                                    if (SatisfiedGoodsList2.Sum(x => x.Number) >= fullNumPinkageModel.FullNumPinkage)
                                                    {
                                                        FreeShipping_Use = true;
                                                        SatisfiedGoodsList.AddRange(SatisfiedGoodsList2);
                                                    }
                                                }
                                                else if (fullNumPinkageModel.FullMoneyPinkage > 0)
                                                {
                                                    if (SatisfiedGoodsList2.Sum(x => x.Money) >= fullNumPinkageModel.FullMoneyPinkage)
                                                    {
                                                        FreeShipping_Use = true;
                                                        SatisfiedGoodsList.AddRange(SatisfiedGoodsList2);
                                                    }
                                                }
                                            }

                                            //看着商品是否包含在这里面
                                            if (SatisfiedGoodsList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).Any())
                                            {
                                                item.FreeShippingRemarks = SatisfiedGoodsList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault().Name;
                                            }
                                        }
                                    }
                                }
                            }
                            if (FreeShipping_Use == false)
                            {
                                int FreightId2 = gmodel.FreightId ?? 0;
                                if (gmodel.FreightId == 0)
                                {
                                    FreightId2 = DefFreightId;
                                }
                                if (FreightId2 > 0)
                                {
                                    var rulesModel = rulesList.Where(x => x.ID == FreightId2).FirstOrDefault();
                                    List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList2 = priceList.Where(x => x.RulesId == FreightId2).ToList();
                                    if (priceList2.Any())
                                    {
                                        var priceIds = priceList2.Select(x => x.ID).ToList();
                                        var regionList2 = regionList.Where(x => priceIds.Contains(x.RulesPriceId)).ToList();

                                        var regionModel = regionList2.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                                        if (regionModel != null)
                                        {
                                            var pmodel = priceList2.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                                            if (pmodel != null && rulesModel != null)
                                            {
                                                if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                                {
                                                    //按件计费
                                                    if (exNum <= pmodel.First)
                                                    {
                                                        Express = pmodel.FirstPrice;
                                                    }
                                                    else
                                                    {
                                                        if (pmodel.Second > 0)
                                                        {
                                                            if ((exNum - pmodel.First) % pmodel.Second == 0)
                                                            {
                                                                Express = pmodel.FirstPrice + ((exNum - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                            }
                                                            else
                                                            {
                                                                Express = pmodel.FirstPrice + ((exNum - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            Express = pmodel.FirstPrice;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    //重量计费
                                                    int TotalW = exNum * (item.GoodsWeight ?? 0);
                                                    if (TotalW <= pmodel.First)
                                                    {
                                                        Express = pmodel.FirstPrice;
                                                    }
                                                    else
                                                    {
                                                        if (pmodel.Second > 0)
                                                        {
                                                            if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                                            {
                                                                Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                                            }
                                                            else
                                                            {
                                                                Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            Express = pmodel.FirstPrice;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                TExpress = Express;
                                if (exNum != item.Number)
                                {
                                    Express = Math.Round(Express * (item.Number ?? 0) / exNum, 2, MidpointRounding.AwayFromZero);
                                    if (!ExpressGoodsId.Contains(item.GoodsId ?? 0))
                                    {
                                        ExpressGoodsId.Add(item.GoodsId ?? 0);
                                    }
                                    else
                                    {
                                        ExpressIsReckon = true;
                                    }
                                }
                            }
                        }
                    }
                    if (!ExpressIsReckon)
                    {
                        TotalExpress += TExpress;
                    }
                    #endregion
                    item.FreightMoney = Express;

                    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));
                        }
                    }

                    #region 佣金抵扣
                    item.Final_Price -= (item.DeductionCommission ?? 0);
                    item.SmallShopsCostPrice -= (item.DeductionCommission ?? 0);//微店价格也需要减去
                    #endregion

                    #region 储值卡使用
                    if (demodel.Use_Deposit_Id > 0 && depositModel.SurplusPrice > 0)
                    {
                        if ((item.Final_Price ?? 0) > depositModel.SurplusPrice)
                        {
                            item.DepositMoney = depositModel.SurplusPrice;
                            depositModel.SurplusPrice = 0;
                            TotalDepositMoney += item.DepositMoney;
                            //item.Final_Price = (item.Final_Price ?? 0) - depositModel.SurplusPrice;
                        }
                        else
                        {
                            item.DepositMoney = (item.Final_Price ?? 0);
                            depositModel.SurplusPrice -= (item.Final_Price ?? 0);
                            TotalDepositMoney += item.DepositMoney;
                            //item.Final_Price = 0;
                        }
                        if ((item.FreightMoney ?? 0) > depositModel.SurplusPrice)
                        {
                            item.DepositFreightMoney = depositModel.SurplusPrice;
                            depositModel.SurplusPrice = 0;
                            TotalDepositMoney += item.DepositFreightMoney;
                            //item.FreightMoney = (item.FreightMoney ?? 0) - depositModel.SurplusPrice;
                        }
                        else
                        {
                            item.DepositFreightMoney = (item.FreightMoney ?? 0);
                            depositModel.SurplusPrice -= (item.FreightMoney ?? 0);
                            TotalDepositMoney += item.DepositFreightMoney;
                            //item.FreightMoney = 0;
                        }
                        //item.Final_Price -= (item.DepositMoney + item.DepositFreightMoney);
                        //item.SmallShopsCostPrice -= (item.DepositMoney + item.DepositFreightMoney);//微店价格也需要减去
                    }
                    #endregion
                }
            }
            if (demodel.FreightMoney != TotalExpress)
            {
                return ApiResult.Failed("运费不正确");
            }
            if (CouponsMoney != demodel.CouponMoney)
            {
                return ApiResult.Failed("优惠金额计算有误");
            }
            if (DeductionCommission != (demodel.DeductionCommission ?? 0))
            {
                return ApiResult.Failed("抵扣佣金不正确");
            }
            if (OldDepositMoney > (TotalMoney + TotalExpress - DeductionCommission))
            {
                //为了防止运费出现四舍五入不平均问题，只要全额抵扣的就重新赋下值
                TotalDepositMoney = (TotalMoney + TotalExpress - DeductionCommission);
                depositModel.SurplusPrice = OldDepositMoney - TotalDepositMoney;
            }
            if (TotalDepositMoney != demodel.DepositMoney)
            {
                return ApiResult.Failed("储值卡抵扣金额有误");
            }

            if (demodel.Income != (TotalMoney + TotalExpress - DeductionCommission - TotalDepositMoney))//商品最终金额+ 运费-购买抵扣金额-储值卡抵扣金额
            {
                return ApiResult.Failed("订单合计金额不正确");
            }
            demodel.PreferPrice = TotalMoney + CouponsMoney;

            #region 手续费计算
            decimal ServiceCharge = Convert.ToDecimal(Config.SettlementRate) / 100;
            if (demodel.VersionSource == 1 || demodel.OrderEduType > 0)
            {
                ServiceCharge = Convert.ToDecimal(Config.EduSettlementRate) / 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;
                demodel.VersionSource ??= 0;//默认商城
                if (demodel.VersionSource == 1)
                {
                    //教育端下单 初始化参数
                    //demodel.PaymentWay = OrderPaymentTypeEnum.OfflinePay;
                    //demodel.OrderStatus = OrderStatusEnum.Completed;
                    //demodel.PaymentTime = DateTime.Now;
                    //demodel.DeliveryTime = DateTime.Now;
                    //demodel.ReceivingTime = DateTime.Now;
                    //demodel.FinishTime = DateTime.Now;
                }
                if (demodel.Income == 0 && demodel.DepositMoney > 0)
                {
                    //使用储值卡全额抵扣了，无需再次付款
                    demodel.PaymentWay = OrderPaymentTypeEnum.PayCards;
                    demodel.OrderStatus = OrderStatusEnum.WaitSendGoods;
                    demodel.PaymentTime = DateTime.Now;
                }
                if (demodel.Income == 0 && demodel.Use_Integral == 1 && TotalIntegralMoney > 0 && umodel.CustomerChildrenId > 0) {
                    //使用 积分抵扣全额，无需再次付款
                    demodel.OrderStatus = OrderStatusEnum.WaitSendGoods;
                    demodel.PaymentTime = 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, SatisfiedGoodsList);
                    #region 优惠抵扣
                    //用户订单数增加
                    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)
                    {
                        if (umodel.CustomerChildrenId > 0)
                        {//进入erp同业积分更新
                            try
                            {
                                customer_IntegralRepository.Insert(new Model.Entity.Customer.RB_Customer_Integral()
                                {
                                    Id = 0,
                                    CustomerId = umodel.CustomerId,
                                    CustomerChildrenId = umodel.CustomerChildrenId,
                                    GroupId = 2,
                                    OrderId = OrderId,
                                    TCID = 0,
                                    OrderType = 2,
                                    IsDeduction = 1,
                                    IntegralNum = 0 - TotalIntegralNumber,
                                    CreateTime = DateTime.Now,
                                    CustomerType = 1,
                                    Description = "赞羊订单使用积分抵扣" + TotalIntegralMoney + "元，订单号：" + demodel.OrderNo,
                                    MallCommission = demodel.DetailList.Sum(x => x.CommissionPrice)
                                });
                                //更新同行积分数
                                customer_IntegralRepository.UpdateCustomerIntegral(umodel.CustomerId, TotalIntegralNumber);
                            }
                            catch {}
                        }
                        else
                        {
                            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);
                    //使用储值卡
                    if (demodel.Use_Deposit_Id > 0 && TotalDepositMoney > 0)
                    {
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Member_DepositBuy_Extend.SurplusPrice),depositModel.SurplusPrice}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_DepositBuy_Extend.Id),
                                  FiledValue=demodel.Use_Deposit_Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool depflag = member_DepositBuyRepository.Update(keyValues1, wheres1, trans);
                        if (depflag)
                        {
                            //记录储值卡流水
                            member_DepositBalanceRepository.Insert(new RB_Member_DepositBalance()
                            {
                                Id = 0,
                                UserId = umodel.Id,
                                Balance = OldDepositMoney,
                                CouponIco = depositModel.CouponIco,
                                CreateDate = DateTime.Now,
                                DepositPrice = depositModel.DepositPrice,
                                MallBaseId = umodel.MallBaseId,
                                MergeType = 3,
                                Name = depositModel.Name,
                                NewDepositBuyId = 0,
                                OldDepositBuyId = 0,
                                Remarks = "订单" + demodel.OrderNo + "使用储值卡抵扣" + TotalDepositMoney,
                                SalePrice = depositModel.SalePrice,
                                Status = 0,
                                Surplus = depositModel.SurplusPrice,
                                TenantId = umodel.TenantId,
                                Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend
                            }, trans);
                        }
                    }
                    #endregion
                    #region 购物下线
                    //来自购物车的话  需清除购物车数据
                    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);
                    }
                    #endregion
                    #region 订单返佣
                    //任务执行返佣  失败查看日志，手动返佣(空闲可增加手动返佣接口)
                    if (demodel.User_Coupon_Id > 0 && demodel.CouponMoney > 0)
                    {
                        demodel.CouponDestription = "使用" + (IsCommissionCoupons ? "通用" : "店铺") + "优惠券抵扣";
                    }
                    //2025-05-30 ld erp同业绑定人员 使用积分抵扣 不返佣， 佣金由积分承担公司抵扣
                    if (!(umodel.CustomerChildrenId > 0 && demodel.Use_Integral == 1 && TotalIntegralNumber > 0))
                    {
                        Task.Run(() => InsertOrderCommission(demodel, umodel, GoodsIds, OrderId));
                    }
                    #endregion
                    //记录日志
                    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();
                //任务执行 订单记录当前用户的所有上级
                Task.Run(() => SaveOrderUserAllParent(demodel.UserId ?? 0, OrderId));
                //进阶小课堂回调
                if (demodel.TenantId == 27 && demodel.OrderStatus == OrderStatusEnum.Completed)
                {

                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            string url = Common.Config.JJSWAdminApi + "/api/Third/SynchronousMallOrder";
                            var postData =
                                new
                                {
                                    Msg = new
                                    {
                                        OrderId = OrderId
                                    }
                                };
                            string str = HttpHelper.HttpPost(url, Common.Plugin.JsonHelper.Serialize(postData));
                            Common.Plugin.LogHelper.WriteInfo("SetAppletGoodsOrderInfo_更新小课堂订单::" + OrderId + " Result::" + str);
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "SetAppletGoodsOrderInfo_更新小课堂订单::" + OrderId);
                        }
                    }, TaskCreationOptions.LongRunning);
                }
                return ApiResult.Success("", new { OrderId, demodel.OrderStatus });
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetAppletGoodsOrderInfo");
                goods_OrderRepository.DBSession.Rollback("SetAppletGoodsOrderInfo");
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 订单记录当前用户的所有上级
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        public bool SaveOrderUserAllParent(int UserId, int OrderId)
        {
            if (OrderId <= 0 || UserId <= 0)
            {
                return false;
            }
            try
            {
                string parentIds = member_UserRepository.GetMemberParentIdStr(UserId);
                string distributorIds = "";
                int eduUserId = 0;
                if (!string.IsNullOrEmpty(parentIds))
                {
                    //查询用户是否是分销商
                    var dlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = parentIds, AuditStatus = DistributorAuditStatusEnum.Audited });
                    List<int> pList = JsonConvert.DeserializeObject<List<int>>("[" + parentIds + "]");
                    foreach (var item in pList)
                    {
                        var dmodel = dlist.Where(x => x.UserId == item).FirstOrDefault();
                        if (dmodel != null)
                        {
                            distributorIds += item + ",";
                        }
                    }
                    if (!string.IsNullOrEmpty(distributorIds))
                    {
                        distributorIds = distributorIds[0..^1];
                    }

                    var userList = member_UserRepository.GetList(new RB_Member_User_Extend { UserIds = parentIds });
                    if (userList != null && userList.Any(x => x.SuperiorId == 0))
                    {
                        int userId = userList.Where(x => x.SuperiorId == 0).FirstOrDefault()?.Id ?? 0;
                        var eduSellModel = GetEducationSellBaseInfo(new RB_Education_EduSell_Extend { UserId = userId }).FirstOrDefault();
                        if (eduSellModel != null && eduSellModel.Id > 0)
                        {
                            eduUserId = eduSellModel.EduSellId;
                        }
                        else
                        {
                            eduUserId = Convert.ToInt32(Config.EduXuZongId ?? "2602");
                        }

                    }
                    else
                    {
                        eduUserId = Convert.ToInt32(Config.EduXuZongId ?? "2602");
                    }
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_Order_Extend.UserTree),parentIds },
                     { nameof(RB_Education_Consult_Extend.EduUserId),eduUserId },
                    { nameof(RB_Goods_Order_Extend.DistributorTree),distributorIds }
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                          FiledValue=OrderId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = goods_OrderRepository.Update(keyValues, wheres);
                return flag;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// ERP修改商品订单状态
        /// </summary>
        /// <param name="extModel"></param>
        /// <param name="tradeModel"></param>
        /// <returns></returns>
        public bool UpdateERPGoodsOrderInfoModule(RB_Goods_Order_Extend extModel, RB_Goods_Online_Trade_Extend tradeModel, int FinanceId = 0)
        {
            bool flag;
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Goods_Order_Extend.MerchantsNo),extModel.MerchantsNo },
                {nameof(RB_Goods_Order_Extend.OrderStatus),extModel.OrderStatus },
                {nameof(RB_Goods_Order_Extend.PaymentTime),extModel.PaymentTime },
                {nameof(RB_Goods_Order_Extend.Fee),extModel.Fee}
            };
            var detailsList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = extModel.OrderId });
            if (detailsList != null && detailsList.Count > 0)
            {
                foreach (var item in detailsList)
                {
                    RB_ECFinanceId_Relation rModel = new RB_ECFinanceId_Relation()
                    {
                        FinanceId = FinanceId,
                        CreateDate = DateTime.Now,
                        ECOrderDetailId = item.Id,
                        ECOrderId = extModel.OrderId,
                        Status = Common.Enum.DateStateEnum.Normal
                    };
                    flag = new RB_ECFinanceId_RelationRepository().Insert(rModel) > 0;
                }
            }
            flag = goods_OrderRepository.Update(fileds, new WhereHelper(nameof(RB_Goods_Order_Extend.OrderId), extModel.OrderId));
            if (flag)
            {
                flag = goods_Online_TradeRepository.Insert(tradeModel) > 0;
            }
            return flag;
        }

        /// <summary>
        /// 司导下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult SetAppletSDGoodsOrderInfo(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("您在黑名单状态无法下单，请联系管理员核实");
            }
            List<int> disList = new List<int>
            {
                demodel.Province ?? 0,
                demodel.City ?? 0,
                demodel.District ?? 0
            };

            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 InsuranceMoney = 0;//保险金额
            int seat_number = 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
            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 }, 1);
                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 mallbaseModel = mallBaseRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_MallBase_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                var guidebaseModel = guideCar_BaseRepository.GetList(new Model.Extend.GuideCar.RB_GuideCar_Base_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();

                #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)
                {
                    seat_number = item.Number ?? 0;
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1 || gmodel.GoodsClassify != 1)
                    {
                        return ApiResult.Failed("有商品不存在或者商品已失效");
                    }
                    if (gmodel.CarType != demodel.CarType)
                    {
                        return ApiResult.Failed("商品服务类型不一致");
                    }
                    if (gmodel.CarType != GuideCarGoodsTypeEnum.Line)
                    {
                        item.Number = 1;//设置为单人  用于计算一口价
                    }
                    int uday = Convert.ToInt32((gmodel.UseDay ?? 0).Equals(Convert.ToDecimal(0.5)) ? 1 : (gmodel.UseDay ?? 0));
                    if (demodel.TripSTime.Value.AddDays(uday - 1).ToString("yyyy-MM-dd") != demodel.TripETime.Value.ToString("yyyy-MM-dd"))
                    {
                        return ApiResult.Failed("预定日期与商品使用天数不一致");
                    }
                    item.OrderType = OrderTypeEnum.SDGoods;
                    item.CarType = gmodel.CarType;
                    item.UseDay = gmodel.UseDay;
                    item.TripSTime = demodel.TripSTime;
                    item.TripETime = demodel.TripETime;
                    item.IsSpell = gmodel.IsSpell;
                    item.GoodsRideNum = gmodel.RideNum;
                    item.SiteId = gmodel.SiteId;
                    item.GuideId = gmodel.GuideId;
                    item.CarId = gmodel.CarId;
                    item.CarColorId = gmodel.CarColorId;
                    item.CarNumber = gmodel.CarNumber;
                    item.LineName = gmodel.LineName;
                    item.Specification = "[]";
                    item.SpecificationSort = "0";

                    var tdlist = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = item.GoodsId ?? 0, StartTime = item.TripSTime.Value.ToString("yyyy-MM-dd"), EndTime = item.TripETime.Value.ToString("yyyy-MM-dd") });
                    var targetList = tdlist.Where(x => x.IsReserve == 1 && x.Date == Convert.ToDateTime(demodel.TripSTime.Value.ToString("yyyy-MM-dd"))).ToList();
                    if (gmodel.AdvanceDay > 0)
                    {
                        DateTime Mindate = Convert.ToDateTime(DateTime.Now.AddDays(gmodel.AdvanceDay ?? 0).ToString("yyyy-MM-dd"));
                        targetList = targetList.Where(x => x.Date >= Mindate).ToList();
                    }
                    if (!targetList.Any())
                    {
                        return ApiResult.Failed("不在预定时间范围，无法下单");
                    }
                    if (gmodel.CarType == GuideCarGoodsTypeEnum.Line && gmodel.IsSpell == 1)
                    {
                        var targetModel = targetList.FirstOrDefault();
                        if ((gmodel.RideNum ?? 0) - (targetModel.ReserveNum) < seat_number)
                        {
                            return ApiResult.Failed("商品剩余座位数不足，剩余：" + ((gmodel.RideNum ?? 0) - (targetModel.ReserveNum)));
                        }
                    }
                    else
                    {
                        foreach (var qitem in tdlist)
                        {
                            if (qitem.IsReserve == 2)
                            {
                                return ApiResult.Failed(qitem.Date.Value.ToString("yyyy-MM-dd") + "已被预定，无法下单");
                            }
                            //验证座位数量
                            if ((gmodel.RideNum ?? 0) - (qitem.ReserveNum) < seat_number)
                            {
                                return ApiResult.Failed(qitem.Date.Value.ToString("yyyy-MM-dd") + "剩余座位数不足，剩余：" + ((gmodel.RideNum ?? 0) - (qitem.ReserveNum)));
                            }
                        }
                    }

                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();

                    item.CommissionPrice = gmodel.Commission;// 粉象 返佣金额
                    item.CostMoney = gmodel.CostPrice ?? 0;

                    item.ProductCode = gmodel.GoodsNumbers;
                    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.NorGoodsMoney = item.Final_Price ?? 0;//用于计算 运费的  202-08-05 ld

                    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

                    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;
                        }
                    }
                }

                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;
                    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.FreightMoney = 0;
                    item.InsuranceMoney = (guidebaseModel?.SalePrice ?? 0) * seat_number;
                    item.InsuranceCostMoney = (guidebaseModel?.CostPrice ?? 0) * seat_number;
                    InsuranceMoney += (item.InsuranceMoney ?? 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));
                        }
                    }

                    if (gmodel.CarType != GuideCarGoodsTypeEnum.Line)
                    {
                        item.Number = seat_number;
                    }
                }
            }
            if (CouponsMoney != demodel.CouponMoney)
            {
                return ApiResult.Failed("优惠金额计算有误");
            }
            //验证总额
            if (demodel.Income != TotalMoney + InsuranceMoney)
            {
                return ApiResult.Failed("订单合计金额不正确");
            }
            demodel.PreferPrice = TotalMoney + CouponsMoney + InsuranceMoney;

            #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;
                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;
                        demodel.CompanyId = pUserId;
                    }
                    #endregion
                    //插入订单明细+ 商品库存更新 
                    InsertOrderDetail(demodel, trans, OrderId, new List<FreeShippingGoodsDetail>(), true);

                    //用户订单数增加
                    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);

                    //下线
                    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();
            }
        }

        /// <summary>
        /// 线下服务订单
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool SetAppletOfflineGoodsOrderModule(RB_Goods_Order_Extend demodel, out string message)
        {
            message = "";
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                message = "用户不存在";
                return false;
            }
            if (demodel.SmallShopsId == 0)
            {
                demodel.SmallShopsId = umodel.SmallShopId;
            }
            if (umodel.Blacklist == 1)
            {
                message = "您在黑名单状态无法下单，请联系管理员核实";
                return false;
            }

            decimal TotalMoney = 0;
            decimal TotalDepositMoney = 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())
                                    {
                                        message = "优惠券不存在，请核实后再试";
                                        return false;
                                    }
                                }
                            }
                            if (dcList.Where(x => x.SmallShopId > 0).Any())
                            {
                                IsCommissionCoupons = false;
                            }
                        }
                    }
                }
            }
            #endregion

            #region 套餐卡初始化
            List<RB_Reserve_MemberCoupon_Extend> eList = new List<RB_Reserve_MemberCoupon_Extend>();
            List<RB_Reserve_Coupon_Extend> deList = new List<RB_Reserve_Coupon_Extend>();
            List<RB_Reserve_CouponProduct_Extend> edcpList = new List<RB_Reserve_CouponProduct_Extend>();
            if (demodel.Use_Education_Id > 0)
            {
                if (demodel.User_Coupon_Id > 0)
                {
                    message = "套餐卡与优惠券不能同时使用";
                    return false;
                }
                if (demodel.Use_Integral > 0)
                {
                    message = "套餐卡与积分抵扣不能同时使用";
                    return false;
                }
                eList = reserve_MemberCouponRepository.GetList(new RB_Reserve_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)
                    {
                        message = "套餐卡剩余次数不足";
                        return false;
                    }
                    string cIds = string.Join(",", eList.Select(x => x.CouponId).Distinct());
                    deList = reserve_CouponRepository.GetDiscountCouponList(new RB_Reserve_Coupon_Extend()
                    {
                        CouponIds = cIds,
                        TenantId = demodel.TenantId,
                        MallBaseId = demodel.MallBaseId,
                        StoreId = demodel.StoresId,
                    }, true);
                    edcpList = reserve_CouponProductRepository.GetListByDiscountCouponIds(new RB_Reserve_Coupon_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, cIds, true);
                    if (deList.Any())
                    {
                        foreach (var item in deList)
                        {
                            if (!string.IsNullOrWhiteSpace(item.StoreIds))
                            {
                                if (item.StoreIds != "0")
                                {
                                    bool isGrantCoupon = false;
                                    foreach (var itemStoreId in item.StoreIds.Split(","))
                                    {
                                        if (Convert.ToInt32(itemStoreId) > 0)
                                        {
                                            if (Convert.ToInt32(itemStoreId) == demodel.StoresId)
                                            {
                                                isGrantCoupon = true;
                                            }
                                        }
                                    }
                                    if (!isGrantCoupon)
                                    {
                                        message = "领取套餐卡不属于当前门店";
                                        return false;
                                    }
                                }
                            }
                        }
                        foreach (var item in eList)
                        {
                            if (item.CouponId > 0)
                            {
                                if (!deList.Where(x => x.ID == item.CouponId).Any())
                                {
                                    message = "套餐卡不存在，请核实后再试";
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            #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 }, 3);
                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)
                    {
                        message = "有商品不存在或者商品已失效";
                        return false;
                    }
                    if (gmodel.GoodsClassify != 3)
                    {
                        message = "有非线下服务类商品";
                        return false;
                    }
                    TotalDepositMoney += gmodel.DepositMoney * (item?.Number ?? 0);
                    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)
                            {
                                message = "优惠卷不存在，亲核实后再试";
                                return false;
                            }
                            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)
                            {
                                message = "优惠卷不存在，亲核实后再试";
                                return false;
                            }
                            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 = OrderTypeEnum.OfflineService;
                    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)
                    {
                        message = "优惠卷不存在，亲核实后再试";
                        return false;
                    }
                    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;
                    item.GoodServiceTime = gmodel.ServiceTime;
                    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 ?? 0) != EducationMoney)
            {
                message = "套餐卡抵扣金额不正确";
                return false;
            }
            if (CouponsMoney != (demodel?.CouponMoney ?? 0))
            {
                message = "优惠金额计算有误";
                return false;
            }

            if (demodel.PaymentWay == OrderPaymentTypeEnum.OnlinePayment)
            {
                //验证总额
                if (demodel.Income != (TotalMoney - EducationMoney))
                {
                    message = "订单合计金额不正确";
                    return false;
                }
            }
            if (demodel.PaymentWay == OrderPaymentTypeEnum.PayDeposit)
            {
                //验证总额
                if (demodel.Income != (TotalDepositMoney - EducationMoney))
                {
                    message = "订单合计金额不正确";
                    return false;
                }
            }
            if (demodel.PaymentWay == OrderPaymentTypeEnum.OfflinePay)
            {
                demodel.OrderStatus = OrderStatusEnum.WaitReceiving;
            }
            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
            try
            {
                Random R = new Random();
                int Rstr = R.Next(111, 999);
                demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                if (demodel?.PaymentWay == null)
                {
                    demodel.PaymentWay = OrderPaymentTypeEnum.OnlinePayment;//先默认在线支付
                }
                demodel.Remark ??= "";
                demodel.ApplyForCancelStatus ??= 0;
                if (demodel.Income == 0)
                {
                    demodel.OrderStatus = OrderStatusEnum.WaitReceiving;
                    demodel.PaymentTime = DateTime.Now;
                    demodel.DeliveryTime = DateTime.Now;
                    demodel.ReceivingTime = DateTime.Now;
                    demodel.FinishTime = DateTime.Now;
                }
                int OrderId = goods_OrderRepository.Insert(demodel);
                if (OrderId > 0)
                {
                    demodel.OrderId = OrderId;
                    #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, null, 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);
                            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
                        });
                    }

                    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);

                    #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
                        });
                        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);
                        }
                    }
                    #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);
                    }

                    //任务执行返佣  失败查看日志，手动返佣(空闲可增加手动返佣接口)
                    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
                    });
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetAppletOfflineGoodsOrderModule");
                return false;
            }
        }

        /// <summary>
        /// 修改订单线下服务人员
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="ServicepersonalId"></param>
        /// <returns></returns>
        public bool SetOfflineOrderServicepersionModule(int OrderId, int ServicepersonalId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Goods_OrderDetail_Extend.ServicepersonalId),ServicepersonalId }
            };
            return goods_OrderDetailRepository.Update(fileds, new WhereHelper(nameof(RB_Goods_OrderDetail_Extend.OrderId), OrderId));
        }

        /// <summary>
        /// 赠送粉象等级
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="umodel"></param>
        /// <param name="OrderId"></param>
        private void InsertPresentFXGrade(RB_Goods_Order_Extend demodel, int UserId, int OrderId)
        {
            var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if ((basicModel?.IsEnableFXGrade ?? 2) == 1)
            {
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                if (disModel == null)
                {
                    LogHelper.Write("该用户分销商等级不存在，UserId:" + UserId);
                }
                if (demodel.DetailList.Where(x => x.PresentFXGrade > 0).Any() && disModel != null)
                {
                    var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var VIPModel = FXList.Where(x => x.IsGuest == 3).FirstOrDefault();
                    List<int> GradeList = new List<int>();//等级列表
                    int VIPMonths = 0;//vip赠送月份
                    foreach (var item in demodel.DetailList)
                    {
                        if (item.PresentFXGrade > 0)
                        {
                            //查询是否有申请退款
                            var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.Id, Type = 1, MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId });
                            if (!afterSaleList.Any())
                            {
                                //有赠送粉象等级
                                GradeList.Add(item.PresentFXGrade ?? 0);
                                if (item.PresentFXGrade == (VIPModel?.Id ?? 0))
                                {
                                    VIPMonths += (item.PresentFXMonth ?? 0) * (item.Number ?? 0);
                                }
                            }
                        }
                    }
                    if (GradeList.Any())
                    {
                        //判断等级 取最高级别
                        int MaxGradeId = 0;
                        int MaxGrade = 0;
                        if (GradeList.Distinct().Count() > 1)
                        {
                            //说明有两种级别  取最高的
                            foreach (var item in GradeList.Distinct())
                            {
                                var fxmodel = FXList.Where(x => x.Id == item).FirstOrDefault();
                                MaxGrade = (fxmodel.Grade ?? 0) > MaxGrade ? (fxmodel.Grade ?? 0) : MaxGrade;
                            }
                            MaxGradeId = FXList.Where(x => x.Grade == MaxGrade).FirstOrDefault()?.Id ?? 0;
                        }
                        else
                        {
                            MaxGradeId = GradeList.FirstOrDefault();
                            var fxmodel = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault();
                            MaxGrade = (fxmodel.Grade ?? 0) > MaxGrade ? (fxmodel.Grade ?? 0) : MaxGrade;
                        }
                        var oldGrade = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault()?.Grade ?? 0;

                        try
                        {
                            bool UpdateGrade = false;
                            if (MaxGradeId > 0 && MaxGrade >= oldGrade && MaxGradeId == (VIPModel?.Id ?? 0))
                            {
                                UpdateGrade = true;
                                string MaxGradeName = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault()?.GradeName ?? "";
                                //vip 
                                var VipExpiryDate = DateTime.Now.AddMonths(VIPMonths);
                                if (VIPMonths >= 1)
                                {
                                    VipExpiryDate = Convert.ToDateTime(VipExpiryDate.AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
                                }
                                if (MaxGrade == oldGrade && disModel.VipExpiryDate.HasValue)
                                {
                                    if (disModel.VipExpiryDate > DateTime.Now)
                                    {
                                        VipExpiryDate = disModel.VipExpiryDate.Value.AddMonths(VIPMonths);
                                    }
                                }
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                    {
                                        { nameof(RB_Distributor_Info_Extend.FXGradeId), MaxGradeId },
                                        { nameof(RB_Distributor_Info_Extend.VipExpiryDate), VipExpiryDate }
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disModel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool gflag = distributor_InfoRepository.Update(keyValues1, wheres1);
                                if (gflag)
                                {
                                    //新增vip赠送记录表
                                    Random R1 = new Random();
                                    int Rstr1 = R1.Next(111, 999);
                                    string OrderNo1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr1;
                                    vip_BuyRepository.Insert(new Model.Entity.User.RB_Vip_Buy()
                                    {
                                        CreateDate = DateTime.Now,
                                        ExpiryDate = VipExpiryDate,
                                        GradeId = MaxGradeId,
                                        GradeName = MaxGradeName,
                                        Id = 0,
                                        MallBaseId = demodel.MallBaseId,
                                        MerchantsNo = "",
                                        Money = 0,
                                        OrderNo = OrderNo1,
                                        PayState = 1,
                                        PayTime = null,
                                        PayWay = 1,
                                        Remark = "下单赠送，订单号：" + demodel.OrderNo + "(" + OrderId + ")",
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UserId = UserId
                                    });
                                }
                            }
                            else if (MaxGradeId > 0 && MaxGrade > oldGrade)
                            {
                                UpdateGrade = true;
                                string MaxGradeName = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault()?.GradeName ?? "";
                                //比vip高级
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                    {
                                        { nameof(RB_Distributor_Info_Extend.FXGradeId), MaxGradeId }
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disModel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool gflag = distributor_InfoRepository.Update(keyValues1, wheres1);
                                if (gflag)
                                {
                                    //新增vip赠送记录表
                                    Random R1 = new Random();
                                    int Rstr1 = R1.Next(111, 999);
                                    string OrderNo1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr1;
                                    vip_BuyRepository.Insert(new Model.Entity.User.RB_Vip_Buy()
                                    {
                                        CreateDate = DateTime.Now,
                                        ExpiryDate = null,
                                        GradeId = MaxGradeId,
                                        GradeName = MaxGradeName,
                                        Id = 0,
                                        MallBaseId = demodel.MallBaseId,
                                        MerchantsNo = "",
                                        Money = 0,
                                        OrderNo = OrderNo1,
                                        PayState = 1,
                                        PayTime = null,
                                        PayWay = 1,
                                        Remark = "下单赠送，订单号：" + demodel.OrderNo + "(" + OrderId + ")",
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UserId = UserId
                                    });
                                }
                            }
                            if (UpdateGrade)
                            {
                                new UserCommonModule().FXAutoUpgradeUserDistributorGrade(UserId, demodel.TenantId, demodel.MallBaseId);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "InsertPresentFXGrade赠送粉象分销等级失败，OrderId：" + OrderId);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 其他付款
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetAppletGoodsOrderOtherPay(int orderId, int type, AppletUserInfo userInfo)
        {
            var omodel = goods_OrderRepository.GetEntity(orderId);
            if (omodel == null)
            {
                return "订单不存在，请核实后再试";
            }
            var umodel = member_UserRepository.GetEntity(userInfo.UserId);

            var mallModel = mallBaseRepository.GetEntity(userInfo.MallBaseId);
            if (!string.IsNullOrEmpty(mallModel?.PayWay))
            {
                if (type == 1)
                {
                    if (!("," + mallModel.PayWay + ",").Contains("," + (int)OrderPaymentTypeEnum.OfflinePayment + ","))
                    {
                        return "暂不支持该支付方式";
                    }
                }
                else if (type == 2)
                {
                    if (!("," + mallModel.PayWay + ",").Contains("," + (int)OrderPaymentTypeEnum.YEPayment + ","))
                    {
                        return "暂不支持该支付方式";
                    }
                }
            }
            else
            {
                return "暂不支持该支付方式";
            }
            if (type == 1)
            {
                //更新订单信息
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_Order_Extend.OrderStatus),Common.Enum.Goods.OrderStatusEnum.WaitSendGoods},
                    { nameof(RB_Goods_Order_Extend.PaymentWay),Common.Enum.Goods.OrderPaymentTypeEnum.OfflinePayment}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                          FiledValue=orderId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = goods_OrderRepository.Update(keyValues, wheres);
                if (flag)
                {
                    return "";
                }
                return "支付失败，请联系管理员";
            }
            else
            {
                if ((omodel.Income ?? 0) > (umodel.Balance ?? 0))
                {
                    return "您当前余额不足：" + (umodel.Balance ?? 0);
                }
                //更新订单信息
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_Order_Extend.OrderStatus),Common.Enum.Goods.OrderStatusEnum.WaitSendGoods},
                    { nameof(RB_Goods_Order_Extend.PaymentTime),DateTime.Now},
                    { nameof(RB_Goods_Order_Extend.PaymentWay),Common.Enum.Goods.OrderPaymentTypeEnum.YEPayment}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                          FiledValue=orderId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = goods_OrderRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //更新用户余额
                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                        { nameof(RB_Member_User_Extend.Balance),(umodel.Balance??0)-(omodel.Income??0)}
                    };
                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Member_User_Extend.Id),
                              FiledValue=userInfo.UserId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    bool flag2 = member_UserRepository.Update(keyValues2, wheres2);
                    if (flag2)
                    {
                        //写入余额日志
                        member_BalanceRepository.Insert(new Model.Entity.User.RB_Member_Balance()
                        {
                            UserId = userInfo.UserId,
                            Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
                            Balance = (omodel.Income ?? 0),
                            Image = 0,
                            Description = "余额支付订单：" + omodel.OrderNo + "(id " + omodel.OrderId + ")",
                            Remarks = "",
                            PlatformType = omodel.OrderSource,
                            CreateDate = DateTime.Now,
                            Id = 0,
                            MallBaseId = omodel.MallBaseId,
                            TenantId = omodel.TenantId
                        });
                    }
                    //下线
                    if (umodel.DownlineCondition == Common.Enum.User.DistrbutorReferralsEnum.SCFK && 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);
                    }
                    return "";
                }
                return "支付失败，请联系管理员";
            }
        }

        /// <summary>
        /// 初始化返佣
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool SetAppletOrderCommissionInitialize(int orderId, int userId = 0)
        {
            var demodel = goods_OrderRepository.GetEntity<RB_Goods_Order_Extend>(orderId);
            if (demodel == null)
            {
                return false;
            }
            userId = demodel.UserId ?? 0;
            var umodel = member_UserRepository.GetEntity(userId);
            if (umodel == null)
            {
                return false;
            }


            var detList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderId });
            demodel.DetailList = detList;
            string GoodsIds = "";
            if (demodel.DetailList.Any())
            {
                GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        return false;
                    }

                    item.SeparateDistribution = gmodel.SeparateDistribution;
                    item.SeparateDistributionType = gmodel.SeparateDistributionType;
                    item.SeparateDistributionMoneyType = gmodel.SeparateDistributionMoneyType;
                    item.IntegralPresent = gmodel.IntegralPresent;
                    item.IntegralPresentType = gmodel.IntegralPresentType;

                    item.CommissionPrice = gmodel.Commission;// 粉象 返佣金额
                    item.CostMoney = (gmodel.IsCustomSpecification == 2) ? (gmodel.CostPrice ?? 0) : (speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault()?.CostMoney ?? 0);//gmodel.CostPrice ?? 0;

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

                    if (!string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        item.CommissionPrice = speciPModel?.Commission ?? 0;
                    }
                }
            }

            InsertOrderCommission(demodel, umodel, GoodsIds, orderId);
            return true;
        }

        /// <summary>
        /// 初始化返佣
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string SetOrderCommissionInitialize(int orderId)
        {
            var demodel = goods_OrderRepository.GetEntity<RB_Goods_Order_Extend>(orderId);
            if (demodel == null)
            {
                return "订单不存在，请核实后再试";
            }
            int userId = demodel.UserId ?? 0;
            var umodel = member_UserRepository.GetEntity(userId);
            if (umodel == null)
            {
                return "用户不存在，请核实后再试";
            }

            var shopcList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { MallBaseId = demodel.MallBaseId, OrderId = demodel.OrderId });
            if (shopcList.Any())
            {
                return "有微店返佣，暂联系管理员处理";
            }

            var commissionList = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { MallBaseId = demodel.MallBaseId, OrderId = demodel.OrderId });
            if (commissionList.Any())
            {
                if (commissionList.Where(x => x.CommissionState == 2).Any())
                {
                    return "该订单已返佣，无法重置返佣数据";
                }
            }
            else
            {
                return "历史返佣不存在，请联系管理员处理";
            }
            //删除原返佣记录
            goods_OrderCommissionRepository.DeleteBatch(commissionList);

            var detList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderId });
            demodel.DetailList = detList;
            string GoodsIds = "";
            if (demodel.DetailList.Any())
            {
                GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        return "有商品状态不正确";
                    }

                    item.SeparateDistribution = gmodel.SeparateDistribution;
                    item.SeparateDistributionType = gmodel.SeparateDistributionType;
                    item.SeparateDistributionMoneyType = gmodel.SeparateDistributionMoneyType;
                    item.IntegralPresent = gmodel.IntegralPresent;
                    item.IntegralPresentType = gmodel.IntegralPresentType;

                    item.CommissionPrice = gmodel.Commission;// 粉象 返佣金额
                    item.CostMoney = (gmodel.IsCustomSpecification == 2) ? (gmodel.CostPrice ?? 0) : (speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault()?.CostMoney ?? 0);//gmodel.CostPrice ?? 0;

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

                    if (!string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        item.CommissionPrice = speciPModel?.Commission ?? 0;
                    }
                }
            }

            InsertOrderCommission(demodel, umodel, GoodsIds, orderId);
            return "";
        }

        /// <summary>
        /// 插入返佣
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="umodel"></param>
        /// <param name="GoodsIds"></param>
        /// <param name="OrderId"></param>
        private void InsertOrderCommission(RB_Goods_Order_Extend demodel, Model.Entity.User.RB_Member_User umodel, string GoodsIds, int OrderId)
        {
            var trans = goods_OrderCommissionRepository.DbTransaction;
            try
            {
                #region 司导商品处理
                if (demodel.OrderClassify == 1)
                {
                    if (demodel.DetailList.Where(x => x.CarType != GuideCarGoodsTypeEnum.Line).Any())
                    {
                        foreach (var item in demodel.DetailList.Where(x => x.CarType != GuideCarGoodsTypeEnum.Line))
                        {
                            item.Number = 1;//司导的  除了线路  其他的都算包车
                        }
                    }
                }
                #endregion

                var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                if ((basicModel?.IsEnableFXGrade ?? 2) == 1)
                {
                    if (((basicModel?.IsEnableNoSuperiorFY ?? 1) == 1) || ((basicModel?.IsEnableNoSuperiorFY ?? 1) == 2 && (umodel.SuperiorId ?? 0) > 0))
                    {
                        //粉象返佣
                        var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        if (FXList.Any() && FXList.Where(x => x.IsGuest == 1).Any())
                        {
                            var FXPModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                            //验证用户必须是分销商 最低普通会员 不是以普通会员处理
                            var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = umodel.Id, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                            var FXModel = FXPModel;
                            if (disModel != null)
                            {
                                if (disModel.FXGradeId > 0)
                                {
                                    FXModel = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault();
                                }
                            }
                            else
                            {
                                LogHelper.Write("粉象返佣 用户分销商信息不存在：UserId:" + umodel.Id);
                            }
                            if (FXModel != null)
                            {
                                //查询出当前用户的所有上级
                                string UserIds = member_UserRepository.GetMemberParentIdStr(umodel.Id);
                                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = UserIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                //查询出用户的所有分销信息
                                var dlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = UserIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                foreach (var item in dlist)
                                {
                                    item.Grade = FXList.Where(x => x.Id == item.FXGradeId).FirstOrDefault()?.Grade ?? 0;
                                }
                                //开始慢慢找   注 同级返佣数量  返佣建子表可以无限级返佣了   --2020/10/16 未使用课程卡的才能返佣
                                var DetailList = demodel.DetailList.Where(x => x.CommissionPrice > 0 && (x.EducationCouponId ?? 0) == 0).ToList();
                                foreach (var item in DetailList)
                                {
                                    if ((item.PresentFXGrade ?? 0) > 0)
                                    {
                                        //是赠送VIP等级的  暂直接表示 反购买VIP佣金  2020-08-03  ld
                                        continue;
                                    }
                                    //返佣
                                    List<RB_Goods_OrderCommission> gocList = new List<RB_Goods_OrderCommission>();
                                    List<FXOrderCommissionNumModel> fxNumList = new List<FXOrderCommissionNumModel>();
                                    decimal TotalCommission = item.CommissionPrice;
                                    int UserId = umodel.Id;
                                    int Num = 1;
                                    while (UserId > 0 && TotalCommission > 0)
                                    {
                                        var numodel = ulist.Where(x => x.Id == UserId).FirstOrDefault();
                                        if (numodel == null)
                                        {
                                            UserId = 0;
                                            break;
                                        }
                                        if (numodel.Id == umodel.Id)
                                        {
                                            //第一个进来  按等级的返佣比例给佣金
                                            UserId = numodel.SuperiorId ?? 0;
                                            decimal DcommionMoney = 0;
                                            if (FXModel.DecimalType == 1)
                                            {
                                                DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                            fxNumList.Add(new FXOrderCommissionNumModel()
                                            {
                                                GradeId = FXModel.Id,
                                                Grade = FXModel.Grade ?? 0,
                                                Money = DcommionMoney,
                                                Sort = Num,
                                                IsSelfBuy = 1
                                            });
                                            Num++;
                                            TotalCommission -= DcommionMoney;

                                            RB_Goods_OrderCommission gocModel = new RB_Goods_OrderCommission()
                                            {
                                                Id = 0,
                                                Commission = FXModel.CommissionType == 2 ? 0 : DcommionMoney,//下单抵扣了  返佣金额=0
                                                CommissionState = 1,
                                                CreateDate = DateTime.Now,
                                                Grade = FXModel.Id,
                                                IsGoodsDistribution = 2,
                                                MallBaseId = demodel.MallBaseId,
                                                OrderDetailId = item.Id,
                                                OrderId = OrderId,
                                                Remark = "粉象 " + FXModel.GradeName + "下单返佣，返佣比例:" + (FXModel.CommissionRatio ?? 0) + "%;" + (FXModel.CommissionType == 2 ? "已抵扣" + (DcommionMoney * (item.Number ?? 0)) + "金额" : ""),
                                                TenantId = demodel.TenantId,
                                                UpdateDate = DateTime.Now,
                                                UserId = numodel.Id,
                                                Type = 3,
                                                IsRemit = 0,
                                                DeductionCommission = (DcommionMoney * (item.Number ?? 0))
                                            };
                                            gocList.Add(gocModel);
                                        }
                                        else
                                        {
                                            var d2Model = dlist.Where(x => x.UserId == numodel.Id).FirstOrDefault();
                                            var FXGModel = new RB_Distributor_FXGrade_Extend();
                                            if (d2Model == null)
                                            {
                                                LogHelper.Write("粉象返佣 用户分销商信息不存在：UserId:" + numodel.Id);
                                                FXGModel = FXPModel;
                                            }
                                            else
                                            {
                                                FXGModel = FXList.Where(x => x.Id == d2Model.FXGradeId).FirstOrDefault();
                                                if (FXGModel == null)
                                                {
                                                    FXGModel = FXPModel;
                                                }
                                            }
                                            int MaxGrade = fxNumList.Max(x => x.Grade);
                                            if (FXGModel.Grade < MaxGrade)
                                            {
                                                //后面的全部不返佣  2020-08-06  刘东 继续找下一级返佣
                                                UserId = numodel.SuperiorId ?? 0;
                                                continue;
                                            }
                                            int MaxGradeNum = fxNumList.Where(x => x.Grade == FXGModel.Grade).Count();
                                            int MaxGradeId = fxNumList.Where(x => x.Grade == MaxGrade).FirstOrDefault()?.GradeId ?? 0;
                                            if ((FXGModel.SiblingRebatesNum ?? 0) + 1 > MaxGradeNum)
                                            {
                                                UserId = numodel.SuperiorId ?? 0;
                                                decimal DcommionMoney = 0;
                                                decimal CommissionRatio = 0;
                                                if (FXGModel.Grade > MaxGrade && fxNumList.Where(x => x.GradeId == FXPModel.Id).Count() == 2 && MaxGrade == FXPModel.Grade)
                                                {
                                                    //需要提间接普会
                                                    CommissionRatio = GetFXGradeRatioCommon(FXList, FXGModel.Id, FXPModel.Id, 2);
                                                }
                                                else
                                                {
                                                    CommissionRatio = GetFXGradeRatioCommon(FXList, FXGModel.Id, MaxGradeId, 1);
                                                }
                                                if (FXGModel.DecimalType == 1)
                                                {
                                                    DcommionMoney = Math.Ceiling(item.CommissionPrice * CommissionRatio / 100);
                                                }
                                                else
                                                {
                                                    DcommionMoney = Math.Ceiling(item.CommissionPrice * CommissionRatio) / 100;
                                                }
                                                fxNumList.Add(new FXOrderCommissionNumModel()
                                                {
                                                    GradeId = FXGModel.Id,
                                                    Grade = FXGModel.Grade ?? 0,
                                                    Money = DcommionMoney,
                                                    Sort = Num,
                                                    IsSelfBuy = 2
                                                });
                                                Num++;
                                                bool IsMoneyLack = false;
                                                if (TotalCommission < DcommionMoney)
                                                {
                                                    DcommionMoney = TotalCommission;
                                                    IsMoneyLack = true;
                                                }
                                                RB_Goods_OrderCommission gocModel = new RB_Goods_OrderCommission()
                                                {
                                                    Id = 0,
                                                    Commission = DcommionMoney,
                                                    CommissionState = 1,
                                                    CreateDate = DateTime.Now,
                                                    Grade = FXGModel.Id,
                                                    IsGoodsDistribution = 2,
                                                    MallBaseId = demodel.MallBaseId,
                                                    OrderDetailId = item.Id,
                                                    OrderId = OrderId,
                                                    Remark = "粉象 " + FXGModel.GradeName + "返佣，返佣比例:" + CommissionRatio + "%" + (IsMoneyLack ? "  佣金不够、未返完" : ""),
                                                    TenantId = demodel.TenantId,
                                                    UpdateDate = DateTime.Now,
                                                    UserId = numodel.Id,
                                                    Type = 3,
                                                    IsRemit = 0
                                                };
                                                gocList.Add(gocModel);
                                                TotalCommission -= DcommionMoney;
                                            }
                                            else
                                            {
                                                UserId = 0;
                                                //该等级的已提完了  看是否可以直接找到下一个等级的
                                                var fx2List = dlist.Where(x => x.Grade > MaxGrade).ToList();
                                                if (fx2List.Any())
                                                {
                                                    //说明是有下一级的
                                                    for (var i = 0; i < ulist.Count; i++)
                                                    {
                                                        var n1umodel = ulist.Where(x => x.Id == (numodel.SuperiorId ?? 0)).FirstOrDefault();
                                                        if (n1umodel == null)
                                                        {
                                                            UserId = 0;
                                                            break;
                                                        }
                                                        var dis1Model = dlist.Where(x => x.UserId == n1umodel.Id).FirstOrDefault();
                                                        var FXG2Model = new RB_Distributor_FXGrade_Extend();
                                                        if (dis1Model == null)
                                                        {
                                                            LogHelper.Write("粉象返佣 用户分销商信息不存在：UserId:" + n1umodel.Id);
                                                            FXG2Model = FXPModel;
                                                        }
                                                        else
                                                        {
                                                            FXG2Model = FXList.Where(x => x.Id == dis1Model.FXGradeId).FirstOrDefault();
                                                            if (FXG2Model == null)
                                                            {
                                                                FXG2Model = FXPModel;
                                                            }
                                                        }
                                                        if (FXG2Model.Grade < MaxGrade)
                                                        {
                                                            //后面的全部不返佣
                                                            UserId = 0;
                                                            numodel = n1umodel;//继续查找下一级  2020-08-06  刘东
                                                        }
                                                        else if (FXG2Model.Grade > MaxGrade)
                                                        {
                                                            //已找到上级  继续返佣
                                                            UserId = n1umodel.Id;
                                                            break;
                                                        }
                                                        else
                                                        {
                                                            UserId = 0;
                                                            numodel = n1umodel;//继续查找下一级
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    item.TCommissionMoney = 0;
                                    foreach (var qitem in gocList)
                                    {
                                        qitem.Commission = (qitem.Commission ?? 0) * (item.Number ?? 0);
                                        item.TCommissionMoney += (qitem.Commission ?? 0);
                                        goods_OrderCommissionRepository.Insert(qitem, trans);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    //判断是否开启和平返佣
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.Status),
                                FiledValue=0,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.Enabled),
                                FiledValue=1,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.TenantId),
                                FiledValue=demodel.TenantId,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.MallBaseId),
                                FiledValue=demodel.MallBaseId,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    if (distributor_HPCommissionRepository.Exists(wheres))
                    {
                        int OneUserId = umodel.SuperiorId ?? 0;
                        //获取分销商信息
                        var disModel = new RB_Distributor_Info_Extend();
                        if ((basicModel?.InPurchasing ?? 2) == 1)
                        {
                            disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = umodel.Id, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                            if (disModel != null && (disModel.HPGradeId ?? 0) > 0)
                            {
                                OneUserId = umodel.Id;//设置了分销内购   并且自己是分销商  并且设置了和平等级 ， 那么就是自购返佣
                            }
                        }
                        if (OneUserId != umodel.Id)
                        {
                            //求其上级
                            disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = OneUserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                            if (disModel != null && (disModel.HPGradeId ?? 0) > 0)
                            {
                                OneUserId = umodel.SuperiorId ?? 0;//其上级可返佣
                            }
                            else
                            {
                                OneUserId = 0;
                            }
                        }
                        if (OneUserId > 0)
                        {
                            foreach (var item in demodel.DetailList)
                            {
                                if (item.CostMoney > 0)
                                {
                                    //成本价格大于0的才进行返佣
                                    string categoryids = string.Join(",", item.CategoryIdList);
                                    var hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIdsT = categoryids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    if (hpcList.Any())
                                    {
                                        RB_Distributor_HPCommission_Extend hpcModel;
                                        if (hpcList.Where(x => x.IsCommon != 1).Any())
                                        {
                                            //有使用非通用返佣
                                            hpcModel = hpcList.Where(x => x.IsCommon != 1).FirstOrDefault();
                                        }
                                        else
                                        {
                                            //查询通用返佣
                                            hpcModel = hpcList.Where(x => x.IsCommon == 1).FirstOrDefault();
                                        }
                                        //查询所有返佣比例
                                        var gList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = hpcModel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                                        var ratioModel = gList.Where(x => x.GradeId == disModel.HPGradeId).FirstOrDefault();
                                        decimal OneCommission = 0;
                                        if (ratioModel != null)
                                        {
                                            decimal MPrice = (item.CostMoney ?? 0) / (1 - ((ratioModel.CommissionRatio ?? 0) / 100));
                                            OneCommission = (item.Final_Price ?? 0) - MPrice > 0 ? (item.Final_Price ?? 0) - MPrice : 0;
                                        }
                                        if (hpcModel.DecimalType == 1)
                                        {
                                            OneCommission = Math.Ceiling(OneCommission);
                                        }
                                        else if (hpcModel.DecimalType == 2)
                                        {
                                            OneCommission = Math.Ceiling(OneCommission * 100) / 100;
                                        }
                                        //插入返佣
                                        goods_OrderCommissionRepository.Insert(new RB_Goods_OrderCommission()
                                        {
                                            Id = 0,
                                            Commission = OneCommission,
                                            CommissionState = 1,
                                            CreateDate = DateTime.Now,
                                            Grade = disModel.HPGradeId,
                                            IsGoodsDistribution = 2,
                                            MallBaseId = demodel.MallBaseId,
                                            OrderDetailId = item.Id,
                                            OrderId = OrderId,
                                            Remark = "和平返佣",
                                            TenantId = demodel.TenantId,
                                            UpdateDate = DateTime.Now,
                                            UserId = OneUserId,
                                            Type = 2,
                                            IsRemit = 0
                                        }, trans);

                                        //向上找出所有可以分销的
                                        int ParentId = 0;
                                        if (OneUserId == umodel.Id)
                                        {
                                            ParentId = umodel.SuperiorId ?? 0;
                                        }
                                        else
                                        {
                                            ParentId = member_UserRepository.GetEntity(umodel.SuperiorId ?? 0)?.SuperiorId ?? 0;
                                        }
                                        decimal ParentCommission = OneCommission;
                                        while (ParentId > 0)
                                        {
                                            var disModel1 = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = ParentId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                                            if (disModel1 != null && (disModel1.HPGradeId ?? 0) > 0)
                                            {
                                                //其上级可进行返佣
                                                var ratioModel1 = gList.Where(x => x.GradeId == disModel1.HPGradeId).FirstOrDefault();
                                                decimal OneCommission1 = 0;
                                                if (ratioModel1 != null)
                                                {
                                                    decimal MPrice1 = (item.CostMoney ?? 0) / (1 - ((ratioModel1.CommissionRatio ?? 0) / 100));
                                                    OneCommission1 = (item.Final_Price ?? 0) - MPrice1 > 0 ? (item.Final_Price ?? 0) - MPrice1 : 0;
                                                }
                                                if (hpcModel.DecimalType == 1)
                                                {
                                                    OneCommission1 = Math.Ceiling(OneCommission1);
                                                }
                                                else if (hpcModel.DecimalType == 2)
                                                {
                                                    OneCommission1 = Math.Ceiling(OneCommission1 * 100) / 100;
                                                }
                                                //减去下级已提佣金
                                                OneCommission1 -= ParentCommission;
                                                ParentCommission += OneCommission1;//累计下级已提佣金
                                                                                   //插入返佣
                                                goods_OrderCommissionRepository.Insert(new RB_Goods_OrderCommission()
                                                {
                                                    Id = 0,
                                                    Commission = OneCommission1,
                                                    CommissionState = 1,
                                                    CreateDate = DateTime.Now,
                                                    Grade = disModel1.HPGradeId,
                                                    IsGoodsDistribution = 2,
                                                    MallBaseId = demodel.MallBaseId,
                                                    OrderDetailId = item.Id,
                                                    OrderId = OrderId,
                                                    Remark = "和平返佣",
                                                    TenantId = demodel.TenantId,
                                                    UpdateDate = DateTime.Now,
                                                    UserId = ParentId,
                                                    Type = 2,
                                                    IsRemit = 0
                                                }, trans);
                                            }
                                            ParentId = member_UserRepository.GetEntity(ParentId)?.SuperiorId ?? 0;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        var dcList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        if (basicModel != null && basicModel.DistributorTier > 0)
                        {
                            if ((basicModel.InPurchasing ?? 2) != 1)
                            {
                                umodel.IsDistributor = 2;
                            }
                            #region 分销商id+分销商等级
                            int OneUserId = 0, TwoUserId = 0, ThreeUserId = 0;
                            int OneDistributorGrade = -1, TwoDistributorGrade = -1, ThreeDistributorGrade = -1;
                            //获取多级 分销商id
                            if (basicModel != null && basicModel.DistributorTier > 0)
                            {
                                for (int i = 1; i < basicModel.DistributorTier + 1; i++)
                                {
                                    switch (i)
                                    {
                                        case 1:
                                            if (umodel.IsDistributor != 1 || basicModel.InPurchasing != 1)
                                            {
                                                OneUserId = umodel.SuperiorId ?? 0;
                                            }
                                            else
                                            {
                                                OneUserId = umodel.Id;
                                            }
                                            break;
                                        case 2:
                                            if (OneUserId > 0)
                                            {
                                                if (umodel.IsDistributor != 1 || basicModel.InPurchasing != 1)
                                                {
                                                    TwoUserId = member_UserRepository.GetEntity(OneUserId).SuperiorId ?? 0;
                                                }
                                                else
                                                {
                                                    TwoUserId = umodel.SuperiorId ?? 0;
                                                }
                                            }
                                            break;
                                        case 3:
                                            if (TwoUserId > 0)
                                            {
                                                ThreeUserId = member_UserRepository.GetEntity(TwoUserId).SuperiorId ?? 0;
                                            }
                                            break;
                                    }
                                }
                            }
                            if (OneUserId > 0)
                            {
                                #region 临时处理
                                if (TwoUserId > 0 && TwoUserId < 20)
                                {
                                    TwoUserId = 0;
                                }
                                if (ThreeUserId > 0 && ThreeUserId < 20)
                                {
                                    ThreeUserId = 0;
                                }
                                #endregion
                                if (OneUserId > 0)
                                {
                                    var dis1Model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = OneUserId, AuditStatus = DistributorAuditStatusEnum.Audited })?.FirstOrDefault();
                                    if (dis1Model != null)
                                    {
                                        OneDistributorGrade = dis1Model?.GradeId ?? 0;
                                    }
                                    else
                                    {
                                        OneDistributorGrade = -1;//不是分销商
                                    }
                                }
                                if (TwoUserId > 0 && OneDistributorGrade >= 0)
                                {
                                    var dis2Model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = TwoUserId, AuditStatus = DistributorAuditStatusEnum.Audited })?.FirstOrDefault();
                                    if (dis2Model != null)
                                    {
                                        TwoDistributorGrade = dis2Model?.GradeId ?? 0;
                                    }
                                    else
                                    {
                                        TwoDistributorGrade = -1;
                                    }
                                }
                                if (ThreeUserId > 0 && TwoDistributorGrade >= 0)
                                {
                                    var dis3Model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = ThreeUserId, AuditStatus = DistributorAuditStatusEnum.Audited })?.FirstOrDefault();
                                    if (dis3Model != null)
                                    {
                                        ThreeDistributorGrade = dis3Model?.GradeId ?? 0;
                                    }
                                    else
                                    {
                                        ThreeDistributorGrade = -1;
                                    }
                                }
                                #endregion
                                #region 分销商等级列表
                                List<int> gradeIdlist = new List<int>();
                                if (OneDistributorGrade > 0)
                                {
                                    gradeIdlist.Add(OneDistributorGrade);
                                }
                                if (TwoDistributorGrade > 0)
                                {
                                    gradeIdlist.Add(TwoDistributorGrade);
                                }
                                if (ThreeDistributorGrade > 0)
                                {
                                    gradeIdlist.Add(ThreeDistributorGrade);
                                }
                                List<RB_Distributor_Grade_Extend> dgradeList = new List<RB_Distributor_Grade_Extend>();
                                if (gradeIdlist.Any())
                                {
                                    dgradeList = distributor_GradeRepository.GetList(new RB_Distributor_Grade_Extend() { GradeIds = string.Join(",", gradeIdlist), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                }
                                #endregion
                                foreach (var item in demodel.DetailList.Where(x => (x.EducationCouponId ?? 0) == 0))
                                {
                                    decimal fmoney = (item.Final_Price ?? 0);
                                    if (demodel.SmallShopsId > 0 && item.Final_Price != item.SmallShopsCostPrice)
                                    {
                                        fmoney = (item.SmallShopsCostPrice ?? 0);
                                    }
                                    //返佣
                                    List<RB_Goods_OrderCommission> gocList = new List<RB_Goods_OrderCommission>();
                                    for (int i = 1; i < basicModel.DistributorTier + 1; i++)
                                    {
                                        switch (i)
                                        {
                                            case 1:
                                                decimal DcommionMoney = 0;
                                                if (item.SeparateDistribution == 1)
                                                {
                                                    if (item.SeparateDistributionType == 1)
                                                    {
                                                        DcommionMoney = dcList.Where(x => x.GoodsId == item.GoodsId && x.DistributorGrade == OneDistributorGrade).FirstOrDefault()?.OneCommission ?? 0;
                                                    }
                                                    else
                                                    {
                                                        DcommionMoney = dcList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort && x.DistributorGrade == OneDistributorGrade).FirstOrDefault()?.OneCommission ?? 0;
                                                    }
                                                    if (item.SeparateDistributionMoneyType == 1)
                                                    {
                                                        DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                    }
                                                }
                                                else
                                                {
                                                    //获取分销商等级
                                                    if (OneDistributorGrade > 0)
                                                    {
                                                        var dgradeModel = dgradeList.Where(x => x.Id == OneDistributorGrade).FirstOrDefault();
                                                        DcommionMoney = dgradeModel?.OneCommission ?? 0;
                                                        if (dgradeModel.DistributionCommissionType == 1)
                                                        {
                                                            DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //默认分销商等级  读取基本配置的返佣
                                                        DcommionMoney = basicModel.OneCommission ?? 0;
                                                        if (basicModel.DistributorCommissionType == 1)
                                                        {
                                                            DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                        }
                                                    }

                                                }
                                                if (TwoUserId == 0 && basicModel.IsCommissionResidue == 1)
                                                {
                                                    //表示其为一级分销商  把后面的佣金都提完
                                                    TwoUserId = OneUserId;
                                                    TwoDistributorGrade = OneDistributorGrade;
                                                }
                                                RB_Goods_OrderCommission gocModel = new RB_Goods_OrderCommission()
                                                {
                                                    Id = 0,
                                                    Commission = DcommionMoney,
                                                    CommissionState = 1,
                                                    CreateDate = DateTime.Now,
                                                    Grade = umodel.IsDistributor == 1 ? 0 : 1,
                                                    IsGoodsDistribution = item.SeparateDistribution,
                                                    MallBaseId = demodel.MallBaseId,
                                                    OrderDetailId = item.Id,
                                                    OrderId = OrderId,
                                                    Remark = "",
                                                    TenantId = demodel.TenantId,
                                                    UpdateDate = DateTime.Now,
                                                    UserId = OneUserId,
                                                    Type = 1,
                                                    IsRemit = 0
                                                };
                                                if (OneDistributorGrade != -1)
                                                {
                                                    gocList.Add(gocModel);
                                                }
                                                break;
                                            case 2:
                                                if (TwoUserId > 0)
                                                {
                                                    DcommionMoney = 0;
                                                    if (item.SeparateDistribution == 1)
                                                    {
                                                        if (item.SeparateDistributionType == 1)
                                                        {
                                                            DcommionMoney = dcList.Where(x => x.GoodsId == item.GoodsId && x.DistributorGrade == TwoDistributorGrade).FirstOrDefault()?.TwoCommission ?? 0;
                                                        }
                                                        else
                                                        {
                                                            DcommionMoney = dcList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort && x.DistributorGrade == TwoDistributorGrade).FirstOrDefault()?.TwoCommission ?? 0;
                                                        }
                                                        if (item.SeparateDistributionMoneyType == 1)
                                                        {
                                                            DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //获取分销商等级
                                                        if (TwoDistributorGrade > 0)
                                                        {
                                                            var dgradeModel = dgradeList.Where(x => x.Id == TwoDistributorGrade).FirstOrDefault();
                                                            DcommionMoney = dgradeModel?.TwoCommission ?? 0;
                                                            if (dgradeModel.DistributionCommissionType == 1)
                                                            {
                                                                DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            //默认分销商等级  读取基本配置的返佣
                                                            DcommionMoney = basicModel.TwoCommission ?? 0;
                                                            if (basicModel.DistributorCommissionType == 1)
                                                            {
                                                                DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                            }
                                                        }

                                                    }
                                                    if (ThreeUserId == 0 && basicModel.IsCommissionResidue == 1)
                                                    {
                                                        //表示其为二级分销商  把后面的佣金都提完
                                                        ThreeUserId = TwoUserId;
                                                        ThreeDistributorGrade = TwoDistributorGrade;
                                                    }
                                                    gocModel = new RB_Goods_OrderCommission()
                                                    {
                                                        Id = 0,
                                                        Commission = DcommionMoney,
                                                        CommissionState = 1,
                                                        CreateDate = DateTime.Now,
                                                        Grade = umodel.IsDistributor == 1 ? TwoUserId == OneUserId ? 0 : 1 : 2,
                                                        IsGoodsDistribution = item.SeparateDistribution,
                                                        MallBaseId = demodel.MallBaseId,
                                                        OrderDetailId = item.Id,
                                                        OrderId = OrderId,
                                                        Remark = "",
                                                        TenantId = demodel.TenantId,
                                                        UpdateDate = DateTime.Now,
                                                        UserId = TwoUserId,
                                                        Type = 1,
                                                        IsRemit = 0
                                                    };
                                                    if (TwoDistributorGrade != -1)
                                                    {
                                                        gocList.Add(gocModel);
                                                    }
                                                }
                                                break;
                                            case 3:
                                                if (ThreeUserId > 0)
                                                {
                                                    DcommionMoney = 0;
                                                    if (item.SeparateDistribution == 1)
                                                    {
                                                        if (item.SeparateDistributionType == 1)
                                                        {
                                                            DcommionMoney = dcList.Where(x => x.GoodsId == item.GoodsId && x.DistributorGrade == ThreeDistributorGrade).FirstOrDefault()?.ThreeCommission ?? 0;
                                                        }
                                                        else
                                                        {
                                                            DcommionMoney = dcList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort && x.DistributorGrade == ThreeDistributorGrade).FirstOrDefault()?.ThreeCommission ?? 0;
                                                        }
                                                        if (item.SeparateDistributionMoneyType == 1)
                                                        {
                                                            DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //获取分销商等级
                                                        if (ThreeDistributorGrade > 0)
                                                        {
                                                            var dgradeModel = dgradeList.Where(x => x.Id == ThreeDistributorGrade).FirstOrDefault();
                                                            DcommionMoney = dgradeModel?.ThreeCommission ?? 0;
                                                            if (dgradeModel.DistributionCommissionType == 1)
                                                            {
                                                                DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            //默认分销商等级  读取基本配置的返佣
                                                            DcommionMoney = basicModel.ThreeCommission ?? 0;
                                                            if (basicModel.DistributorCommissionType == 1)
                                                            {
                                                                DcommionMoney = Math.Round(fmoney * DcommionMoney / 100, 2, MidpointRounding.AwayFromZero);
                                                            }
                                                        }

                                                    }
                                                    #region 获取返佣等级
                                                    int Grade = 0;
                                                    if (OneUserId == TwoUserId && TwoUserId == ThreeUserId)
                                                    {
                                                        Grade = 0;
                                                    }
                                                    else if (OneUserId != TwoUserId && TwoUserId == ThreeUserId)
                                                    {
                                                        Grade = 1;
                                                    }
                                                    else
                                                    {
                                                        Grade = 2;
                                                    }
                                                    if (umodel.IsDistributor != 1)
                                                    {
                                                        Grade++;
                                                    }
                                                    #endregion
                                                    gocModel = new RB_Goods_OrderCommission()
                                                    {
                                                        Id = 0,
                                                        Commission = DcommionMoney,
                                                        CommissionState = 1,
                                                        CreateDate = DateTime.Now,
                                                        Grade = Grade,
                                                        IsGoodsDistribution = item.SeparateDistribution,
                                                        MallBaseId = demodel.MallBaseId,
                                                        OrderDetailId = item.Id,
                                                        OrderId = OrderId,
                                                        Remark = "",
                                                        TenantId = demodel.TenantId,
                                                        UpdateDate = DateTime.Now,
                                                        UserId = ThreeUserId,
                                                        Type = 1,
                                                        IsRemit = 0
                                                    };
                                                    if (ThreeDistributorGrade != -1)
                                                    {
                                                        gocList.Add(gocModel);
                                                    }
                                                }
                                                break;

                                        }
                                    }
                                    List<RB_Goods_OrderCommission> gocfulList = gocList;
                                    //gocList 合并用户金额
                                    if (basicModel.IsCommissionResidue == 1)
                                    {
                                        if (gocList.Count() != gocList.Select(x => x.UserId).Distinct().Count())
                                        {
                                            gocfulList = new List<RB_Goods_OrderCommission>();
                                            //说明有用户可以合并
                                            var userIdList = gocList.Select(x => x.UserId).Distinct().ToList();
                                            foreach (var qitem in userIdList)
                                            {
                                                var gocModel = gocList.Where(x => x.UserId == qitem).FirstOrDefault();
                                                if (gocList.Where(x => x.UserId == qitem).Count() > 1)
                                                {
                                                    decimal tcommission = gocList.Where(x => x.UserId == qitem).Sum(x => x.Commission ?? 0);
                                                    gocModel.Commission = tcommission;
                                                    gocModel.Remark = "多级全额返佣";
                                                }
                                                gocfulList.Add(gocModel);
                                            }
                                        }
                                    }
                                    item.TCommissionMoney = 0;
                                    if (gocfulList.Any())
                                    {
                                        foreach (var qitem in gocfulList)
                                        {
                                            qitem.Commission = (qitem.Commission ?? 0) * (item.Number ?? 0);
                                            item.TCommissionMoney += (qitem.Commission ?? 0);
                                            goods_OrderCommissionRepository.Insert(qitem, trans);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #region 推荐返佣
                if (demodel.DetailList.Where(x => x.SupplierId > 0 && (x.EducationCouponId ?? 0) == 0).Any())
                {
                    string supplierIds = string.Join(",", demodel.DetailList.Where(x => x.SupplierId > 0).Select(x => x.SupplierId));
                    var supplist = supplierRepository.GetList(new RB_Supplier_Extend() { SupplierIds = supplierIds }).Where(x => x.Introducer > 0).ToList();
                    if (supplist.Any())
                    {
                        //有 就需要反推荐佣金
                        //查出返佣的比例
                        var scList = supplierCommissionRepository.GetListBySupplierIds(string.Join(",", supplist.Select(x => x.ID)));
                        //查出所有的订单
                        var detailList = demodel.DetailList.Where(x => supplist.Select(x => x.ID).Contains(x.SupplierId) && (x.EducationCouponId ?? 0) == 0).ToList();
                        foreach (var item in detailList)
                        {
                            decimal fmoney = (item.Final_Price ?? 0);
                            if (demodel.SmallShopsId > 0 && item.Final_Price != item.SmallShopsCostPrice)
                            {
                                fmoney = (item.SmallShopsCostPrice ?? 0);
                            }
                            var supplierModel = supplist.Where(x => x.ID == item.SupplierId).FirstOrDefault();
                            var qscList = scList.Where(x => x.SupplierId == item.SupplierId).ToList();
                            if (item.CostMoney > 0 && (fmoney - (item.CostMoney ?? 0) * (item.Number ?? 0) - item.TCommissionMoney) > 0 && qscList.Any())
                            {
                                decimal Profit = fmoney - (item.CostMoney ?? 0) * (item.Number ?? 0) - item.TCommissionMoney;
                                decimal GrossMargin = Math.Round(Profit / fmoney, 2, MidpointRounding.AwayFromZero);
                                var scModel = qscList.Where(x => (x.CommissionType * 10) >= (GrossMargin * 100)).OrderBy(x => x.CommissionType).FirstOrDefault();
                                decimal Commission = Math.Round(Profit * scModel.CommissionRate / 100, 2, MidpointRounding.AwayFromZero);
                                if (Commission > 0)
                                {
                                    //插入返佣记录
                                    goods_OrderIntroductionRepository.Insert(new RB_Goods_OrderIntroduction()
                                    {
                                        Commission = Commission,
                                        CommissionRatio = scModel.CommissionRate,
                                        CommissionState = 1,
                                        CreateDate = DateTime.Now,
                                        Id = 0,
                                        MallBaseId = demodel.MallBaseId,
                                        OrderDetailId = item.Id,
                                        OrderId = OrderId,
                                        Remark = "商品总额：" + fmoney + "，总成本：" + (item.CostMoney ?? 0) * (item.Number ?? 0) + "，总返佣：" + item.TCommissionMoney + "，总利润：" + Profit,
                                        RemitStatus = 2,
                                        TenantId = demodel.TenantId,
                                        Type = 1,
                                        UpdateDate = DateTime.Now,
                                        UserId = supplierModel.Introducer
                                    }, trans);
                                }
                            }
                        }
                    }
                }
                #endregion

                #region 微店返佣
                if (demodel.SmallShopsId > 0 && demodel.DetailList.Where(x => x.Final_Price != x.SmallShopsCostPrice && (x.EducationCouponId ?? 0) == 0).Any())
                {
                    var smallModel = smallShops_InfoRepository.GetEntity(demodel.SmallShopsId);
                    if (smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                    {
                        foreach (var item in demodel.DetailList.Where(x => x.Final_Price != x.SmallShopsCostPrice && (x.EducationCouponId ?? 0) == 0).ToList())
                        {
                            decimal sscommission = (item.Final_Price ?? 0) - (item.SmallShopsCostPrice ?? 0);
                            string CouponDestription = "";
                            if (item.CouponMoney > 0)
                            {
                                CouponDestription = demodel.CouponDestription + (item.CouponMoney ?? 0) + "元";
                            }
                            smallShops_CommissionRepository.Insert(new RB_SmallShops_Commission()
                            {
                                Commission = sscommission,
                                CommissionState = 1,
                                CreateDate = DateTime.Now,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                OrderDetailId = item.Id,
                                OrderId = OrderId,
                                Remark = "赞羊售价：" + (item.SmallShopsCostPrice ?? 0) + "  微店售价：" + (item.Final_Price ?? 0) + "  " + CouponDestription,
                                IsRemit = 2,
                                TenantId = demodel.TenantId,
                                Type = 1,
                                UpdateDate = DateTime.Now,
                                UserId = smallModel.UserId,
                                SmallShopsId = demodel.SmallShopsId ?? 0
                            }, trans);
                        }
                    }
                }
                #endregion
                goods_OrderCommissionRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "InsertOrderCommission:" + OrderId + "订单返佣失败");
                goods_OrderCommissionRepository.DBSession.Rollback();
            }
        }

        /// <summary>
        /// 获取粉象返佣比例
        /// </summary>
        /// <param name="list"></param>
        /// <param name="id1"></param>
        /// <param name="id2"></param>
        /// <returns></returns>
        private decimal GetFXGradeRatioCommon(List<RB_Distributor_FXGrade_Extend> list, int id1, int id2, int Type = 1)
        {
            var model1 = list.Where(x => x.Id == id1).FirstOrDefault();
            var model2 = list.Where(x => x.Id == id2).FirstOrDefault();
            var pModel = list.Where(x => x.IsGuest == 1).FirstOrDefault();
            if (id1 == id2 && Type == 1)
            {
                return model1.SiblingRatio ?? 0;
            }
            if (model2.Grade > model1.Grade)
            {
                return 0;
            }
            if (model1.Grade > model2.Grade && Type == 1)
            {
                return (model1.CommissionRatio ?? 0) - (model2.CommissionRatio ?? 0);
            }
            if (id2 == pModel.Id && Type == 2)
            {
                if (id1 == id2) { return 0; }
                return (model1.CommissionRatio ?? 0) - ((pModel.CommissionRatio ?? 0) + (pModel.SiblingRatio ?? 0));
            }
            return 0;
        }

        /// <summary>
        /// 插入订单明细，以及更新商品库存
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="trans"></param>
        /// <param name="OrderId"></param>
        private void InsertOrderDetail(RB_Goods_Order_Extend demodel, System.Data.IDbTransaction trans, int OrderId, List<FreeShippingGoodsDetail> SatisfiedGoodsList, bool IsSDGoods = false)
        {
            foreach (var item in demodel.DetailList)
            {
                int IntegralPresent = item.IntegralPresent ?? 0;
                //积分
                if (item.IntegralPresent > 0)
                {
                    if (item.IntegralPresentType == 1)
                    {
                        IntegralPresent = Convert.ToInt32((item.Final_Price ?? 0) * (item.IntegralPresent ?? 0) / 100);
                    }
                }
                //插入订单明细表
                int detailId = goods_OrderDetailRepository.Insert(new RB_Goods_OrderDetail()
                {
                    Id = 0,
                    CustomFormInfo = demodel?.CustomFormInfo ?? "",
                    CostMoney = item.CostMoney,
                    CoverImage = item.CoverImage,
                    CreateDate = DateTime.Now,
                    DiscountRate = item.DiscountRate ?? 0,
                    Final_Price = item.Final_Price,
                    GoodsId = item.GoodsId,
                    GoodsName = item.GoodsName,
                    IsMemberPrice = item.IsMemberPrice ?? 2,
                    MallBaseId = demodel.MallBaseId,
                    Number = item.Number,
                    OrderId = OrderId,
                    OrderType = item.OrderType,
                    Original_Price = item.Original_Price,
                    ProductCode = item.ProductCode,
                    Specification = item.Specification,//前端传递过来
                    SpecificationSort = item.SpecificationSort,
                    Unit_Price = item.Unit_Price,
                    TenantId = demodel.TenantId,
                    UpdateDate = DateTime.Now,
                    IsComment = 2,
                    FreightMoney = item.FreightMoney,
                    IntegralMoney = item.IntegralMoney,
                    IntegralNumber = item.IntegralNumber,
                    CouponMoney = item.CouponMoney,
                    IntegralGoodsPresent = IntegralPresent,
                    SupplierId = item.SupplierId,
                    CostFinanceId = 0,
                    FreightCostMoney = 0,
                    FreightFinanceId = 0,
                    PresentFXGrade = item.PresentFXGrade,
                    PresentFXMonth = item.PresentFXMonth,
                    FreeShippingRemarks = item.FreeShippingRemarks,
                    SmallShopsCostPrice = item.SmallShopsCostPrice,
                    PaidCostMoney = 0,
                    LiveCommission = item.LiveCommission,
                    LiveFinanceIds = "",
                    LivePeopleNum = 1,
                    PayMoney = 0,
                    YFMoney = 0,
                    RealMoney = 0,
                    YSMoney = 0,
                    CompanyId = demodel.CompanyId,
                    CompanyProfitRate = demodel.CompanyProfitRate,
                    ServiceCharge = item.ServiceCharge,
                    CarType = item.CarType,
                    LineName = item.LineName,
                    CarNumber = item.CarNumber,
                    CarColorId = item.CarColorId,
                    GuideId = item.GuideId,
                    SiteId = item.SiteId,
                    CarId = item.CarId,
                    IsSpell = item.IsSpell,
                    TripETime = item.TripETime,
                    TripSTime = item.TripSTime,
                    UseDay = item.UseDay,
                    InsuranceMoney = item.InsuranceMoney ?? 0,
                    InsuranceCostMoney = item.InsuranceCostMoney ?? 0,
                    InsuranceFinanceId = 0,
                    CommentGiveIntegral = item.CommentGiveIntegral,
                    EducationCouponId = item.EducationCouponId,
                    DeductionCommission = item.DeductionCommission,
                    ServiceDate = item.ServiceDate,
                    ServicepersonalId = item.ServicepersonalId,
                    ServiceTime = item.ServiceTime,
                    GoodServiceTime = item.GoodServiceTime,
                    IsNoTax = item.IsNoTax,
                    DepositMoney = item.DepositMoney,
                    DepositFreightMoney = item.DepositFreightMoney,
                    DepositRefundMoney = item.DepositRefundMoney,
                    ClassId = item.ClassId,
                    FXCommission = item.CommissionPrice,
                    OriginalCostMoney = item.CostMoney ?? 0,
                    PresentCoffeeNum = item.PresentCoffeeNum,
                    MaterialId = item.MaterialId,
                    DepositRatio = item.DepositRatio,
                }, trans);
                item.Id = detailId;
                if (detailId > 0 && SatisfiedGoodsList.Any())
                {
                    //插入适配的包邮规则
                    var fsmodel = SatisfiedGoodsList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                    if (fsmodel != null)
                    {
                        orderDetailFreeShippingRepository.Insert(new RB_Goods_OrderDetailFreeShipping()
                        {
                            FreeshippingId = fsmodel.FreeShipping,
                            Category = fsmodel.CategoryId,
                            CreateDate = DateTime.Now,
                            FullMoneyPinkage = 0,
                            FullNumPinkage = 0,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Name = fsmodel.Name,
                            OrderDetailId = detailId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        }, trans);
                    }
                }
                if (IsSDGoods == false && demodel.OrderClassify != 2 && demodel.OrderEduType != 1)
                {
                    //更新商品数量
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Goods.InventoryNum),item.InventoryNum-(item.Number??0)}
                        };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods.Id),
                                  FiledValue=item.GoodsId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods.TenantId),
                                  FiledValue=demodel.TenantId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods.MallBaseId),
                                  FiledValue=demodel.MallBaseId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                    bool flagg = goodsRepository.Update(keyValues, wheres, trans);
                    if (flagg)
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort) && item.SpeciPriceId > 0)
                        {
                            //更新规格价格库存
                            Dictionary<string, object> keyValuesp = new Dictionary<string, object>() {
                                    { nameof(RB_Goods_SpecificationPrice.InventoryNum),item.InventoryNum-(item.Number??0)}
                                };
                            List<WhereHelper> wheresp = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                          FiledValue=item.SpeciPriceId,
                                           OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods_SpecificationPrice.GoodsId),
                                          FiledValue=item.GoodsId,
                                           OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.TenantId),
                                          FiledValue=demodel.TenantId,
                                           OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.MallBaseId),
                                          FiledValue=demodel.MallBaseId,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                            goods_SpecificationPriceRepository.Update(keyValuesp, wheresp, trans);
                        }
                        //记录日志
                        goods_LogRepository.Insert(new RB_Goods_Log()
                        {
                            Id = 0,
                            Type = 2,
                            SourceId = item.GoodsId,
                            Content = "新增订单，Key:" + item.SpecificationSort + "，商品库存减少:" + item.Number,
                            CreateDate = DateTime.Now,
                            MallBaseId = demodel.MallBaseId,
                            TenantId = demodel.TenantId
                        }, trans);
                    }
                }

                #region 更新司导商品预约时间
                if (IsSDGoods)
                {
                    //通过下单时间范围  查询出所有的日期   线路的看是否可以拼车  增加人数  更新日期预定状态
                    var tdlist = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = item.GoodsId ?? 0, StartTime = item.TripSTime.Value.ToString("yyyy-MM-dd"), EndTime = item.TripETime.Value.ToString("yyyy-MM-dd") });
                    if (tdlist.Any())
                    {
                        if (item.CarType == GuideCarGoodsTypeEnum.Line && item.IsSpell == 1)
                        {
                            //只调整第一天的   其他天 直接表示已预订了
                            var fristModel = tdlist.Where(x => x.Date == Convert.ToDateTime(item.TripSTime.Value.ToString("yyyy-MM-dd"))).FirstOrDefault();
                            //第一条更新数量  如果OK咯  更新已预定
                            if (fristModel != null)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>();
                                if ((item.GoodsRideNum ?? 0) - (fristModel.ReserveNum) <= (item.Number ?? 0))
                                {
                                    keyValues1.Add(nameof(RB_Goods_TargetDate.IsReserve), 2);
                                    keyValues1.Add(nameof(RB_Goods_TargetDate.ReserveNum), (fristModel.ReserveNum) + (item.Number ?? 0));
                                }
                                else
                                {
                                    keyValues1.Add(nameof(RB_Goods_TargetDate.IsReserve), 1);
                                    keyValues1.Add(nameof(RB_Goods_TargetDate.ReserveNum), (fristModel.ReserveNum) + (item.Number ?? 0));
                                }
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                            FiledName=nameof(RB_Goods_TargetDate.Id),
                                            FiledValue=fristModel.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goods_TargetDateRepository.Update(keyValues1, wheres1, trans);
                            }
                            //其他的直接已预定
                            foreach (var qitem in tdlist.Where(x => x.Date != Convert.ToDateTime(item.TripSTime.Value.ToString("yyyy-MM-dd")) && x.IsReserve == 1))
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods_TargetDate.IsReserve),2},
                                    { nameof(RB_Goods_TargetDate.ReserveNum),item.Number??0},
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                            FiledName=nameof(RB_Goods_TargetDate.Id),
                                            FiledValue=qitem.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goods_TargetDateRepository.Update(keyValues1, wheres1, trans);
                            }
                        }
                        else
                        {
                            //直接更新日期为已预订
                            foreach (var qitem in tdlist)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods_TargetDate.IsReserve),2},
                                    { nameof(RB_Goods_TargetDate.ReserveNum),qitem.ReserveNum + (item.Number??0)},
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods_TargetDate.Id),
                                          FiledValue=qitem.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goods_TargetDateRepository.Update(keyValues1, wheres1, trans);
                            }
                        }
                    }
                }
                #endregion
            }
        }

        /// <summary>
        /// 用户取消订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool CancelAppletGoodsOrderInfo(int orderId, int type, string remark, int userId, int tenantId, int mallBaseId)
        {
            var omodel = goods_OrderRepository.GetEntity(orderId);
            if (omodel == null)
            {
                return false;
            }
            if (type == 1)
            {
                if (omodel.OrderStatus != OrderStatusEnum.NonPayment)
                {
                    return false;
                }
            }
            else if (type == 2)
            {
                if (omodel.OrderClassify == 1)
                {
                    if (omodel.OrderStatus != OrderStatusEnum.WaitSendGoods || omodel.OrderStatus != OrderStatusEnum.WaitReceiving)
                    {
                        return false;
                    }
                }
                else
                {
                    if (omodel.TenantId == 29)
                    {
                        if (omodel.OrderStatus != OrderStatusEnum.WaitReceiving)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (omodel.OrderStatus != OrderStatusEnum.WaitSendGoods)
                        {
                            return false;
                        }
                        //物流
                        var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
                        if (erlist.Any())
                        {
                            return false;//已有商品发货，无法退款
                        }
                    }

                    //验证储值卡  并且未实际金额的话，直接取消订单  无需后台二次确认
                    if (omodel.Income == 0 && omodel.DepositId > 0 && omodel.DepositMoney > 0)
                    {
                        type = 1;//改为直接取消
                    }
                }
            }
            var trans = goods_OrderRepository.DbTransaction;
            try
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
                if (type == 1)
                {
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Cancel);
                    keyValues.Add(nameof(RB_Goods_Order.CancelTime), DateTime.Now);
                }
                else
                {
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.WaitDeal);
                    keyValues.Add(nameof(RB_Goods_Order.IsApplyForCancel), 1);
                    keyValues.Add(nameof(RB_Goods_Order.HistoryOrderStatus), (int)omodel.OrderStatus);
                    keyValues.Add(nameof(RB_Goods_Order.CancelRemark), remark);
                }
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.OrderId),
                          FiledValue=orderId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.UserId),
                          FiledValue=userId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.TenantId),
                          FiledValue=tenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.MallBaseId),
                          FiledValue=mallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = goods_OrderRepository.Update(keyValues, wheres, trans);
                if (flag)
                {
                    //回滚商品库存
                    if (type == 1)
                    {
                        List<int> classIdList = new List<int>();
                        int TotalIntegralNumber = 0;
                        var detailList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = omodel.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
                        if (detailList.Any())
                        {
                            string goodsIds = string.Join(",", detailList.Select(x => x.GoodsId ?? 0).Distinct());
                            var goodsList = goodsRepository.GetSingleList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId }, true);
                            var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });

                            foreach (var item in detailList)
                            {
                                var gmodel = goodsList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                                if (gmodel == null)
                                {
                                    continue;
                                }
                                if (string.IsNullOrEmpty(item.SpecificationSort) || item.OrderType == OrderTypeEnum.SDGoods)
                                {
                                    if (gmodel.IsCustomSpecification == 1)
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    if (gmodel.IsCustomSpecification != 1)
                                    {
                                        continue;
                                    }
                                    var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                                    if (speciPModel == null)
                                    {
                                        continue;
                                    }
                                    //更新商品规格表库存 + 商品表总库存
                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_SpecificationPrice.InventoryNum), (speciPModel.InventoryNum??0)+(item.Number??0)}
                                    };
                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                                FiledValue=speciPModel.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    goods_SpecificationPriceRepository.Update(keyValues2, wheres2, trans);
                                }
                                if (item.OrderType == OrderTypeEnum.SDGoods)
                                {
                                    //更新商品可预定日期
                                    var tdlist = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = item.GoodsId ?? 0, StartTime = item.TripSTime.Value.ToString("yyyy-MM-dd"), EndTime = item.TripETime.Value.ToString("yyyy-MM-dd") });
                                    if (item.CarType == GuideCarGoodsTypeEnum.Line && item.IsSpell == 1)
                                    {
                                        //只调整第一天的   其他天 直接表示已预订了
                                        var fristModel = tdlist.Where(x => x.Date == Convert.ToDateTime(item.TripSTime.Value.ToString("yyyy-MM-dd"))).FirstOrDefault();
                                        //第一条更新数量  如果OK咯  更新已预定
                                        if (fristModel != null)
                                        {
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                        {
                                            { nameof(RB_Goods_TargetDate.IsReserve), 1 },
                                            { nameof(RB_Goods_TargetDate.ReserveNum), (fristModel.ReserveNum) - (item.Number ?? 0) }
                                        };

                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_Goods_TargetDate.Id),
                                                    FiledValue=fristModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                            goods_TargetDateRepository.Update(keyValues1, wheres1, trans);
                                            if ((fristModel.ReserveNum) - (item.Number ?? 0) <= 0)
                                            {
                                                //其他的直接改未预定
                                                foreach (var qitem in tdlist.Where(x => x.Date != Convert.ToDateTime(item.TripSTime.Value.ToString("yyyy-MM-dd")) && x.IsReserve == 2))
                                                {
                                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                    { nameof(RB_Goods_TargetDate.IsReserve),1},
                                                    { nameof(RB_Goods_TargetDate.ReserveNum),0},
                                                };
                                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                            FiledName=nameof(RB_Goods_TargetDate.Id),
                                                            FiledValue=qitem.Id,
                                                            OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                    goods_TargetDateRepository.Update(keyValues2, wheres2, trans);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //直接回滚所有的日期 为可预定
                                        foreach (var qitem in tdlist)
                                        {
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_TargetDate.IsReserve),1},
                                            { nameof(RB_Goods_TargetDate.ReserveNum),0},
                                        };
                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Goods_TargetDate.Id),
                                                  FiledValue=qitem.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                            goods_TargetDateRepository.Update(keyValues1, wheres1, trans);
                                        }
                                    }
                                }
                                else
                                {
                                    if (omodel.OrderClassify != 2)
                                    {
                                        //更新商品表库存
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods.InventoryNum), (gmodel.InventoryNum??0)+(item.Number??0)}
                                        };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_Goods.Id),
                                                    FiledValue=gmodel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goodsRepository.Update(keyValues1, wheres1, trans);
                                    }
                                }
                                if (omodel.DepositId > 0)
                                {
                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderDetail_Extend.DepositRefundMoney),item.DepositMoney + item.DepositFreightMoney}
                                    };
                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Goods_OrderDetail_Extend.Id),
                                              FiledValue=item.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    goods_OrderDetailRepository.Update(keyValues1, wheres1, trans);
                                }
                                goods_LogRepository.Insert(new RB_Goods_Log()
                                {
                                    Id = 0,
                                    Type = 2,
                                    SourceId = item.GoodsId,
                                    Content = $"取消订单{orderId}，还原商品库存:" + item.Number,
                                    CreateDate = DateTime.Now,
                                    MallBaseId = mallBaseId,
                                    TenantId = tenantId
                                });

                                if (item.IntegralNumber > 0)
                                {
                                    TotalIntegralNumber += (item.IntegralNumber ?? 0);
                                }

                                if (item.ClassId > 0)
                                {
                                    classIdList.Add(item.ClassId);
                                }
                            }
                        }
                        var umodel = member_UserRepository.GetEntity(omodel.UserId);
                        //积分抵扣回滚
                        if (TotalIntegralNumber > 0)
                        {
                            if (umodel.CustomerChildrenId > 0)
                            {
                                //进入erp同业积分更新
                                try
                                {
                                    customer_IntegralRepository.Insert(new Model.Entity.Customer.RB_Customer_Integral()
                                    {
                                        Id = 0,
                                        CustomerId = umodel.CustomerId,
                                        CustomerChildrenId = umodel.CustomerChildrenId,
                                        GroupId = 2,
                                        OrderId = omodel.OrderId,
                                        TCID = 0,
                                        OrderType = 2,
                                        IsDeduction = 1,
                                        IntegralNum = TotalIntegralNumber,
                                        CreateTime = DateTime.Now,
                                        CustomerType = 1,
                                        Description = "赞羊订单取消返回积分抵扣，订单号：" + omodel.OrderNo,
                                        MallCommission = 0 - detailList.Sum(x => x.FXCommission)
                                    });
                                    //更新同行积分数
                                    customer_IntegralRepository.UpdateCustomerIntegral(umodel.CustomerId, 0 - TotalIntegralNumber);
                                }
                                catch { }
                            }
                            else
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User_Extend.Integral),umodel.Integral + TotalIntegralNumber}
                            };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_User_Extend.Id),
                                      FiledValue=umodel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                                bool flag2 = member_UserRepository.Update(keyValues1, wheres1, trans);
                                if (flag2)
                                {
                                    member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                                    {
                                        Id = 0,
                                        CreateDate = DateTime.Now,
                                        Description = "订单取消返回积分抵扣，订单号：" + omodel.OrderNo,
                                        Image = 0,
                                        Integral = TotalIntegralNumber,
                                        MallBaseId = omodel.MallBaseId,
                                        PlatformType = omodel.OrderSource,
                                        Remarks = "",
                                        TenantId = omodel.TenantId,
                                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                        UserId = omodel.UserId,
                                        OrderId = omodel.OrderId
                                    }, trans);
                                }
                            }
                        }
                        //优惠券回滚
                        if (!string.IsNullOrEmpty(omodel.CouponsIds))
                        {
                            var cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 1, Ids = omodel.CouponsIds, UserId = omodel.UserId, TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId });
                            foreach (var item in cList)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DiscountCoupon_Extend.UseState),0}
                                };
                                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);
                            }
                        }
                        //储值卡回滚
                        if (omodel.DepositId > 0)
                        {
                            var depositModel = member_DepositBuyRepository.GetEntity(omodel.DepositId);
                            if (depositModel != null)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DepositBuy_Extend.SurplusPrice),depositModel.SurplusPrice + omodel.DepositMoney}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_DepositBuy_Extend.Id),
                                          FiledValue=depositModel.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_DepositBuyRepository.Update(keyValues1, wheres1, trans);
                                member_DepositBalanceRepository.Insert(new RB_Member_DepositBalance()
                                {
                                    Id = 0,
                                    UserId = umodel.Id,
                                    Balance = depositModel.SurplusPrice,
                                    CouponIco = depositModel.CouponIco,
                                    CreateDate = DateTime.Now,
                                    DepositPrice = depositModel.DepositPrice,
                                    MallBaseId = umodel.MallBaseId,
                                    MergeType = 3,
                                    Name = depositModel.Name,
                                    NewDepositBuyId = 0,
                                    OldDepositBuyId = 0,
                                    Remarks = "订单" + omodel.OrderNo + "取消，退回使用储值卡抵扣" + omodel.DepositMoney + "金额",
                                    SalePrice = depositModel.SalePrice,
                                    Status = 0,
                                    Surplus = depositModel.SurplusPrice + omodel.DepositMoney,
                                    TenantId = umodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income
                                }, trans);
                            }
                        }

                        //余额支付回滚

                        if (omodel.OrderClassify == 2 && omodel.EducationMoney > 0)
                        {
                            var uclist = education_MemberUseCouponRepository.GetList(new Model.Entity.Education.RB_Education_MemberUseCoupon() { OrderId = omodel.OrderId });
                            var ucModel = uclist.FirstOrDefault();
                            if (ucModel != null)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(Model.Entity.Education.RB_Education_MemberUseCoupon.Status),1}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(Model.Entity.Education.RB_Education_MemberUseCoupon.Id),
                                          FiledValue=ucModel.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                education_MemberUseCouponRepository.Update(keyValues1, wheres1, trans);

                                var educationModel = education_MemberCouponRepository.GetEntity(ucModel.MemberCouponId ?? 0);
                                if (educationModel != null)
                                {
                                    //更新用户课程卡 已使用数量
                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Education_MemberCoupon_Extend.UseHeXiao),educationModel.UseHeXiao - ucModel.UseHeXiao}
                                    };
                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Education_MemberCoupon_Extend.Id),
                                              FiledValue=educationModel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    education_MemberCouponRepository.Update(keyValues2, wheres2, trans);
                                }
                            }
                        }

                        if (classIdList != null && classIdList.Any())
                        {
                            var resultInfo = new
                            {
                                Msg = new { Order = classIdList },
                            };
                            System.Threading.Tasks.Task.Run(() => Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("EduUpdateGoodsSpecification"), JsonHelper.Serialize(resultInfo), ""));
                        }

                    }
                    Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                    {
                        Id = 0,
                        Type = 1,
                        SourceId = orderId,
                        Content = type == 1 ? "客人取消订单" : "客人申请取消订单",
                        CreateDate = DateTime.Now,
                        MallBaseId = mallBaseId,
                        TenantId = tenantId
                    }));
                    if (type == 2 && omodel.OrderClassify == 0 && omodel.TenantId == 16 && omodel.MallBaseId == 6)
                    {
                        try
                        {
                            weChatPublicAccountModule.SendOrderCancelMsg(omodel.TenantId, omodel.MallBaseId, omodel.OrderNo, DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分"), omodel.Income.ToString());
                        }
                        catch (Exception ex)
                        {
                            Common.Plugin.LogHelper.Write(ex, "CancelAppletGoodsOrderInfo");
                        }
                    }
                    if (type == 2)
                    {
                        #region 管理端通知
                        message_NoticeRepository.Insert(new RB_Message_Notice()
                        {
                            Id = 0,
                            CreateDate = DateTime.Now,
                            IsLook = 2,
                            MallBaseId = mallBaseId,
                            OrderNo = omodel.OrderNo,
                            SourceId = omodel.OrderId,
                            TenantId = tenantId,
                            Type = 2,
                            UserId = userId
                        });
                        #endregion
                    }
                }
                goods_OrderRepository.DBSession.Commit();
                return flag;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "CancelAppletGoodsOrderInfo");
                goods_OrderRepository.DBSession.Rollback();
                return false;
            }

        }

        /// <summary>
        /// 申请售后
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetAppletMyOrderAfterSale(RB_Goods_OrderAfterSale_Extend demodel)
        {
            var dModel = goods_OrderDetailRepository.GetEntity(demodel.OrderDetialId);
            if (demodel.Type == 1 && ((dModel.Final_Price ?? 0) - dModel.DepositMoney) < demodel.Refund)
            {
                return false;
            }
            if (dModel.TenantId == 29)//2024-02-22 add by:W
            {
                var orderModel = goods_OrderRepository.GetEntity(dModel.OrderId);
                if (orderModel?.PayIncome != orderModel.Income)//支付金额与实收金额不一致  //判断这个订单的实收金额
                {
                    demodel.Income = dModel.Final_Price - ((dModel.Final_Price ?? 0) * (1 - (dModel.DepositRatio / 100)));
                }
                else
                {
                    demodel.Income = ((dModel.Final_Price ?? 0) - dModel.DepositMoney);
                }
            }
            else
            {
                demodel.Income = ((dModel.Final_Price ?? 0) - dModel.DepositMoney);
            }

            demodel.RefundActual ??= 0;
            demodel.Refund ??= 0;
            demodel.DeliveryId ??= 0;
            demodel.CreateDate = DateTime.Now;
            demodel.OrderId = dModel.OrderId;
            demodel.ReExpressId ??= 0;
            demodel.ReExpressNumber ??= "";
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.ReOrderNo = "RE" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;

            var oasList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = demodel.OrderDetialId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, false);
            if (oasList.Any())
            {
                return false;
            }
            int Id = goods_OrderAfterSaleRepository.Insert(demodel);
            if (Id > 0)
            {
                //


                //流程
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "买家申请售后",
                    Type = 1,
                    ReOrderId = Id,
                    TenantId = demodel.TenantId,
                    CreateDate = DateTime.Now,
                    MallBaseId = demodel.MallBaseId
                });
                #region 管理端通知
                message_NoticeRepository.Insert(new RB_Message_Notice()
                {
                    Id = 0,
                    CreateDate = DateTime.Now,
                    IsLook = 2,
                    MallBaseId = demodel.MallBaseId,
                    OrderNo = demodel.ReOrderNo,
                    SourceId = Id,
                    TenantId = demodel.TenantId,
                    Type = 3,
                    UserId = demodel.UserId ?? 0
                });
                #endregion
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取小程序配置
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public Model.Extend.BaseSetUp.RB_MallBase_Extend GetMallBaseInfo(int TenantId, int MallBaseId)
        {
            var mallbaseModel = mallBaseRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_MallBase_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            return mallbaseModel;
        }

        /// <summary>
        /// 获取买家发货界面信息
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <returns></returns>
        public ApiResult GetAppletOrderBuyerToDeliverInfo(int reOrderId)
        {
            var omodel = goods_OrderAfterSaleRepository.GetEntity(reOrderId);
            if (omodel == null)
            {
                return ApiResult.Failed("售后订单不存在");
            }
            if (omodel.ReOrderStatus != OrderAfterSaleStatusEnum.DeliveryToBuyer)
            {
                return ApiResult.Failed("状态不正确，刷新后再试");
            }
            if ((omodel.DeliveryId ?? 0) <= 0)
            {
                return ApiResult.Failed("该订单出错啦，请联系管理员");
            }
            var delmodel = logistics_DeliveryRepository.GetEntity(omodel.DeliveryId);
            if (delmodel == null)
            {
                return ApiResult.Failed("收货地址有误，请联系管理员");
            }
            string DistrictAddress = (destinationRepository.GetEntity(delmodel.ProvinceId)?.Name ?? "") + " " + (destinationRepository.GetEntity(delmodel.CityId)?.Name ?? "") + " " + (destinationRepository.GetEntity(delmodel.DistrictId)?.Name ?? "");
            var detailmodel = goods_OrderDetailRepository.GetEntity(omodel.OrderDetialId);
            if (detailmodel == null)
            {
                return ApiResult.Failed("订单不存在，请联系管理员");
            }
            string ImagePath = detailmodel.CoverImage;

            return ApiResult.Success("", new
            {
                omodel.ReOrderId,
                omodel.ReOrderStatus,
                ReOrderStatusName = omodel.ReOrderStatus.GetEnumName(),
                omodel.Type,
                omodel.Remark,
                omodel.Refund,
                VoucherList = string.IsNullOrEmpty(omodel.Voucher) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(omodel.Voucher),
                RecipientInfo = new
                {
                    delmodel.Name,
                    delmodel.Mobile,
                    DistrictAddress,
                    delmodel.Address,
                    delmodel.Remarks
                },
                OrderInfo = new
                {
                    detailmodel.Id,
                    ImagePath,
                    detailmodel.GoodsName,
                    detailmodel.GoodsId,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(detailmodel.Specification),
                    detailmodel.Final_Price
                }
            });
        }

        /// <summary>
        /// 售后买家发货
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="expressId"></param>
        /// <param name="expressNumber"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetAppletOrderSendGoods(int reOrderId, int expressId, string expressNumber, int tenantId, int mallBaseId)
        {
            var omodel = goods_OrderAfterSaleRepository.GetEntity(reOrderId);
            if (omodel == null)
            {
                return false;
            }
            if (omodel.ReOrderStatus != OrderAfterSaleStatusEnum.DeliveryToBuyer)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderAfterSale.ReOrderStatus),OrderAfterSaleStatusEnum.ReceivedBySeller},
                { nameof(RB_Goods_OrderAfterSale.ReExpressId),expressId},
                { nameof(RB_Goods_OrderAfterSale.ReExpressNumber),expressNumber},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                      FiledValue=reOrderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderAfterSaleRepository.Update(keyValues, wheres);
            if (flag)
            {
                //流程
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "买家已发货",
                    Type = 1,
                    ReOrderId = reOrderId,
                    TenantId = tenantId,
                    CreateDate = DateTime.Now,
                    MallBaseId = mallBaseId
                });
                return true;
            }
            return flag;
        }

        /// <summary>
        /// 后台处理买家发货
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetUserOrderAfterSaleSendGoods(int reOrderId, int tenantId, int mallBaseId)
        {
            var omodel = goods_OrderAfterSaleRepository.GetEntity(reOrderId);
            if (omodel == null)
            {
                return false;
            }
            if (omodel.ReOrderStatus != OrderAfterSaleStatusEnum.DeliveryToBuyer)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>();
            if (omodel.Type == 2)
            {
                keyValues.Add(nameof(RB_Goods_OrderAfterSale.ReOrderStatus), OrderAfterSaleStatusEnum.ReceivedBySeller);
            }
            else
            {
                keyValues.Add(nameof(RB_Goods_OrderAfterSale.ReOrderStatus), OrderAfterSaleStatusEnum.RefundedBySeller);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                      FiledValue=reOrderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderAfterSaleRepository.Update(keyValues, wheres);
            if (flag)
            {
                //流程
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "管理员操作无需客人发货",
                    Type = 1,
                    ReOrderId = reOrderId,
                    TenantId = tenantId,
                    CreateDate = DateTime.Now,
                    MallBaseId = mallBaseId
                });
                return true;
            }
            return flag;
        }

        /// <summary>
        /// 获取售后订单详情
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletOrderAfterSaleInfo(int reOrderId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderAfterSaleRepository.GetEntity<RB_Goods_OrderAfterSale_Extend>(reOrderId);
            if (model == null)
            {
                return ApiResult.ParamIsNull();
            }
            var gModel = goods_OrderRepository.GetEntity<RB_Goods_Order_Extend>(model.OrderId);
            if (gModel == null)
            {
                return ApiResult.ParamIsNull("订单不存在");
            }
            var odModel = goods_OrderDetailRepository.GetEntity<RB_Goods_OrderDetail_Extend>(model.OrderDetialId);
            if (odModel == null)
            {
                return ApiResult.ParamIsNull("订单明细不存在");
            }
            odModel.CoverImagePath = odModel.CoverImage;

            //物流信息
            List<object> TExpressList = new List<object>();
            List<object> HExpressList = new List<object>();
            if (model.DeliveryId > 0 && model.ReExpressId > 0)
            {
                var leModel = logistics_ExpressRepository.GetEntity(model.ReExpressId);
                TExpressList.Add(new
                {
                    ExpressName = leModel.Name ?? "",
                    ExpressNumber = model.ReExpressNumber,
                    Type = 1
                });
            }
            if (model.Type == 2)
            {
                var oeModel = goods_OrderExpressRepository.GetList(new RB_Goods_OrderExpress_Extend() { AfterSaleOrderId = model.ReOrderId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                if (oeModel != null)
                {
                    if (oeModel.Type == 1)
                    {
                        var leModel = logistics_ExpressRepository.GetEntity(oeModel.ExpressId);
                        HExpressList.Add(new
                        {
                            ExpressName = leModel.Name ?? "",
                            oeModel.ExpressNumber,
                            Type = 1
                        });
                    }
                    else
                    {
                        HExpressList.Add(new
                        {
                            ExpressName = "",
                            ExpressNumber = oeModel.Remark,
                            Type = 2
                        });
                    }
                }
            }


            //获取订阅消息
            var miniModel = miniProgramRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = gModel.TenantId, MallBaseId = gModel.MallBaseId }).FirstOrDefault();

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.AuditResultTpl))
                {
                    template_message_list.Add(miniModel.AuditResultTpl);
                }
            }
            return ApiResult.Success("", new
            {
                template_message_list,
                model.ReOrderId,
                model.ReOrderNo,
                model.Type,
                TypeName = model.Type == 1 ? "退货退款" : "换货",
                VoucherList = string.IsNullOrEmpty(model.Voucher) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(model.Voucher),
                model.Income,
                model.Refund,
                model.RefundActual,
                model.ReOrderStatus,
                model.Remark,
                model.ReRemark,
                ReOrderStatusName = model.ReOrderStatus.GetEnumName(),
                AuditTime = model.AuditTime.HasValue ? model.AuditTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = model.FinishTime.HasValue ? model.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                OrderInfo = new
                {
                    odModel.OrderId,
                    odModel.CoverImagePath,
                    odModel.GoodsId,
                    odModel.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(odModel.Specification),
                    odModel.Number,
                    odModel.Final_Price
                },
                TExpressList,
                HExpressList
            });
        }

        /// <summary>
        /// 获取售后订单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderAfterSale_Extend> GetAppletOrderAfterPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderAfterSale_Extend demodel)
        {
            var list = goods_OrderAfterSaleRepository.GetAppletPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string orderDetilIds = string.Join(",", list.Select(x => x.OrderDetialId));
                var gdList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderDetailIds = orderDetilIds });
                if (gdList.Any())
                {
                    foreach (var item in gdList)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }

                foreach (var item in list)
                {
                    item.OrderDetailModel = gdList.Where(x => x.Id == item.OrderDetialId).FirstOrDefault();
                }
            }
            return list;
        }

        /// <summary>
        /// 订单确认收货
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetAppletOrderGoodsReceiving(int orderId, int userId, int tenantId, int mallBaseId, Microsoft.AspNetCore.Http.IHttpContextAccessor accessor)
        {
            var omodel = goods_OrderRepository.GetEntity(orderId);
            if (omodel == null) { return false; }
            if (omodel.OrderStatus != OrderStatusEnum.WaitReceiving) { return false; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Received},
                { nameof(RB_Goods_Order.ReceivingTime), DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.UserId),
                      FiledValue=userId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.TenantId),
                      FiledValue=tenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.MallBaseId),
                      FiledValue=mallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志                
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = "客人确认收货",
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderId,
                    TenantId = tenantId,
                    Type = 1
                });

                //收货  自动确认订单
                SetOrderOperation(omodel.RefMapperTo<RB_Goods_Order_Extend>(), 6, "", 0, tenantId, mallBaseId, accessor);
            }
            return flag;
        }
        #endregion

        /// <summary>
        /// 获取教育销售的基础信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Education_EduSell_Extend> GetEducationSellBaseInfo(RB_Education_EduSell_Extend query)
        {
            var list = education_EduSellRepository.GetEducationSellBaseInfo(query);
            if (list != null && list.Any(x => x.EduSellId > 0))
            {
                string qIds = string.Join(",", list.Where(x => x.EduSellId > 0).Distinct().Select(x => x.EduSellId));
                var employeeList = RB_AccountRepository.GetEmployeeListRepository(new Employee_ViewModel { QIds = qIds }).ToList();
                if (employeeList != null && employeeList.Any())
                {
                    foreach (var item in list)
                    {
                        item.employeeModel = new Employee_ViewModel();
                        item.employeeModel = employeeList.Where(x => x.Id == item.EduSellId).FirstOrDefault();
                    }
                }
            }
            return list;
        }

        #region  评论标签管理

        /// <summary>
        /// 获取评论标签分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Comment_Label_Extend> GetCommentLabelPageModule(int pageIndex, int pageSize, out long totalCount, RB_Comment_Label_Extend query)
        {
            var list = comment_LabelRepository.GetCommentLabelPageRepository(pageIndex, pageSize, out totalCount, query);
            return list;
        }


        /// <summary>
        /// 获取评论标签列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Comment_Label_Extend> GetCommentLabelListModule(RB_Comment_Label_Extend query)
        {
            var list = comment_LabelRepository.GetCommentLabelListRepository(query);
            return list;
        }

        /// <summary>
        /// 新增修改评论标签
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetCommentLabelModule(RB_Comment_Label_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Comment_Label_Extend.Name),model.Name },
                    {nameof(RB_Comment_Label_Extend.UpdateDate),model.UpdateDate },
                };
                flag = comment_LabelRepository.Update(fileds, new WhereHelper(nameof(RB_Comment_Label_Extend.Id), model.Id));
            }
            else
            {
                var newId = comment_LabelRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取频率标签
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Comment_Label_Extend GetCommentLabelModule(int Id)
        {
            var extModel = comment_LabelRepository.GetEntity<RB_Comment_Label_Extend>(Id);
            return extModel;
        }

        /// <summary>
        /// 根据编号删除评论标签
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveCommentLabelModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Comment_Label_Extend.Status),1 },
                {nameof(RB_Comment_Label_Extend.UpdateDate),DateTime.Now },
            };
            var flag = comment_LabelRepository.Update(fileds, new WhereHelper(nameof(RB_Comment_Label_Extend.Id), Id));
            return flag;
        }
        #endregion
    }
}
