using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mall.AOP.CustomerAttribute;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Enum;
using Mall.Common.Enum.Goods;
using Mall.Common.Enum.User;
using Mall.Common.Plugin;
using Mall.Model.Entity.Finance;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.User;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.Education;
using Mall.Model.Extend.Finance;
using Mall.Model.Extend.GuideCar;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
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 Mall.ThirdCore.Message;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 商品处理层
    /// </summary>
    public partial class OrderModule
    {
        /// <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_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>
        /// 用户余额
        /// </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_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_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 static 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();
        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_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 RB_GuideCar_SiteRepository guideCar_SiteRepository = new RB_GuideCar_SiteRepository();
        /// <summary>
        /// 车辆颜色
        /// </summary>
        private RB_GuideCar_CarColorRepository guideCar_CarColorRepository = new RB_GuideCar_CarColorRepository();

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

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

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

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

                #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.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();
                                    item.SpecificationList.Add(sModel.Name + ":" + svModel.Name);
                                }
                            }
                            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 = false;
            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.Number),scModel.Number + demodel.Number},
                    { nameof(RB_Goods_ShoppingCart.UpdateDate),DateTime.Now},
                };
                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
                }) > 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 ?? "");
                }
            }
            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 });
            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);
                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;
                    }
                }
            }
            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 });
            //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)
            //    {
            //        item.ExpressName = logistics_ExpressRepository.GetEntity(item.ExpressId)?.Name ?? "";
            //    }
            //}

            //是否可以申请售后
            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.DeliveryMethod,
                DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                model.PreferPrice,
                model.Income,
                model.CouponMoney,
                model.FreightMoney,
                model.Consignee,
                model.Mobile,
                model.DistrictAddress,
                model.ShoppingAddress,
                IsHaveExpress = erlist.Any() ? 1 : 2,
                DetailList = model.DetailList.Select(x => new
                {
                    DetailId = x.Id,
                    x.GoodsId,
                    x.GoodsName,
                    x.CoverImagePath,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(x.Specification),
                    x.Number,
                    x.Final_Price,
                    x.IsComment,
                    x.IsApplyForAfterSale,
                    x.FreeShippingRemarks
                }),
                model.IsApplyForCancel,
                model.RejectRemark,
                model.IsCanApplyForAfterSale,
                model.PresentFXGrade,
                model.BuyerMessage
            });
        }

        /// <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
                });
                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 ?? "";
                }
            }
            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,
                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,
                }),
                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>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletMyOrderAfterSaleInfo(int orderDetailId, int userId, int tenantId, int mallBaseId)
        {
            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;
            if (omodel.Income < dModel.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,
                dModel.FreightMoney
            });
        }


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

        /// <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;
            }
            //积分
            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();
            }
            //快递默认
            //demodel.DeliveryMethod ??= OrderDeliveryMethodEnum.ExpressDistribution;
            #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;//总快递费  总商品价格  总原价  总售价
            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
            List<object> goods_list = new List<object>();
            List<FreeShippingGoodsDetail> SatisfiedGoodsList = new List<FreeShippingGoodsDetail>();//可包邮的商品
            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 });
                //区域
                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>();
                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 优惠卷初始化
                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
                //初始化值
                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 图片
                    gmodel.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
                            });
                        }
                        //封面图
                        gmodel.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;
                        }
                    }

                    //规格赋值
                    //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();
                                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
                                });
                            }
                        }
                        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);
                        }

                        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

                    Total_integral_price += (item.IntegralMoney ?? 0);
                    Total_use_integral += (item.IntegralNumber ?? 0);
                    TotalGoodsMoney += item.Final_Price ?? 0;
                    TotalGoodsOriginalMoney += (gmodel.OriginalPrice ?? 0) * (item.Number ?? 0);
                    TotalGoodsSellMoney += gmodel.MemberPrice * (item.Number ?? 0);
                    item.Unit_Price = gmodel.SellingPrice ?? 0;
                    item.Original_Price = gmodel.OriginalPrice ?? 0;
                    item.MemberPrice = gmodel.MemberPrice;
                    item.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

                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;//总价格需减去优惠券金额
                    }

                    #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

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

                    goods_list.Add(new
                    {
                        id = gmodel.Id,
                        name = gmodel.Name,
                        categoryIdList = item.CategoryIdList,
                        specificationNameList = item.SpecificationNameList,
                        num = item.Number,
                        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,
                        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,
                            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 = gmodel.CoverImage,
                            individual_share = umodel?.IsDistributor ?? 2,// 是否分销商
                            share_type = gmodel.SeparateDistributionMoneyType,//分销佣金类型,
                            member_price = item.MemberPrice,
                            integral_price = demodel.Use_Integral == 1 ? item.IntegralMoney : 0,//积分抵扣金额
                            use_integral = demodel.Use_Integral == 1 ? item.IntegralNumber : 0,
                            couponMoney,
                            //discount= [],
                            //extra= [],
                            //goods_warehouse_id = 19813,
                            name = gmodel.Name,
                            cover_pic = gmodel.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 = gmodel.CoverImage,
                        is_level_alone = gmodel.SeparateSetMember,//是否单独设置会员价
                        //custom_currency= [],
                        is_level = gmodel.EnjoyMember,//是否销售会员价格
                        //goods_warehouse_id = 19813,
                        sign = "",
                        confine_order_count = gmodel.LimitBuyOrderNum,//限制订单数量
                        form_id = gmodel.FormsId,//表单id
                        marketingLogo = gmodel.MarketingLogo
                        //goodsWarehouse = new
                        //{
                        //    id = 19813,
                        //    mall_id = 1285,
                        //    name = "测试商品【勿拍】",
                        //    original_price = "100000.00",
                        //    cost_price = "0.00",
                        //    detail = "<p>测试</p>",
                        //    cover_pic = "https://cdnimg.iotweixin.com/uploads/mall1285/20200303/0729b37fd19a002733018a1ece30ca55.jpg",
                        //    pic_url = "[{\"id=\"77531\",\"pic_url=\"https:\\/\\/cdnimg.iotweixin.com\\/uploads\\/mall1285\\/20200303\\/0729b37fd19a002733018a1ece30ca55.jpg\"},{\"id=\"77530\",\"pic_url=\"https:\\/\\/cdnimg.iotweixin.com\\/uploads\\/mall1285\\/20200303\\/8eebc4fc427d7d2bbd2625f5f3448c5b.jpg\"}]",
                        //    video_url = "https://cdnimg.iotweixin.com/uploads/mall1285/20200303/5f26c823c9118e7646681152ef441fd7.mp4",
                        //    unit = "件",
                        //    created_at = "2020-05-25 16:05:02",
                        //    updated_at = "2020-05-25 16:05:02",
                        //    deleted_at = "0000-00-00 00:00:00",
                        //    is_delete = 0
                        //},
                        //form_data= null,
                        //form= null
                    });
                }
            }

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

            var minModel = miniProgramRepository.GetEntity(demodel.MallBaseId);
            //积分
            var IntegralObj = new
            {
                can_use = IsPointsDeduction,
                use = demodel.Use_Integral == 1 ? true : false,
                use_num = Total_use_integral,
                deduction_price = Total_integral_price
            };
            //满足全局包邮的规则
            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
                    });
                }
            }

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

            #endregion

            mch_list.Add(new
            {
                mch = new
                {
                    id = minModel?.MallBaseId ?? 0,
                    name = minModel?.MallName ?? ""
                },
                goods_list,
                pinkageList = PinkageList,
                express_price = TotalExpress,
                remark = "",
                //order_form_data= [],
                total_goods_price = TotalGoodsSellMoney,
                total_goods_original_price = TotalGoodsOriginalMoney,
                member_discount,
                coupon = new
                {
                    enabled = true,
                    use = CouponsMoney > 0 && demodel.User_Coupon_Id > 0 ? true : false,
                    coupon_discount = CouponsMoney,
                    user_coupon_id = CouponsMoney > 0 ? demodel.User_Coupon_Id ?? 0 : 0
                },
                integral = IntegralObj,
                delivery = Delivery,
                //store= null,
                store_select_enable = true,
                total_price = TotalGoodsMoney,
                //pick_up_enable= true,
                //pick_up_price= null,
                //diff_goods_form_count= 0,
                //has_goods_form= false
            });

            //minModel

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

            if (minModel != null)
            {
                if (!string.IsNullOrWhiteSpace(minModel.OrderSuccessTpl))
                {
                    template_message_list.Add(minModel.OrderSuccessTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderCancelTpl))
                {
                    template_message_list.Add(minModel.OrderCancelTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderDeliverGoodsTpl))
                {
                    template_message_list.Add(minModel.OrderDeliverGoodsTpl);
                }
            }
            var Robj = new
            {
                mch_list,
                promptNoSuperiorFY = PromptNoSuperiorFY,
                total_price = TotalGoodsMoney,
                price_enable = true,
                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,
                //has_ziti= false,
                //custom_currency_all= [],
                //allZiti= false,
                //hasCity= false,
                template_message_list = template_message_list //new List<string>() { "WPELErDfYO3JnizA5Zikta6Y8qrBBAgecuj2aLoucuY", "pCmTJwvTqNpyRREo7vvqIYBcrATNWoitfbLS61fLhzU", "i6QPsaOHgfNwlIRMwmvFGSCqX28g0cRa8XaLZ5_gpgc" }
            };
            #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 (demodel.SmallShopsId == 0)
            {
                demodel.SmallShopsId = umodel.SmallShopId;
            }
            if (umodel.Blacklist == 1)
            {
                return ApiResult.Failed("您在黑名单状态无法下单，请联系管理员核实");
            }
            List<int> disList = new List<int>();
            disList.Add(demodel.Province ?? 0);
            disList.Add(demodel.City ?? 0);
            disList.Add(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>();
            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
            List<FreeShippingGoodsDetail> SatisfiedGoodsList = new List<FreeShippingGoodsDetail>();//可包邮的商品
            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 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

                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.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.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;//商品重量                    

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

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

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

                    #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));
                        }
                    }
                }
            }
            if (demodel.FreightMoney != TotalExpress)
            {
                return ApiResult.Failed("运费不正确");
            }
            if (CouponsMoney != demodel.CouponMoney)
            {
                return ApiResult.Failed("优惠金额计算有误");
            }
            //验证总额
            if (demodel.Income != (TotalMoney + TotalExpress))
            {
                return ApiResult.Failed("订单合计金额不正确");
            }
            demodel.PreferPrice = TotalMoney + CouponsMoney;

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

            var trans = goods_OrderRepository.DbTransaction;
            try
            {
                Random R = new Random();
                int Rstr = R.Next(111, 999);
                demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                demodel.PaymentWay = OrderPaymentTypeEnum.OnlinePayment;//先默认在线支付
                demodel.Remark ??= "";
                demodel.ApplyForCancelStatus ??= 0;
                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);

                    //用户订单数增加
                    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 (demodel.IsFormShoppingCart == 1)
                    {
                        foreach (var cartItem in demodel.ShoppingCartIdList)
                        {
                            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                { nameof(RB_Goods_ShoppingCart.Status),1},
                                { nameof(RB_Goods_ShoppingCart.UpdateDate),DateTime.Now}
                            };
                            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.Id),
                                        FiledValue=cartItem,
                                        OperatorEnum=OperatorEnum.IN
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.UserId),
                                        FiledValue=demodel.UserId,
                                        OperatorEnum=OperatorEnum.IN
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.TenantId),
                                        FiledValue=demodel.TenantId,
                                        OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.MallBaseId),
                                        FiledValue=demodel.MallBaseId,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_ShoppingCartRepository.Update(keyValues2, wheres2);
                        }
                    }
                    //下线
                    if (umodel.DownlineCondition == Common.Enum.User.DistrbutorReferralsEnum.SCXD && umodel.IsBeDownline == 2)
                    {
                        //首次下单成为下线
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            {nameof(RB_Member_User_Extend.SuperiorId),umodel.WaitSuperiorId },
                            {nameof(RB_Member_User_Extend.IsBeDownline),1 },
                            {nameof(RB_Member_User_Extend.BeDownlineDate),DateTime.Now },
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                  FiledValue=umodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        member_UserRepository.Update(keyValues1, wheres1, trans);
                    }

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

        /// 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 = false;
            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>();
            disList.Add(demodel.Province ?? 0);
            disList.Add(demodel.City ?? 0);
            disList.Add(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;
            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_Education_MemberCoupon_Extend> eList = new List<RB_Education_MemberCoupon_Extend>();
            List<RB_Education_Coupon_Extend> deList = new List<RB_Education_Coupon_Extend>();
            List<RB_Education_CouponProduct_Extend> edcpList = new List<RB_Education_CouponProduct_Extend>();
            if (demodel.Use_Education_Id > 0)
            {
                if (demodel.User_Coupon_Id > 0)
                {
                    message = "套餐卡与优惠券不能同时使用";
                    return false;
                }
                if (demodel.Use_Integral > 0)
                {
                    message = "套餐卡与积分抵扣不能同时使用";
                    return false;
                }
                eList = education_MemberCouponRepository.GetList(new RB_Education_MemberCoupon_Extend() { Ids = (demodel.Use_Education_Id ?? 0).ToString(), UserId = umodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                if (eList.Any())
                {
                    var educationModel = eList.FirstOrDefault();
                    if (educationModel.HeXiao <= educationModel.UseHeXiao)
                    {
                        message = "套餐卡剩余次数不足";
                        return false;
                    }
                    string cIds = string.Join(",", eList.Select(x => x.CouponId).Distinct());
                    deList = education_CouponRepository.GetDiscountCouponList(new RB_Education_Coupon_Extend() { CouponIds = cIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                    edcpList = education_CouponProductRepository.GetListByDiscountCouponIds(new Model.Entity.Education.RB_Education_Coupon() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, cIds, true);
                    if (deList.Any())
                    {
                        foreach (var item in eList)
                        {
                            if (item.CouponId > 0)
                            {
                                if (!deList.Where(x => x.ID == item.CouponId).Any())
                                {
                                    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;
                    }
                    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 = 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)
                    {
                        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)
            {
                message = "优惠金额计算有误";
                return false;
            }

            //验证总额
            if (demodel.Income != (TotalMoney - EducationMoney))
            {
                message = "订单合计金额不正确";
                return false;
            }
            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;
                demodel.PaymentWay = OrderPaymentTypeEnum.OnlinePayment;//先默认在线支付
                demodel.Remark ??= "";
                demodel.ApplyForCancelStatus ??= 0;
                if (demodel.Income == 0)
                {
                    demodel.OrderStatus = OrderStatusEnum.Completed;
                    demodel.PaymentTime = DateTime.Now;
                    demodel.DeliveryTime = DateTime.Now;
                    demodel.ReceivingTime = DateTime.Now;
                    demodel.FinishTime = DateTime.Now;
                }
                int OrderId = goods_OrderRepository.Insert(demodel);
                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.GoodsId), 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="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 = DcommionMoney,
                                                CommissionState = 1,
                                                CreateDate = DateTime.Now,
                                                Grade = FXModel.Id,
                                                IsGoodsDistribution = 2,
                                                MallBaseId = demodel.MallBaseId,
                                                OrderDetailId = item.Id,
                                                OrderId = OrderId,
                                                Remark = "粉象 " + FXModel.GradeName + "下单返佣，返佣比例:" + (FXModel.CommissionRatio ?? 0) + "%",
                                                TenantId = demodel.TenantId,
                                                UpdateDate = DateTime.Now,
                                                UserId = numodel.Id,
                                                Type = 3,
                                                IsRemit = 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,
                    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,
                    ServiceDate = item.ServiceDate,
                    ServicepersonalId = item.ServicepersonalId,
                    ServiceTime = item.ServiceTime,
                    GoodServiceTime=item.GoodServiceTime,
                }, 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)
                {
                    //更新商品数量
                    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
            }
            //if (IntegralPresentTotal > 0)
            //{
            //    member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
            //    {
            //        Id = 0,
            //        CreateDate = DateTime.Now,
            //        Description = "订单购买赠送积分",
            //        Image = 0,
            //        Integral = IntegralPresentTotal,
            //        MallBaseId = demodel.MallBaseId,
            //        PlatformType = demodel.OrderSource,
            //        Remarks = "",
            //        TenantId = demodel.TenantId,
            //        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
            //        UserId = demodel.UserId,
            //        OrderId = OrderId
            //    }, trans);
            //}
        }

        /// <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.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;//已有商品发货，无法退款
                    }
                }
            }
            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)
                    {
                        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);
                                    }
                                }
                                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);
                                }
                            }
                        }
                        var umodel = member_UserRepository.GetEntity(omodel.UserId);
                        //积分抵扣回滚
                        if (TotalIntegralNumber > 0)
                        {
                            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.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);
                                }
                            }
                        }
                    }
                    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
                    }));
                }
                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) < demodel.Refund)
            {
                return false;
            }
            demodel.Income = dModel.Final_Price;
            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
                });
                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>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletOrderBuyerToDeliverInfo(int reOrderId, int tenantId, int mallBaseId)
        {
            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

        #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> GetGoodsOrderPageList(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)) });
                var erList = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                List<RB_Finance_Extend> flist = new List<RB_Finance_Extend>();
                if (pageSize != 10000 && demodel.TenantId == 1)
                {
                    //查询所有财务单据
                    string detailIds = string.Join(",", dlist.Select(x => x.Id));
                    flist = financeRepository.GetList(new RB_Finance_Extend() { ECOrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                }
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    //剑鱼兄需求 2020=07-30  再查询一次商品表
                    string GoodsIds = string.Join(",", dlist.Select(x => x.GoodsId).Distinct());
                    var GList = goodsRepository.GetSingleListForGoodsSubName(new RB_Goods_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, GoodsIds = GoodsIds }, true);
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                        item.IsBindExpress = erList.Where(x => x.OrderDetailId == item.Id).Any() ? 1 : 2;

                        item.GoodsSubName = GList.Where(x => x.Id == item.GoodsId).FirstOrDefault()?.SubName ?? "";

                        item.FinanceList = flist.Where(x => x.ECOrderDetailId == item.Id).ToList();// 2020-08-19 新增财务单据列表
                    }
                }
                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);

                //2020-08-25 Add By:W Start

                List<RB_Member_DiscountCoupon_Extend> memberCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                if (list.Any(x => !string.IsNullOrWhiteSpace(x.CouponsIds)))
                {
                    memberCouponList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UseState = -1, Ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x.CouponsIds)).Select(x => x.CouponsIds)) });
                }
                //2020-08-25 Add By:W  End
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    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 ?? "");
                    item.MemberDiscountCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                    if (!string.IsNullOrWhiteSpace(item.CouponsIds))
                    {

                        foreach (var itemCoupons in item.CouponsIds.Split(','))
                        {
                            item.MemberDiscountCouponList.AddRange(memberCouponList.Where(x => itemCoupons == x.Id.ToString()));
                        }
                    }

                }
            }
            return list;
        }

        /// <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> GetSDGoodsOrderPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetGuideCarOrderPageList(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)) });
                List<RB_Finance_Extend> flist = new List<RB_Finance_Extend>();
                if (pageSize != 10000 && demodel.TenantId == 1)
                {
                    //查询所有财务单据
                    string detailIds = string.Join(",", dlist.Select(x => x.Id));
                    flist = financeRepository.GetList(new RB_Finance_Extend() { ECOrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                }
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    //剑鱼兄需求 2020=07-30  再查询一次商品表
                    string GoodsIds = string.Join(",", dlist.Select(x => x.GoodsId).Distinct());
                    var GList = goodsRepository.GetSingleListForGoodsSubName(new RB_Goods_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, GoodsIds = GoodsIds }, true);

                    #region 查询司导信息
                    string siteIds = string.Join(",", dlist.Select(x => x.SiteId));
                    var sitelist = guideCar_SiteRepository.GetGuideCarSiteList(new RB_GuideCar_Site_Extend() { SiteIds = siteIds });
                    string guideIds = string.Join(",", dlist.Select(x => x.GuideId));
                    var guidelist = guideCar_GuideRepository.GetGuideCarGuideList(new RB_GuideCar_Guide_Extend() { GuideIds = guideIds });
                    string carids = string.Join(",", dlist.Select(x => x.CarId));
                    var carlist = guideCar_CarRepository.GetGuideCarCarList(new RB_GuideCar_Car_Extend() { GuideCarIds = carids });
                    string colorIds = string.Join(",", dlist.Select(x => x.CarColorId));
                    var carcolorlist = guideCar_CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend() { CarColorIds = colorIds });
                    #endregion

                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;

                        item.GoodsSubName = GList.Where(x => x.Id == item.GoodsId).FirstOrDefault()?.SubName ?? "";

                        item.FinanceList = flist.Where(x => x.ECOrderDetailId == item.Id).ToList();// 2020-08-19 新增财务单据列表


                        item.SiteName = sitelist.Where(x => x.ID == item.SiteId).FirstOrDefault()?.SiteName ?? "";
                        item.GuideName = guidelist.Where(x => x.ID == item.GuideId).FirstOrDefault()?.Name ?? "";
                        item.CarName = carlist.Where(x => x.ID == item.CarId).FirstOrDefault()?.Name ?? "";
                        item.CarColorName = carcolorlist.Where(x => x.ID == item.CarColorId).FirstOrDefault()?.ColorName ?? "";
                    }
                }
                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);

                //2020-08-25 Add By:W Start

                List<RB_Member_DiscountCoupon_Extend> memberCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                if (list.Any(x => !string.IsNullOrWhiteSpace(x.CouponsIds)))
                {
                    memberCouponList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UseState = -1, Ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x.CouponsIds)).Select(x => x.CouponsIds)) });
                }
                //2020-08-25 Add By:W  End
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    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 ?? "");
                    item.MemberDiscountCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                    if (!string.IsNullOrWhiteSpace(item.CouponsIds))
                    {

                        foreach (var itemCoupons in item.CouponsIds.Split(','))
                        {
                            item.MemberDiscountCouponList.AddRange(memberCouponList.Where(x => itemCoupons == x.Id.ToString()));
                        }
                    }

                }
            }
            return list;
        }




        /// <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> GetEducationGoodsOrderPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetEducationOrderPageList(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)) });
                List<RB_Finance_Extend> flist = new List<RB_Finance_Extend>();
                if (pageSize != 10000 && demodel.TenantId == 1)
                {
                    //查询所有财务单据
                    string detailIds = string.Join(",", dlist.Select(x => x.Id));
                    flist = financeRepository.GetList(new RB_Finance_Extend() { ECOrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                }
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    //剑鱼兄需求 2020=07-30  再查询一次商品表
                    string GoodsIds = string.Join(",", dlist.Select(x => x.GoodsId).Distinct());
                    var GList = goodsRepository.GetSingleListForGoodsSubName(new RB_Goods_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, GoodsIds = GoodsIds }, true);
                    //查询订单对应的老师
                    var teacherList = goodsWKTeacherRepository.GetList(new RB_Goods_WK_Teacher_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, GoodsIds = GoodsIds });
                    //查询订单详情对应的课程卡信息
                    string educationCouponIds = string.Join(",", dlist.Where(x => x.EducationCouponId > 0).Select(x => x.EducationCouponId).Distinct());
                    List<RB_Education_MemberCoupon_Extend> educationCouponList = new List<RB_Education_MemberCoupon_Extend>();
                    if (!string.IsNullOrWhiteSpace(educationCouponIds))
                    {
                        educationCouponList = educationMemberCouponRepository.GetList(new RB_Education_MemberCoupon_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, Ids = educationCouponIds });
                    }
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                        item.GoodsSubName = GList.Where(x => x.Id == item.GoodsId).FirstOrDefault()?.SubName ?? "";
                        item.FinanceList = flist.Where(x => x.ECOrderDetailId == item.Id).ToList();// 2020-08-19 新增财务单据列表
                        item.TeacherList = teacherList.Where(x => x.GoodsId == item.GoodsId).ToList();// 2020-10-11 订单对应的老师
                        item.MemberEducationCouponList = educationCouponList.Where(x => x.Id == item.EducationCouponId).ToList();// 2020-10-11 订单详情对应的课程卡
                    }
                }

                //2020-08-25 Add By:W Start 

                List<RB_Member_DiscountCoupon_Extend> memberCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                if (list.Any(x => !string.IsNullOrWhiteSpace(x.CouponsIds)))
                {
                    memberCouponList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UseState = -1, Ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x.CouponsIds)).Select(x => x.CouponsIds)) });
                }
                //2020-08-25 Add By:W  End
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                    item.MemberDiscountCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                    if (!string.IsNullOrWhiteSpace(item.CouponsIds))
                    {

                        foreach (var itemCoupons in item.CouponsIds.Split(','))
                        {
                            item.MemberDiscountCouponList.AddRange(memberCouponList.Where(x => itemCoupons == x.Id.ToString()));
                        }
                    }

                }
            }
            return list;
        }


        /// <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> GetOfflineServiceOrderPageListModule(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetOfflineServiceOrderPageListRepository(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)) });
                List<RB_Finance_Extend> flist = new List<RB_Finance_Extend>();
                if (pageSize != 10000 && demodel.TenantId == 1)
                {
                    //查询所有财务单据
                    string detailIds = string.Join(",", dlist.Select(x => x.Id));
                    flist = financeRepository.GetList(new RB_Finance_Extend() { ECOrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                }
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    //剑鱼兄需求 2020=07-30  再查询一次商品表
                    string GoodsIds = string.Join(",", dlist.Select(x => x.GoodsId).Distinct());
                    var GList = goodsRepository.GetSingleListForGoodsSubName(new RB_Goods_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, GoodsIds = GoodsIds }, true);
                    
                    //获取服务人员
                    string persionIds= string.Join(",", dlist.Select(x => x.ServicepersonalId).Distinct());
                    var persionList = reserve_ServicePersonalRepository.GetServicePersonalList(new Model.Extend.Reserve.RB_Reserve_ServicePersonal_Extend()
                    {
                        QIds = persionIds
                    });
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                        item.GoodsSubName = GList.Where(x => x.Id == item.GoodsId).FirstOrDefault()?.SubName ?? "";
                        item.FinanceList = flist.Where(x => x.ECOrderDetailId == item.Id).ToList();// 2020-08-19 新增财务单据列表
                        item.ServicepersonalName = persionList?.Where(qitem => qitem.ID == item.ServicepersonalId)?.FirstOrDefault()?.Name ?? "";
                    }
                }
                //2020-08-25 Add By:W Start
                List<RB_Member_DiscountCoupon_Extend> memberCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                if (list.Any(x => !string.IsNullOrWhiteSpace(x.CouponsIds)))
                {
                    memberCouponList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UseState = -1, Ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x.CouponsIds)).Select(x => x.CouponsIds)) });
                }
                //2020-08-25 Add By:W  End
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                    item.MemberDiscountCouponList = new List<RB_Member_DiscountCoupon_Extend>();
                    if (!string.IsNullOrWhiteSpace(item.CouponsIds))
                    {
                        foreach (var itemCoupons in item.CouponsIds.Split(','))
                        {
                            item.MemberDiscountCouponList.AddRange(memberCouponList.Where(x => itemCoupons == x.Id.ToString()));
                        }
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 获取教育后台订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetEducationGoodsOrderInfo(int orderId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }

            //查询订单所属微店  2020-08-14 Add By:W
            if (model.SmallShopsId.HasValue && model.SmallShopsId > 0)
            {
                var smallShop = smallShopsInfoRepository.GetEntity(model.SmallShopsId ?? 0);
                if (smallShop != null)
                {
                    model.SmallShopsName = smallShop.Name;
                }
            }


            // 2020-08-14 Add By:W End

            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });

            //查询图片
            List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
            if (dlist.Any())
            {
                //剑鱼兄需求 2020=07-30  再查询一次商品表
                string GoodsIds = string.Join(",", dlist.Select(x => x.GoodsId).Distinct());
                //查询订单对应的老师
                var teacherList = goodsWKTeacherRepository.GetList(new RB_Goods_WK_Teacher_Extend { TenantId = tenantId, MallBaseId = mallBaseId, GoodsIds = GoodsIds });
                List<RB_Education_MemberCoupon_Extend> educationCouponList = new List<RB_Education_MemberCoupon_Extend>();
                //查询订单详情对应的课程卡信息
                string educationCouponIds = string.Join(",", dlist.Where(x => x.EducationCouponId > 0).Select(x => x.EducationCouponId).Distinct());
                if (!string.IsNullOrWhiteSpace(educationCouponIds))
                {
                    educationCouponList = educationMemberCouponRepository.GetList(new RB_Education_MemberCoupon_Extend { TenantId = tenantId, MallBaseId = mallBaseId, Ids = educationCouponIds });
                }
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.TeacherList = teacherList.Where(x => x.GoodsId == item.GoodsId).ToList();// 2020-10-11 订单对应的老师
                    item.MemberEducationCouponList = educationCouponList.Where(x => x.Id == item.EducationCouponId).ToList();// 2020-10-11 订单详情对应的课程卡
                }
            }
            model.DetailList = dlist;
            //获取返佣列表
            var ocList = goods_OrderCommissionRepository.GetListGroupByUser(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId }).OrderBy(x => x.Grade).ToList();
            if (ocList.Any())
            {
                var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (ocList.Where(x => x.Type == 3).Any())
                {
                    string gradeIds = string.Join(",", ocList.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = tenantId, MallBaseId = mallBaseId });
                }
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ocList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ocList)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";

                    if (item.Type == 1)
                    {
                        if (item.Grade == 0)
                        {
                            item.GradeDescription = "自购返利";
                        }
                        else if (item.Grade == 1)
                        {
                            item.GradeDescription = "一级佣金";
                        }
                        else if (item.Grade == 2)
                        {
                            item.GradeDescription = "二级佣金";
                        }
                        else if (item.Grade == 3)
                        {
                            item.GradeDescription = "三级佣金";
                        }
                    }
                    else if (item.Type == 3)
                    {
                        var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                    }
                }
            }

            var vipList = vip_BuyRepository.GetVipBuyList(new RB_Vip_Buy_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, ReOrderId = model.OrderId });
            List<RB_VipBuy_Commission_Extend> clist = new List<RB_VipBuy_Commission_Extend>();
            if (vipList.Any())
            {
                string vipIds = string.Join(",", vipList.Select(x => x.Id));
                clist = vipBuy_CommissionRepository.GetList(new RB_VipBuy_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderIds = vipIds });
                var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = tenantId, MallBaseId = mallBaseId });
                //获取用户
                var ulist = new List<RB_Member_User_Extend>();
                if (clist.Any())
                {
                    ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", clist.Select(x => x.UserId).Distinct()) });
                    foreach (var qitem in clist)
                    {
                        var fxmodel = FXList.Where(x => x.Id == qitem.Grade).FirstOrDefault();
                        qitem.GradeDescription = fxmodel.GradeName;
                        qitem.UserName = ulist.Where(x => x.Id == qitem.UserId).FirstOrDefault()?.Name ?? "";
                    }
                }
            }

            #region 推荐返佣
            List<RB_Goods_OrderIntroduction_Extend> OrderIntroduction = new List<RB_Goods_OrderIntroduction_Extend>();
            var introductList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (introductList.Any())
            {
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", introductList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ulist)
                {
                    decimal Commission = introductList.Where(x => x.UserId == item.Id).Sum(x => x.Commission ?? 0);
                    OrderIntroduction.Add(new RB_Goods_OrderIntroduction_Extend()
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        Commission = Commission
                    });
                }
            }
            #endregion

            #region 微店返佣
            List<RB_SmallShops_Commission_Extend> SmallShopsCommission = new List<RB_SmallShops_Commission_Extend>();
            var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (ssList.Any())
            {
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ssList.Select(x => x.UserId).Distinct()) });
                var slist = smallShops_InfoRepository.GetListForSingle(new RB_SmallShops_Info_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ssList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ulist)
                {
                    decimal Commission = ssList.Where(x => x.UserId == item.Id).Sum(x => x.Commission ?? 0);
                    var smodel = slist.Where(x => x.UserId == item.Id).FirstOrDefault();
                    SmallShopsCommission.Add(new RB_SmallShops_Commission_Extend()
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        Name = smodel?.Name ?? "",
                        Commission = Commission
                    });
                }
            }
            #endregion


            #region  优惠券 2020-08-25 Add By:W Start

            List<RB_Member_DiscountCoupon_Extend> memberCouponList = new List<RB_Member_DiscountCoupon_Extend>();
            if (!string.IsNullOrWhiteSpace(model.CouponsIds))
            {
                memberCouponList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, UseState = -1, Ids = model.CouponsIds });
            }
            #endregion 2020-08-25 Add By:W  End


            return ApiResult.Success("", new
            {
                model.OrderId,
                model.OrderStatus,
                OrderStatusName = model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                PaymentTime = model.PaymentTime.HasValue ? model.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = model.DeliveryTime.HasValue ? model.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = model.ReceivingTime.HasValue ? model.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = model.FinishTime.HasValue ? model.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.Remark,
                model.BuyerMessage,
                model.PreferPrice,
                model.Income,
                model.FreightMoney,
                CouponMoney = model.CouponMoney ?? 0,
                EducationMoney = model.EducationMoney ?? 0,
                IntegralMoney = (model.DetailList != null && model.DetailList.Any()) ? (model.DetailList.Sum(x => x.IntegralMoney ?? 0)) : 0,
                IntegralNumber = (model.DetailList != null && model.DetailList.Any()) ? (model.DetailList.Sum(x => x.IntegralNumber ?? 0)) : 0,
                MemberDiscountCouponList = memberCouponList.Select(y => new
                {
                    y.Name,
                    y.MinConsumePrice,
                    y.MaxDiscountsPrice,
                    y.UseType,
                    y.CouponType,
                    y.DiscountsPrice
                }),
                OrderInfo = new
                {
                    model.OrderNo,
                    model.MerchantsNo,
                    model.PaymentWay,
                    PaymentWayName = model.PaymentWay.GetEnumName(),
                    model.DeliveryMethod,
                    DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                    UserName = member_UserRepository.GetEntity(model.UserId)?.Name ?? "",
                    model.Consignee,
                    model.Mobile,
                    model.DistrictAddress,
                    model.ShoppingAddress,
                    model.Country,
                    model.Province,
                    model.City,
                    model.District,
                    model.SmallShopsName,
                    model.SmallShopsId
                },
                DistributionInfo = ocList.Select(x => new
                {
                    x.Id,
                    x.Grade,
                    x.GradeDescription,
                    x.UserName,
                    x.Mobile,
                    x.Commission
                }),
                VipCommissionInfo = clist.Select(x => new
                {
                    x.Id,
                    x.Grade,
                    x.GradeDescription,
                    x.UserName,
                    x.Commission
                }),
                OrderIntroductionInfo = OrderIntroduction.Select(x => new
                {
                    x.UserId,
                    x.UserName,
                    x.Commission
                }),
                SmallShopsCommissionInfo = SmallShopsCommission.Select(x => new
                {
                    x.UserId,
                    x.UserName,
                    SmallShopsName = x.Name,
                    x.Commission
                }),
                DetailList = model.DetailList.Select(x => new
                {
                    x.Id,
                    x.GoodsName,
                    x.CoverImage,
                    x.CoverImagePath,
                    SpecificationList = x.TeacherList.Select(y => y.Name), //JsonConvert.DeserializeObject<List<string>>(x.Specification),
                    x.Unit_Price,
                    x.Number,
                    x.Original_Price,
                    x.Final_Price,
                    x.IsBindExpress,
                    x.FreeShippingRemarks,
                    x.SmallShopsCostPrice,
                    CouponMoney = x.CouponMoney ?? 0,
                    InsuranceMoney = x.InsuranceMoney ?? 0,
                    IntegralMoney = x.IntegralMoney ?? 0,
                    IntegralNumber = x.IntegralNumber ?? 0,
                    MemberEducationCouponList = x.MemberEducationCouponList.Select(z => new
                    {
                        z.Name,
                        z.UseHeXiao,
                        z.HeXiao
                    }),
                })
            });
        }

        /// <summary>
        /// 获取直播订单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetLiveGoodsOrderPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderDetail_Extend demodel)
        {
            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetSupplierOrderPageList(pageIndex, pageSize, out count, demodel);
            return dlist;
        }

        /// <summary>
        /// 直播订单创建财务单据
        /// </summary>
        /// <param name="isPublic"></param>
        /// <param name="accountIdList"></param>
        /// <param name="orderdetailIdList"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="erpEmpId"></param>
        /// <returns></returns>
        public string SetLiveGoodsOrderFinance(int isPublic, List<int> accountIdList, List<int> orderdetailIdList, string LiveTime, int tenantId, int mallBaseId, int erpEmpId)
        {
            int accountNum = accountIdList.Count();
            string orderdetailIds = string.Join(",", orderdetailIdList);
            var list = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderDetailIds = orderdetailIds });
            foreach (var item in list)
            {
                if (item.LivePeopleNum != accountNum)
                {
                    return "订单:" + item.OrderId + "主播数量不正确";
                }
                if (!string.IsNullOrEmpty(item.LiveFinanceIds))
                {
                    return "订单:" + item.OrderId + " 已生成单据，无法再次生成";
                }
            }
            List<RB_Goods_Order_Extend> OrderList = new List<RB_Goods_Order_Extend>();
            if (list.Any())
            {
                string orderIds = string.Join(",", list.Select(x => x.OrderId).Distinct());
                OrderList = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderIds = orderIds });
            }

            try
            {
                decimal Money = list.Sum(x => x.LiveCommission ?? 0) / accountNum;//每个账户的总金额
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 4 });

                //根据规则中的小程序，查询订单详情信息
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    item.IsPublic = isPublic;
                    List<int> FinanceIds = new List<int>();//返回的财务单号
                    var detailList = new List<object>();
                    List<object> ECList = new List<object>();
                    foreach (var qitem in list)
                    {
                        var orderModel = OrderList.Where(x => x.OrderId == qitem.OrderId).FirstOrDefault();
                        decimal dMoney = (qitem.LiveCommission ?? 0) / accountNum;
                        detailList.Add(new
                        {
                            CostTypeId = 65,//写死 其他费用
                            Number = 1,
                            OriginalMoney = dMoney,
                            UnitPrice = dMoney,
                            Remark = qitem.GoodsName + " " + qitem.Specification + "   " + (orderModel?.OrderNo ?? "")
                        });
                        ECList.Add(new
                        {
                            ECOrderId = qitem.OrderId,
                            ECOrderDetailId = qitem.Id
                        });
                    }
                    foreach (var aitem in accountIdList)
                    {
                        var financeObj = new
                        {
                            CreateBy = erpEmpId > 0 ? erpEmpId.ToString() : Config.ExpendDirector,
                            item.IsPublic,
                            ClientType = 10,
                            ClientID = aitem,
                            item.CurrencyId,
                            WBMoney = Money,
                            PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                            RB_Branch_Id = Config.ExpendBranchId,
                            TemplateId = item.WorkFlowId,
                            OrderSource = 16,
                            OtherType = 20,
                            ReFinanceId = 0,
                            Remark = DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据(主播订单佣金)  直播日期：" + LiveTime,
                            detailList,
                            RB_Depart_Id = Config.ExpendDepartment,
                            ECOrderList = ECList
                        };
                        string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                        var resultInfo = new
                        {
                            msg = sign
                        };

                        string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                        var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                        if (apir.resultCode == 1)
                        {
                            FinanceIds.Add(Convert.ToInt32(apir.data.ToString()));
                        }
                    }

                    if (FinanceIds.Any())
                    {
                        string financeIds2 = string.Join(",", FinanceIds);
                        foreach (var qitem in list)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Goods_OrderDetail.LiveFinanceIds),financeIds2 }
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_OrderDetail.Id),
                                        FiledValue=qitem.Id,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderDetailRepository.Update(keyValues, wheres);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetLiveGoodsOrderFinance");
                return "出错了，请联系管理员";
            }
            return "";
        }

        /// <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> GetDistributionOrdersPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetDistributionOrdersPageList(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)) });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    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);
                //分销情况
                var oclist = goods_OrderCommissionRepository.GetListGroupByUser(new RB_Goods_OrderCommission_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                if (oclist.Any())
                {
                    //获取用户
                    var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                    //获取分销商
                    var dislist = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                    var HpgradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                    if (oclist.Where(x => x.Type == 2).Any())
                    {
                        string gradeIds = string.Join(",", oclist.Where(x => x.Type == 2).Select(x => x.Grade).Distinct());
                        HpgradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                    }
                    var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                    if (oclist.Where(x => x.Type == 3).Any())
                    {
                        string gradeIds = string.Join(",", oclist.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                        FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    }
                    foreach (var item in oclist)
                    {
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        item.UserName = umodel?.Name ?? "";
                        item.Mobile = umodel?.Moblie ?? "";
                        item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";
                        if (item.Type == 1)
                        {
                            if (item.Grade == 0)
                            {
                                item.GradeDescription = "自购返利";
                            }
                            else if (item.Grade == 1)
                            {
                                item.GradeDescription = "一级佣金";
                            }
                            else if (item.Grade == 2)
                            {
                                item.GradeDescription = "二级佣金";
                            }
                            else if (item.Grade == 3)
                            {
                                item.GradeDescription = "三级佣金";
                            }
                        }
                        else if (item.Type == 2)
                        {
                            var hpGModel = HpgradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                            item.GradeDescription = hpGModel?.GradeName ?? "暂无等级";
                        }
                        else if (item.Type == 3)
                        {
                            var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                            item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                        }
                    }
                }
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    string areaName = (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 ?? "");
                    item.ShoppingAddress = areaName + " " + item.ShoppingAddress;

                    item.OrderCommissionList = oclist.Where(x => x.OrderId == item.OrderId).ToList();
                    item.IsOrderCommission = 2;
                    if (item.OrderCommissionList.Where(x => x.CommissionState == 2).Any())
                    {
                        item.IsOrderCommission = 1;
                    }
                }
            }
            return list;
        }

        /// <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> GetDistributionOrdersPageListForRecommend(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetDistributionOrdersPageListForRecommend(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)) });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    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);
                //分销情况
                var oclist = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                if (oclist.Any())
                {
                    //获取用户
                    var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                    //获取分销商
                    var dislist = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                    foreach (var item in oclist)
                    {
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        item.UserName = umodel?.Name ?? "";
                        item.Mobile = umodel?.Moblie ?? "";
                        item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";
                    }
                }
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    string areaName = (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 ?? "");
                    item.ShoppingAddress = areaName + " " + item.ShoppingAddress;

                    foreach (var qitem in item.DetailList)
                    {
                        qitem.OrderIntroduction = oclist.Where(x => x.OrderId == item.OrderId && x.OrderDetailId == qitem.Id).FirstOrDefault();
                    }
                }
            }
            return list;
        }

        /// <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> GetSmallShopsOrdersPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetSmallShopsOrdersPageList(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)) });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    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);
                //分销情况
                var oclist = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                if (oclist.Any())
                {
                    //获取用户
                    var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                    //获取分销商
                    var dislist = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                    foreach (var item in oclist)
                    {
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        item.UserName = umodel?.Name ?? "";
                        item.Mobile = umodel?.Moblie ?? "";
                        item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";
                    }
                }
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    string areaName = (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 ?? "");
                    item.ShoppingAddress = areaName + " " + item.ShoppingAddress;

                    foreach (var qitem in item.DetailList)
                    {
                        qitem.SmallShopsCommission = oclist.Where(x => x.OrderId == item.OrderId && x.OrderDetailId == qitem.Id).FirstOrDefault();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取用户分销订单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderCommission_Extend> GetDistributionOrdersPageList_V2(int pageIndex, int pageSize, out long count, RB_Goods_OrderCommission_Extend demodel)
        {
            var oclist = goods_OrderCommissionRepository.GetListGroupByUser_V2(pageIndex, pageSize, out count, demodel);
            if (oclist.Any())
            {
                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                string orderIds = string.Join(",", oclist.Select(x => x.OrderId).Distinct());
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = orderIds });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }

                var HpgradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                if (oclist.Where(x => x.Type == 2).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 2).Select(x => x.Grade).Distinct());
                    HpgradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                }
                var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (oclist.Where(x => x.Type == 3).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in oclist)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";
                    item.Photo = umodel?.Photo ?? "";
                    item.OrderDetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                    if (item.Type == 1)
                    {
                        if (item.Grade == 0)
                        {
                            item.GradeDescription = "自购返利";
                        }
                        else if (item.Grade == 1)
                        {
                            item.GradeDescription = "一级佣金";
                        }
                        else if (item.Grade == 2)
                        {
                            item.GradeDescription = "二级佣金";
                        }
                        else if (item.Grade == 3)
                        {
                            item.GradeDescription = "三级佣金";
                        }
                    }
                    else if (item.Type == 2)
                    {
                        var hpGModel = HpgradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = hpGModel?.GradeName ?? "暂无等级";
                    }
                    else if (item.Type == 3)
                    {
                        var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                        item.GradeDescription += "佣金";
                    }
                }
            }

            return oclist;
        }

        /// <summary>
        /// 获取用户分销订单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderCommission_Extend> GetDistributionOrdersPageListModule(int pageIndex, int pageSize, out long count, RB_Goods_OrderCommission_Extend demodel)
        {
            var oclist = goods_OrderCommissionRepository.GetListGroupByUserRepository(pageIndex, pageSize, out count, demodel);
            if (oclist.Any())
            {
                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                string orderIds = string.Join(",", oclist.Select(x => x.OrderId).Distinct());
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = orderIds });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }

                var HpgradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                if (oclist.Where(x => x.Type == 2).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 2).Select(x => x.Grade).Distinct());
                    HpgradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                }
                var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (oclist.Where(x => x.Type == 3).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in oclist)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";
                    item.Photo = umodel?.Photo ?? "";
                    item.OrderDetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                    if (item.Type == 1)
                    {
                        if (item.Grade == 0)
                        {
                            item.GradeDescription = "自购返利";
                        }
                        else if (item.Grade == 1)
                        {
                            item.GradeDescription = "一级佣金";
                        }
                        else if (item.Grade == 2)
                        {
                            item.GradeDescription = "二级佣金";
                        }
                        else if (item.Grade == 3)
                        {
                            item.GradeDescription = "三级佣金";
                        }
                    }
                    else if (item.Type == 2)
                    {
                        var hpGModel = HpgradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = hpGModel?.GradeName ?? "暂无等级";
                    }
                    else if (item.Type == 3)
                    {
                        var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                        item.GradeDescription += "佣金";
                    }
                }
            }

            return oclist;
        }

        /// <summary>
        /// 获取用户分销订单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderCommission_Extend> GetERPDistributionOrdersPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderCommission_Extend demodel)
        {
            var oclist = goods_OrderCommissionRepository.GetListGroupByUser_V3(pageIndex, pageSize, out count, demodel);
            if (oclist.Any())
            {
                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                string orderIds = string.Join(",", oclist.Select(x => x.OrderId).Distinct());
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = orderIds });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }

                var HpgradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                if (oclist.Where(x => x.Type == 2).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 2).Select(x => x.Grade).Distinct());
                    HpgradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                }
                var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (oclist.Where(x => x.Type == 3).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in oclist)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";
                    item.OrderDetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                    if (item.Type == 1)
                    {
                        if (item.Grade == 0)
                        {
                            item.GradeDescription = "自购返利";
                        }
                        else if (item.Grade == 1)
                        {
                            item.GradeDescription = "一级佣金";
                        }
                        else if (item.Grade == 2)
                        {
                            item.GradeDescription = "二级佣金";
                        }
                        else if (item.Grade == 3)
                        {
                            item.GradeDescription = "三级佣金";
                        }
                    }
                    else if (item.Type == 2)
                    {
                        var hpGModel = HpgradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = hpGModel?.GradeName ?? "暂无等级";
                    }
                    else if (item.Type == 3)
                    {
                        var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                    }
                }
            }

            return oclist;
        }

        /// <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> GetDistributionOrdersPageListToExcel(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetDistributionOrdersPageList(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)) });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    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);
                //分销情况
                var oclist = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                if (oclist.Any())
                {
                    //获取用户
                    var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                    //获取分销商
                    var dislist = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                    var HpgradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                    if (oclist.Where(x => x.Type == 2).Any())
                    {
                        string gradeIds = string.Join(",", oclist.Where(x => x.Type == 2).Select(x => x.Grade).Distinct());
                        HpgradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                    }
                    var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                    if (oclist.Where(x => x.Type == 3).Any())
                    {
                        string gradeIds = string.Join(",", oclist.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                        FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    }

                    foreach (var item in oclist)
                    {
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        item.UserName = umodel?.Name ?? "";
                        item.Mobile = umodel?.Moblie ?? "";
                        item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";

                        if (item.Type == 1)
                        {
                            if (item.Grade == 0)
                            {
                                item.GradeDescription = "自购返利";
                            }
                            else if (item.Grade == 1)
                            {
                                item.GradeDescription = "一级佣金";
                            }
                            else if (item.Grade == 2)
                            {
                                item.GradeDescription = "二级佣金";
                            }
                            else if (item.Grade == 3)
                            {
                                item.GradeDescription = "三级佣金";
                            }
                        }
                        else if (item.Type == 2)
                        {
                            var hpGModel = HpgradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                            item.GradeDescription = hpGModel?.GradeName ?? "暂无等级";
                        }
                        else if (item.Type == 3)
                        {
                            var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                            item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                        }
                    }
                }
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    string areaName = (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 ?? "");
                    item.ShoppingAddress = areaName + " " + item.ShoppingAddress;

                    item.OrderCommissionList = oclist.Where(x => x.OrderId == item.OrderId).ToList();
                    item.IsOrderCommission = 2;
                    if (item.OrderCommissionList.Where(x => x.CommissionState == 2).Any())
                    {
                        item.IsOrderCommission = 1;
                    }
                }
            }
            return list;
        }

        /// <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> GetGoodsOrderAfterPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderAfterSale_Extend demodel)
        {
            var list = goods_OrderAfterSaleRepository.GetERPPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string orderids = string.Join(",", list.Select(x => x.OrderId).Distinct());
                string orderDetilIds = string.Join(",", list.Select(x => x.OrderDetialId));
                var gList = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = orderids });
                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;
                    }
                }
                string areaIds1 = string.Join(",", gList.Select(x => x.Province ?? 0).Distinct());
                string areaIds2 = string.Join(",", gList.Select(x => x.City ?? 0).Distinct());
                string areaIds3 = string.Join(",", gList.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 gList)
                {
                    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 ?? "");
                }
                List<Model.Entity.BaseSetUp.RB_Logistics_Express> ExpressList = new List<Model.Entity.BaseSetUp.RB_Logistics_Express>();
                if (list.Where(x => x.ReExpressId > 0).Any())
                {
                    ExpressList = logistics_ExpressRepository.GetLogisticsExpressList(new Model.Entity.BaseSetUp.RB_Logistics_Express(), string.Join(",", list.Where(x => x.ReExpressId > 0).Select(x => x.ReExpressId)));
                }
                foreach (var item in list)
                {
                    item.OrderModel = gList.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                    item.OrderDetailModel = gdList.Where(x => x.Id == item.OrderDetialId).FirstOrDefault();
                    if (item.ReExpressId > 0)
                    {
                        item.ReExpressName = ExpressList.Where(x => x.ID == item.ReExpressId)?.FirstOrDefault()?.Name ?? "";
                    }
                }
            }

            return list;
        }

        /// <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> GetMembersToBuyPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetMembersToBuyPageList(pageIndex, pageSize, out count, demodel);
            return list;
        }

        /// <summary>
        /// 获取订单实体
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        public RB_Goods_Order_Extend GetOrderInfo(int OrderId)
        {
            return goods_OrderRepository.GetEntity(OrderId).RefMapperTo<RB_Goods_Order_Extend>();
        }

        /// <summary>
        /// 获取订单明细实体
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        public RB_Goods_OrderDetail_Extend GetOrderDetailInfo(int OrderId)
        {
            return goods_OrderDetailRepository.GetEntity(OrderId).RefMapperTo<RB_Goods_OrderDetail_Extend>();
        }

        /// <summary>
        /// 获取订单是否已返佣
        /// </summary>
        /// <param name="OrderDetailId"></param>
        /// <returns></returns>
        public bool GetOrderCommissionIsSend(int OrderDetailId)
        {
            var list = goods_OrderCommissionRepository.GetOrderHaveCommissionList(OrderDetailId.ToString());
            if (list.Any())
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public RB_Member_User_Extend GetMemberUserInfo(int userId)
        {
            return member_UserRepository.GetEntity(userId).RefMapperTo<RB_Member_User_Extend>();
        }

        /// <summary>
        /// 获取售后订单详情
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetOrderAfterSaleInfo(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;

            var slList = goods_OrderAfterSaleLogRepository.GetList(new RB_Goods_OrderAfterSaleLog_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, ReOrderId = reOrderId });
            var uModel = member_UserRepository.GetEntity(model.UserId);
            //物流信息
            List<object> ExpressList = new List<object>();
            if (model.DeliveryId > 0)
            {
                var ldModel = logistics_DeliveryRepository.GetEntity(model.DeliveryId);
                var leModel = logistics_ExpressRepository.GetEntity(model.ReExpressId);
                ExpressList.Add(new
                {
                    Name = ldModel?.Name ?? "",
                    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 && oeModel.Type == 1)
                {
                    var leModel = logistics_ExpressRepository.GetEntity(oeModel.ExpressId);
                    ExpressList.Add(new
                    {
                        Name = uModel.Name ?? "",
                        ExpressName = leModel.Name ?? "",
                        ExpressNumber = oeModel?.ExpressNumber ?? "",
                        Type = 1
                    });
                }
                else
                {
                    ExpressList.Add(new
                    {
                        Name = uModel.Name ?? "",
                        ExpressName = "",
                        ExpressNumber = oeModel?.Remark ?? "",
                        Type = 2
                    });
                }
            }
            return ApiResult.Success("", new
            {
                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,
                UserName = uModel?.Name ?? "",
                model.ReOrderStatus,
                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") : "",
                AfterSaleLoglist = slList.Select(x => new
                {
                    x.Id,
                    x.Type,
                    x.Content,
                    CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                }),
                OrderInfo = new
                {
                    odModel.OrderId,
                    odModel.CoverImagePath,
                    odModel.GoodsId,
                    odModel.GoodsName,
                    odModel.ProductCode,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(odModel.Specification),
                    odModel.Number,
                    odModel.Original_Price,
                    odModel.Final_Price,
                    odModel.Unit_Price,
                    gModel.PreferPrice,
                    gModel.Income,
                    gModel.CouponMoney,
                    gModel.FreightMoney
                },
                ExpressList
            });
        }

        /// <summary>
        /// 售后订单审核
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="type"></param>
        /// <param name="DeliveryId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult SetOrderAfterSaleAudit(int reOrderId, int type, int DeliveryId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderAfterSaleRepository.GetEntity(reOrderId);
            if (model == null)
            {
                return ApiResult.Failed("售后订单不存在");
            }
            if (model.ReOrderStatus != OrderAfterSaleStatusEnum.Auditing)
            {
                return ApiResult.Failed("状态不正确");
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (type == 1)
            { //通过
                keyValues.Add(nameof(RB_Goods_OrderAfterSale.ReOrderStatus), OrderAfterSaleStatusEnum.DeliveryToBuyer);
                keyValues.Add(nameof(RB_Goods_OrderAfterSale.DeliveryId), DeliveryId);
                keyValues.Add(nameof(RB_Goods_OrderAfterSale.AuditTime), DateTime.Now);
            }
            else
            {
                keyValues.Add(nameof(RB_Goods_OrderAfterSale.ReOrderStatus), OrderAfterSaleStatusEnum.Rejected);
                keyValues.Add(nameof(RB_Goods_OrderAfterSale.AuditTime), DateTime.Now);
            }

            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)
            {
                //记录流程
                string Content = "";
                if (type == 1)
                {
                    Content = "卖家同意售后";
                }
                else
                {
                    Content = "卖家拒绝售后";
                }
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = Content,
                    CreateDate = DateTime.Now,
                    MallBaseId = mallBaseId,
                    ReOrderId = reOrderId,
                    TenantId = tenantId,
                    Type = 2
                });
                return ApiResult.Success();
            }
            return ApiResult.Failed();
        }

        /// <summary>
        /// 收货  （退货退款）
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult SetOrderReceivingForReturnsAndRefunds(int reOrderId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderAfterSaleRepository.GetEntity(reOrderId);
            if (model == null)
            {
                return ApiResult.Failed("售后订单不存在");
            }
            if (model.ReOrderStatus != OrderAfterSaleStatusEnum.ReceivedBySeller)
            {
                return ApiResult.Failed("状态不正确");
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { 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
                },
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.TenantId),
                  FiledValue=tenantId,
                   OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.MallBaseId),
                  FiledValue=mallBaseId,
                   OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderAfterSaleRepository.Update(keyValues, wheres);
            if (flag)
            {
                if (tenantId == 1)
                {
                    var omdoel = goods_OrderRepository.GetEntity(model.OrderId);
                    if (omdoel.OrderSource == UserSourceEnum.ERP)
                    {
                        //2020-07-03 屏蔽 改每日自动生成
                        //2020-09-15 电商erp订单 财务单据生成
                        OrderRefundFinanceModule(model, tenantId, mallBaseId);
                    }
                }
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "卖家确认收货",
                    CreateDate = DateTime.Now,
                    MallBaseId = mallBaseId,
                    ReOrderId = reOrderId,
                    TenantId = tenantId,
                    Type = 2
                });
                return ApiResult.Success();
            }
            return ApiResult.Failed();
        }

        /// <summary>
        /// 生成退款单据
        /// </summary>
        /// <returns></returns>
        public bool OrderRefundFinanceModule(RB_Goods_OrderAfterSale dmodel, int TenantId, int MallBaseId)
        {
            var flag = false;
            try
            {
                decimal Money = dmodel.Refund ?? 0;
                //查询用户
                var umodel = member_UserRepository.GetEntity(dmodel.UserId);
                if (umodel == null) { return false; }
                var omodel = goods_OrderRepository.GetEntity(dmodel.OrderId);
                if (omodel == null) { return false; }
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 3 });

                string dstr = "已收货，客人付款:" + (dmodel.Income ?? 0) + "金额，申请退款:" + (dmodel.Refund ?? 0);
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = dmodel.OrderId ?? 0 });
                    string Remark1 = "";
                    if (dlist.Any())
                    {
                        foreach (var qqitem in dlist)
                        {
                            Remark1 += qqitem.GoodsName + " " + qqitem.Specification + " ";
                        }
                    }
                    var detailList = new List<object>() {
                        new
                        {
                            CostTypeId = item.RefundCostTypeId,
                            Number = 1,
                            OriginalMoney = Money,
                            UnitPrice = Money,
                            Remark = Remark1 + "单号：" + omodel.OrderNo + "售后单号：" + (dmodel.ReOrderNo ?? "暂无") + "   " + dstr
                        }
                    };
                    List<RB_ECFinanceId_Relation> ECList = new List<RB_ECFinanceId_Relation>();
                    foreach (var qitem in dlist)
                    {
                        ECList.Add(new RB_ECFinanceId_Relation()
                        {
                            ECOrderId = qitem.OrderId,
                            ECOrderDetailId = qitem.Id
                        });
                    }

                    item.IsPublic = 8;//默认原路退款
                    var financeObj = new
                    {
                        CreateBy = Config.ExpendDirector,
                        item.IsPublic,
                        ClientType = 0,
                        ClientID = 0,
                        item.CurrencyId,
                        WBMoney = Money,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        RB_Branch_Id = Config.ExpendBranchId,
                        TemplateId = item.WorkFlowId,
                        OrderSource = 16,
                        OtherType = 23,
                        ReFinanceId = dmodel.OrderId ?? 0,
                        Remark = "名称:" + umodel.Name + "(" + umodel.Id + ")" + "   " + System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据(erp订单)",
                        detailList,
                        RB_Depart_Id = Config.ExpendDepartment,
                        ECOrderList = ECList
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign
                    };

                    string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                    var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                    if (apir.resultCode == 1)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Goods_OrderAfterSale.ReRemark), dmodel.ReRemark +"   自动生成财务退款单据："+ apir.data.ToString()},
                            { nameof(RB_Goods_OrderAfterSale.FinanceId), Convert.ToInt32(apir.data.ToString())}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                              FiledValue=dmodel.ReOrderId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderAfterSale.TenantId),
                              FiledValue=dmodel.TenantId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderAfterSale.MallBaseId),
                              FiledValue=dmodel.MallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        goods_OrderAfterSaleRepository.Update(keyValues, wheres);
                        goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                        {
                            Id = 0,
                            Content = "自动生成财务退款单据：" + apir.data.ToString(),
                            CreateDate = DateTime.Now,
                            MallBaseId = dmodel.MallBaseId,
                            ReOrderId = dmodel.ReOrderId,
                            TenantId = dmodel.TenantId,
                            Type = 2
                        });
                    }
                    else
                    {
                        //记录自动生成失败，需手动新增财务单据
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Goods_OrderAfterSale.ReRemark), dmodel.ReRemark +"   财务单据新增失败，请手动增加"}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                              FiledValue=dmodel.ReOrderId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderAfterSale.TenantId),
                              FiledValue=dmodel.TenantId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderAfterSale.MallBaseId),
                              FiledValue=dmodel.MallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        goods_OrderAfterSaleRepository.Update(keyValues, wheres);
                        goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                        {
                            Id = 0,
                            Content = "财务单据新增失败，请手动增加",
                            CreateDate = DateTime.Now,
                            MallBaseId = dmodel.MallBaseId,
                            ReOrderId = dmodel.ReOrderId,
                            TenantId = dmodel.TenantId,
                            Type = 2
                        });
                    }
                }
            }
            catch (Exception ex)
            {

                LogHelper.Write(ex);
            }

            return flag;
        }

        /// <summary>
        /// 获取售后订单实体
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <returns></returns>
        public RB_Goods_OrderAfterSale GetOrderAfterSaleEntity(int reOrderId)
        {
            return goods_OrderAfterSaleRepository.GetEntity(reOrderId);
        }

        /// <summary>
        /// 获取订单已退款次数
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public int GetOrderRefundOnlineTradeNum(int OrderId, int tenantId, int mallBaseId)
        {
            var ReList = goods_Online_TradeRepository.GetList(new RB_Goods_Online_Trade_Extend() { OrderId = OrderId, Type = 2, TenantId = tenantId, MallBaseId = mallBaseId });
            return ReList.Count();
        }

        /// <summary>
        /// 获取小程序信息
        /// </summary>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_MiniProgram_Extend GetMiniProgramExtend(int mallBaseId)
        {
            return miniProgramRepository.GetEntity<RB_MiniProgram_Extend>(mallBaseId);
        }

        /// <summary>
        /// 售后订单退款
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="refund"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderAfterSaleForRefunds(RB_Goods_Order_Extend omodel, int reOrderId, decimal refund, string RefundOrderNo, int tenantId, int mallBaseId, Common.Enum.Goods.OrderPayTypeEnum payType, string dPrice, string outTradeNo, string transactionId, string refundid)
        {

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderAfterSale.ReOrderStatus), OrderAfterSaleStatusEnum.Completed},
                { nameof(RB_Goods_OrderAfterSale.RefundActual), refund},
                { nameof(RB_Goods_OrderAfterSale.RefundOrderNo), RefundOrderNo},
                { nameof(RB_Goods_OrderAfterSale.FinishTime), DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                  FiledValue=reOrderId,
                   OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.TenantId),
                  FiledValue=tenantId,
                   OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.MallBaseId),
                  FiledValue=mallBaseId,
                   OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderAfterSaleRepository.Update(keyValues, wheres);
            if (flag)
            {
                #region 操作原路退款
                //var OrderModel = goods_OrderRepository.GetEntity(model.OrderId);
                //var ReList = goods_Online_TradeRepository.GetList(new RB_Goods_Online_Trade_Extend() { OrderId = model.OrderId, Type = 2, TenantId = tenantId, MallBaseId = mallBaseId });
                //int Num = ReList.Count() + 1;
                //string RefundOrderNo = OrderModel.OrderNo + Num;                
                #endregion


                if (!string.IsNullOrWhiteSpace(dPrice) && !string.IsNullOrWhiteSpace(outTradeNo) && !string.IsNullOrWhiteSpace(transactionId) && !string.IsNullOrWhiteSpace(refundid))
                {
                    goods_Online_TradeRepository.Insert(new Model.Entity.Product.RB_Goods_Online_Trade()
                    {
                        Id = 0,
                        User_Id = omodel.UserId,
                        FinanceId = 0,
                        CreateDate = DateTime.Now,
                        IsRefund = 2,
                        MallBaseId = omodel.MallBaseId,
                        Money = omodel.Income,
                        OrderId = omodel.OrderId,
                        Out_Trade_No = outTradeNo,
                        PayType = "",
                        PayWay = payType,
                        Pay_Date = System.DateTime.Now,
                        Pay_Result = 0,
                        RefundMoney = string.IsNullOrWhiteSpace(dPrice) ? 0 : Convert.ToDecimal(dPrice),
                        RefundStatus = 2,
                        RefundTrade_Order = RefundOrderNo,
                        Refund_Date = DateTime.Now,
                        Refund_Id = refundid,
                        Remarks = omodel.UserName + "(id:" + omodel.UserId + ")",
                        TenantId = omodel.TenantId,
                        Transaction_Id = transactionId,
                        Type = 2
                    });
                }
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "卖家已退款",
                    CreateDate = DateTime.Now,
                    MallBaseId = mallBaseId,
                    ReOrderId = reOrderId,
                    TenantId = tenantId,
                    Type = 2
                });
                return true;
            }
            return false;
        }

        /// <summary>
        /// 电商erp订单退款
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="financeId"></param>
        /// <returns></returns>
        public bool SetMallOrderSalesTheWayRefund(int orderId, int? financeId)
        {
            var financeObj = new
            {
                OrderId = orderId,
                FinanceId = financeId ?? 0
            };
            string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
            var resultInfo = new
            {
                msg = sign
            };

            string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.ZYRefundFinanceApi, JsonHelper.Serialize(resultInfo), "");
            JObject parmsJob = JObject.Parse(apiResult);
            string resultCode = parmsJob.GetStringValue("resultCode");
            if (resultCode == "1")
            {
                return true;
            }
            else
            {
                LogHelper.Write("SetMallOrderSalesTheWayRefund失败，orderId:" + orderId + ",financeId：" + financeId);
                return false;
            }
        }

        /// <summary>
        /// 售后订单  发货
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult SetOrderAfterSaleSendGoods(RB_Goods_OrderExpress_Extend demodel)
        {
            var model = goods_OrderAfterSaleRepository.GetEntity(demodel.AfterSaleOrderId);
            if (model == null)
            {
                return ApiResult.Failed("售后订单不存在");
            }
            if (model.ReOrderStatus != OrderAfterSaleStatusEnum.ReceivedBySeller)
            {
                return ApiResult.Failed("状态不正确");
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderAfterSale.ReOrderStatus), OrderAfterSaleStatusEnum.Completed},
                { nameof(RB_Goods_OrderAfterSale.ReRemark), demodel.Remark},
                { nameof(RB_Goods_OrderAfterSale.FinishTime), DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                  FiledValue=demodel.AfterSaleOrderId,
                   OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.TenantId),
                  FiledValue=demodel.TenantId,
                   OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                 FiledName=nameof(RB_Goods_OrderAfterSale.MallBaseId),
                  FiledValue=demodel.MallBaseId,
                   OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderAfterSaleRepository.Update(keyValues, wheres);
            if (flag)
            {
                //快递
                demodel.OrderId = 0;
                goods_OrderExpressRepository.Insert(demodel);
                //流程
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "卖家已发货",
                    CreateDate = DateTime.Now,
                    MallBaseId = demodel.MallBaseId,
                    ReOrderId = demodel.AfterSaleOrderId,
                    TenantId = demodel.TenantId,
                    Type = 2
                });
                return ApiResult.Success();
            }
            return ApiResult.Failed();
        }


        /// <summary>
        /// 订单发货
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetOrderSendGoods(RB_Goods_OrderExpress_Extend demodel,out string message)
        {
            message = "";
            try
            {
                if (demodel.Id > 0)
                {
                    var omodel = goods_OrderRepository.GetEntity(demodel.OrderId);
                    if (omodel == null)
                    {
                        message= "订单不存在";
                        return false;
                    }
                    if (omodel.OrderStatus >= Common.Enum.Goods.OrderStatusEnum.Received)
                    {
                        message= "已收货无法修改物流信息";
                        return false;
                    }
                    //修改物流信息
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                    {
                        { nameof(RB_Goods_OrderExpress.ExpressId),demodel.ExpressId},
                        { nameof(RB_Goods_OrderExpress.Type),demodel.Type},
                        { nameof(RB_Goods_OrderExpress.PostCode),demodel.PostCode},
                        { nameof(RB_Goods_OrderExpress.ExpressNumber),demodel.ExpressNumber},
                        { nameof(RB_Goods_OrderExpress.Remark),demodel.Remark},
                        { nameof(RB_Goods_OrderExpress.UpdateDate),demodel.UpdateDate},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>()
                    {
                        new WhereHelper()
                        {
                             FiledName=nameof(RB_Goods_OrderExpress.Id),
                             FiledValue=demodel.Id,
                             OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                             FiledName=nameof(RB_Goods_OrderExpress.TenantId),
                             FiledValue=demodel.TenantId,
                             OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper()
                        {
                             FiledName=nameof(RB_Goods_OrderExpress.MallBaseId),
                             FiledValue=demodel.MallBaseId,
                             OperatorEnum=OperatorEnum.Equal
                        },
                    };
                    bool flag = goods_OrderExpressRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        goods_LogRepository.Insert(new RB_Goods_Log()
                        {
                            Content = "修改快递信息",
                            CreateDate = demodel.CreateDate,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            SourceId = demodel.OrderId,
                            TenantId = demodel.TenantId,
                            Type = 1
                        });
                    }
                    message= flag ? "" : "保存失败";
                    return flag;
                }
                else
                {
                    var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderId = demodel.OrderId });
                    if (demodel.OrderDetailIdList.Where(x => !dlist.Select(y => y.Id).Contains(x)).Any())
                    {
                        message= "传递的订单明细Id有误，请核实后再试";
                        return false;
                    }
                    //验证商品是否已创建快递信息
                    var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderId = demodel.OrderId });
                    foreach (var item in demodel.OrderDetailIdList)
                    {
                        if (erlist.Where(x => x.OrderDetailId == item).Any())
                        {
                            message= "传递的订单明细Id:" + item + ",已绑定物流信息无法再次绑定";
                            return false;
                        }
                    }
                    int Id = goods_OrderExpressRepository.Insert(demodel);
                    if (Id > 0)
                    {
                        foreach (var item in demodel.OrderDetailIdList)
                        {
                            goods_ExpressRelevanceRepository.Insert(new RB_Goods_ExpressRelevance()
                            {
                                Id = 0,
                                CreateDate = demodel.CreateDate,
                                MallBaseId = demodel.MallBaseId,
                                OrderDetailId = item,
                                OrderExpressId = Id,
                                OrderId = demodel.OrderId,
                                TenantId = demodel.TenantId,
                                UpdateDate = demodel.UpdateDate
                            });
                        }
                        goods_LogRepository.Insert(new RB_Goods_Log()
                        {
                            Content = "新增快递信息",
                            CreateDate = demodel.CreateDate,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            SourceId = demodel.OrderId,
                            TenantId = demodel.TenantId,
                            Type = 1
                        });
                        //判断商品是否已全部绑定快递， 是的话需要更新商品状态为已发货
                        if (erlist.Select(x => x.OrderDetailId).Distinct().Count() + demodel.OrderDetailIdList.Distinct().Count() == dlist.Count())
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                            {
                                { nameof(RB_Goods_Order.OrderStatus),OrderStatusEnum.WaitReceiving},
                                { nameof(RB_Goods_Order.DeliveryTime),DateTime.Now},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() 
                            {
                                new WhereHelper()
                                {
                                     FiledName=nameof(RB_Goods_Order.OrderId),
                                     FiledValue=demodel.OrderId,
                                     OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            bool oflag = goods_OrderRepository.Update(keyValues, wheres);
                            if (oflag)
                            {
                                goods_LogRepository.Insert(new RB_Goods_Log()
                                {
                                    Content = "修改订单状态为：待收货",
                                    CreateDate = DateTime.Now,
                                    Id = 0,
                                    MallBaseId = demodel.MallBaseId,
                                    SourceId = demodel.OrderId,
                                    TenantId = demodel.TenantId,
                                    Type = 1
                                });
                            }

                            var omodel = goods_OrderRepository.GetEntity(demodel.OrderId);
                            var umodel = member_UserRepository.GetEntity(omodel.UserId);

                            string goodsName = dlist.FirstOrDefault().GoodsName;
                            if (dlist.Count > 1)
                            {
                                if (goodsName.Length > 6)
                                {
                                    goodsName = goodsName.Substring(0, 6);
                                }
                                goodsName += "等" + dlist.Count + "件";
                            }
                            else
                            {
                                if (goodsName.Length > 10)
                                {
                                    goodsName = goodsName.Substring(0, 10);
                                }
                            }
                            if (demodel.Type == 1)
                            {
                                var exModel = logistics_ExpressRepository.GetEntity(demodel.ExpressId);
                                new MiniProgramMsgModule().SendOrderDeliverMsg(demodel.TenantId, demodel.MallBaseId, umodel.OpenId, "商品已发货，注意查收！", demodel.ExpressNumber, exModel.Name ?? "其他", goodsName);
                            }
                            else
                            {
                                //new MiniProgramMsgModule().SendOrderDeliverMsg(demodel.TenantId, demodel.MallBaseId, umodel.OpenId, demodel.Remark ?? "", "", "其他方式", goodsName);
                            }
                        }
                    }
                    message= Id > 0 ? "" : "保存失败";
                    return Id > 0;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetOrderSendGoods");
                message= "保存失败";
                return false;
            }
        }

        /// <summary>
        /// 清空回收站
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderEmptyRecycleBin(int tenantId, int mallBaseId)
        {
            return goods_OrderRepository.SetOrderEmptyRecycleBin(tenantId, mallBaseId);
        }

        /// <summary>
        /// 申请取消订单审核
        /// </summary>
        /// <param name="omodel"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="outTradeNo">商户订单号</param>
        /// <param name="transactionId">微信订单号</param>
        /// <param name="refundid">微信退款单号</param>
        /// <returns></returns>
        public bool SetOrderApplyForCancelAudit(RB_Goods_Order_Extend omodel, int type, string remark, string RefundOrderNo, int tenantId, int mallBaseId, Common.Enum.Goods.OrderPayTypeEnum payType, string dPrice, string outTradeNo, string transactionId, string refundid, int empId)
        {
            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);
                    keyValues.Add(nameof(RB_Goods_Order.ApplyForCancelStatus), 1);
                    keyValues.Add(nameof(RB_Goods_Order.RefundOrderNo), RefundOrderNo);
                    keyValues.Add(nameof(RB_Goods_Order.Refund), omodel.Income);
                }
                else
                {
                    keyValues.Add(nameof(RB_Goods_Order.ApplyForCancelStatus), 2);
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), omodel.HistoryOrderStatus);
                    keyValues.Add(nameof(RB_Goods_Order.RejectRemark), remark);
                    keyValues.Add(nameof(RB_Goods_Order.IsApplyForCancel), 2);
                }

                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.OrderId),
                          FiledValue=omodel.OrderId,
                           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)
                    {
                        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
                                {
                                    //更新商品表库存
                                    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);
                                }
                                goods_LogRepository.Insert(new RB_Goods_Log()
                                {
                                    Id = 0,
                                    Type = 2,
                                    SourceId = item.GoodsId,
                                    Content = $"同意客人申请取消订单{omodel.OrderId}，还原商品库存:" + item.Number,
                                    CreateDate = DateTime.Now,
                                    MallBaseId = mallBaseId,
                                    TenantId = tenantId
                                });

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

                        var umodel = member_UserRepository.GetEntity(omodel.UserId);
                        //积分抵扣回滚
                        if (TotalIntegralNumber > 0)
                        {
                            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);
                            }
                        }
                        //余额支付回滚

                        string goodsName = detailList.FirstOrDefault().GoodsName;
                        if (detailList.Count > 1)
                        {
                            if (goodsName.Length > 6)
                            {
                                goodsName = goodsName.Substring(0, 6);
                            }
                            goodsName += "等" + detailList.Count + "件";
                        }
                        else
                        {
                            if (goodsName.Length > 10)
                            {
                                goodsName = goodsName.Substring(0, 10);
                            }
                        }
                        new MiniProgramMsgModule().SendOrderCancelMsg(tenantId, mallBaseId, umodel.OpenId, omodel.OrderNo, "订单已取消", (omodel.Income ?? 0).ToString(), goodsName);
                    }
                    //记录日志
                    string Content = $"empId：{empId} 客人申请取消订单，审核：{(type == 1 ? "同意" : "拒绝")}";
                    if (type == 2)
                    {
                        Content += "，拒绝理由：" + remark;
                    }
                    if (!string.IsNullOrWhiteSpace(dPrice) && !string.IsNullOrWhiteSpace(outTradeNo) && !string.IsNullOrWhiteSpace(transactionId) && !string.IsNullOrWhiteSpace(refundid))
                    {
                        goods_Online_TradeRepository.Insert(new Model.Entity.Product.RB_Goods_Online_Trade()
                        {
                            Id = 0,
                            User_Id = omodel.UserId,
                            FinanceId = 0,
                            CreateDate = DateTime.Now,
                            IsRefund = 2,
                            MallBaseId = omodel.MallBaseId,
                            Money = omodel.Income,
                            OrderId = omodel.OrderId,
                            Out_Trade_No = outTradeNo,
                            PayType = "",
                            PayWay = payType,
                            Pay_Date = System.DateTime.Now,
                            Pay_Result = 0,
                            RefundMoney = string.IsNullOrWhiteSpace(dPrice) ? 0 : Convert.ToDecimal(dPrice),
                            RefundStatus = 2,
                            RefundTrade_Order = RefundOrderNo,
                            Refund_Date = DateTime.Now,
                            Refund_Id = refundid,
                            Remarks = omodel.UserName + "(id:" + omodel.UserId + ")",
                            TenantId = omodel.TenantId,
                            Transaction_Id = transactionId,
                            Type = 2
                        });
                    }
                    goods_LogRepository.Insert(new RB_Goods_Log()
                    {
                        Content = Content,
                        CreateDate = DateTime.Now,
                        Id = 0,
                        MallBaseId = mallBaseId,
                        SourceId = omodel.OrderId,
                        TenantId = tenantId,
                        Type = 1
                    });
                }
                goods_OrderRepository.DBSession.Commit();
                if (flag && type == 1 && tenantId == 1 && omodel.OrderSource == UserSourceEnum.ERP)
                {
                    //同意 创建财务单据  屏蔽  改为每日自动创建
                    // 2020 -09-15  ld erp订单 需点击创建财务单据
                    OrderRefundFinanceModule(omodel);
                }
                return flag;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "");
                goods_OrderRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 后台强制取消订单
        /// </summary>
        /// <param name="omodel"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="outTradeNo">商户订单号</param>
        /// <param name="transactionId">微信订单号</param>
        /// <param name="refundid">微信退款单号</param>
        /// <returns></returns>
        public bool SetOrderForcedToCancel(RB_Goods_Order_Extend omodel, string RefundOrderNo, int tenantId, int mallBaseId, Common.Enum.Goods.OrderPayTypeEnum payType, string dPrice, string outTradeNo, string transactionId, string refundid)
        {
            var trans = goods_OrderRepository.DbTransaction;
            try
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
                keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Cancel);
                keyValues.Add(nameof(RB_Goods_Order.CancelTime), DateTime.Now);
                keyValues.Add(nameof(RB_Goods_Order.RefundOrderNo), RefundOrderNo);
                if (omodel.OrderStatus != OrderStatusEnum.NonPayment)
                {
                    keyValues.Add(nameof(RB_Goods_Order.Refund), omodel.Income);
                }

                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.OrderId),
                          FiledValue=omodel.OrderId,
                           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)
                {
                    #region 回滚
                    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);
                                }
                            }
                            goods_LogRepository.Insert(new RB_Goods_Log()
                            {
                                Id = 0,
                                Type = 2,
                                SourceId = item.GoodsId,
                                Content = $"后台强制取消订单{omodel.OrderId}，还原商品库存:" + item.Number,
                                CreateDate = DateTime.Now,
                                MallBaseId = mallBaseId,
                                TenantId = tenantId
                            });

                            if (item.IntegralNumber > 0)
                            {
                                TotalIntegralNumber += (item.IntegralNumber ?? 0);
                            }
                        }
                        var umodel = member_UserRepository.GetEntity(omodel.UserId);
                        //积分抵扣回滚
                        if (TotalIntegralNumber > 0)
                        {
                            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);
                            }
                        }
                        //余额支付回滚

                        string goodsName = detailList.FirstOrDefault().GoodsName;
                        if (detailList.Count > 1)
                        {
                            if (goodsName.Length > 6)
                            {
                                goodsName = goodsName.Substring(0, 6);
                            }
                            goodsName += "等" + detailList.Count + "件";
                        }
                        else
                        {
                            if (goodsName.Length > 10)
                            {
                                goodsName = goodsName.Substring(0, 10);
                            }
                        }
                        new MiniProgramMsgModule().SendOrderCancelMsg(tenantId, mallBaseId, umodel.OpenId, omodel.OrderNo, "订单已取消", (omodel.Income ?? 0).ToString(), goodsName);
                        #endregion

                        //记录日志
                        string Content = $"后台强制取消订单";
                        goods_LogRepository.Insert(new RB_Goods_Log()
                        {
                            Content = Content,
                            CreateDate = DateTime.Now,
                            Id = 0,
                            MallBaseId = mallBaseId,
                            SourceId = omodel.OrderId,
                            TenantId = tenantId,
                            Type = 1
                        });
                        if (!string.IsNullOrWhiteSpace(dPrice) && !string.IsNullOrWhiteSpace(outTradeNo) && !string.IsNullOrWhiteSpace(transactionId) && !string.IsNullOrWhiteSpace(refundid))
                        {
                            goods_Online_TradeRepository.Insert(new Model.Entity.Product.RB_Goods_Online_Trade()
                            {
                                Id = 0,
                                User_Id = omodel.UserId,
                                FinanceId = 0,
                                CreateDate = DateTime.Now,
                                IsRefund = 2,
                                MallBaseId = umodel.MallBaseId,
                                Money = omodel.Income,
                                OrderId = omodel.OrderId,
                                Out_Trade_No = outTradeNo,
                                PayType = "",
                                PayWay = payType,
                                Pay_Date = System.DateTime.Now,
                                Pay_Result = 0,
                                RefundMoney = string.IsNullOrWhiteSpace(dPrice) ? 0 : Convert.ToDecimal(dPrice),
                                RefundStatus = 2,
                                RefundTrade_Order = RefundOrderNo,
                                Refund_Date = DateTime.Now,
                                Refund_Id = refundid,
                                Remarks = omodel.UserName + "(id:" + omodel.UserId + ")",
                                TenantId = umodel.TenantId,
                                Transaction_Id = transactionId,
                                Type = 2
                            });
                        }
                    }

                    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);
                            }
                        }
                    }
                }
                goods_OrderRepository.DBSession.Commit();
                if (flag && tenantId == 1 && omodel.OrderSource == UserSourceEnum.ERP)
                {
                    if (omodel.OrderStatus != OrderStatusEnum.NonPayment)
                    {
                        //同意 创建财务单据   屏蔽 改为每日自动创建
                        //erp订单 需创建财务单据 2020-09-15
                        OrderRefundFinanceModule(omodel, true);
                    }
                }
                return flag;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "");
                goods_OrderRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 生成退款单据
        /// </summary>
        /// <param name="omodel"></param>
        /// <returns></returns>
        public bool OrderRefundFinanceModule(RB_Goods_Order_Extend omodel, bool IsForcedToCancel = false)
        {
            var flag = false;
            try
            {
                decimal Money = omodel.Income ?? 0;

                //查询用户
                var umodel = member_UserRepository.GetEntity(omodel.UserId);
                if (umodel == null) { return false; }
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 3 });

                string dstr = "客人付款:" + (omodel.Income ?? 0) + "金额，退款:" + (omodel.Income ?? 0);
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = omodel.OrderId });
                    string Remark1 = "";
                    if (dlist.Any())
                    {
                        foreach (var qqitem in dlist)
                        {
                            Remark1 += qqitem.GoodsName + " " + qqitem.Specification + " ";
                        }
                    }
                    var detailList = new List<object>() {
                        new
                        {
                            CostTypeId = item.RefundCostTypeId,
                            Number = 1,
                            OriginalMoney = Money,
                            UnitPrice = Money,
                            Remark = Remark1 + "单号：" + omodel.OrderNo  + "   " + dstr
                        }
                    };

                    item.IsPublic = 8;//默认原路退款
                    string Remark = "名称:" + umodel.Name + "(" + umodel.Id + ")" + "     " + System.DateTime.Now.ToString("yyyy年MM月dd日") + " 自动生成财务单据（ERP下单）";
                    if (IsForcedToCancel)
                    {
                        Remark = "后台强制取消该订单，用户名称:" + umodel.Name + "(" + umodel.Id + ")" + "     " + System.DateTime.Now.ToString("yyyy年MM月dd日") + " 自动生成财务单据（ERP下单）";
                    }
                    List<RB_ECFinanceId_Relation> ECList = new List<RB_ECFinanceId_Relation>();
                    foreach (var qitem in dlist)
                    {
                        ECList.Add(new RB_ECFinanceId_Relation()
                        {
                            ECOrderId = qitem.OrderId,
                            ECOrderDetailId = qitem.Id
                        });
                    }
                    var financeObj = new
                    {
                        CreateBy = Config.ExpendDirector,
                        item.IsPublic,
                        ClientType = 0,
                        ClientID = 0,
                        item.CurrencyId,
                        WBMoney = Money,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        RB_Branch_Id = Config.ExpendBranchId,
                        TemplateId = item.WorkFlowId,
                        OrderSource = 16,
                        OtherType = 24,
                        ReFinanceId = omodel.OrderId,
                        Remark,
                        detailList,
                        RB_Depart_Id = Config.ExpendDepartment,
                        ECOrderList = ECList
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign
                    };

                    string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                    LogHelper.Write(apiResult);
                    var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                    if (apir.resultCode == 1)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Goods_Order_Extend.Remark), omodel.Remark +"   自动生成财务退款单据："+ apir.data.ToString()}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                              FiledValue=omodel.OrderId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.TenantId),
                              FiledValue=omodel.TenantId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.MallBaseId),
                              FiledValue=omodel.MallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        goods_OrderRepository.Update(keyValues, wheres);
                    }
                    else
                    {
                        //记录自动生成失败，需手动新增财务单据
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Goods_Order_Extend.Remark), omodel.Remark +"   财务单据新增失败，请手动增加"}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                              FiledValue=omodel.OrderId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.TenantId),
                              FiledValue=omodel.TenantId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.MallBaseId),
                              FiledValue=omodel.MallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        goods_OrderRepository.Update(keyValues, wheres);
                    }
                }
            }
            catch (Exception ex)
            {

                LogHelper.Write(ex);
            }

            return flag;
        }

        /// <summary>
        /// 修改订单收货地址
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetOrderShopingAddress(RB_Goods_Order_Extend demodel)
        {
            var omodel = goods_OrderRepository.GetEntity(demodel.OrderId);
            if (omodel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_Order.Consignee), demodel.Consignee},
                { nameof(RB_Goods_Order.Mobile), demodel.Mobile},
                { nameof(RB_Goods_Order.Province), demodel.Province},
                { nameof(RB_Goods_Order.City), demodel.City},
                { nameof(RB_Goods_Order.District), demodel.District},
                { nameof(RB_Goods_Order.ShoppingAddress), demodel.ShoppingAddress}
            };

            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.OrderId),
                      FiledValue=demodel.OrderId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.TenantId),
                      FiledValue=demodel.TenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.MallBaseId),
                      FiledValue=demodel.MallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = $"修改收货地址，历史：{omodel.Consignee} {omodel.Mobile} {omodel.Province} {omodel.City} {omodel.District} {omodel.ShoppingAddress}",
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = demodel.MallBaseId,
                    SourceId = demodel.OrderId,
                    TenantId = demodel.TenantId,
                    Type = 1
                });
            }
            return flag;
        }

        /// <summary>
        /// 设置订单操作
        /// </summary>
        /// <param name="orderModel"></param>
        /// <param name="type">类型  1修改备注  2修改金额  3强制取消  4放入回收站  5确认收货  6确认完成  7回收恢复 8回收删除</param>
        /// <param name="remark"></param>
        /// <param name="income"></param>
        /// <param name="address"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderOperation(RB_Goods_Order_Extend orderModel, int type, string remark, decimal income, string address, int tenantId, int mallBaseId, Microsoft.AspNetCore.Http.IHttpContextAccessor _accessor)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            switch (type)
            {
                case 1:
                    keyValues.Add(nameof(RB_Goods_Order.Remark), remark); break;
                case 2:
                    keyValues.Add(nameof(RB_Goods_Order.Income), income); break;
                case 3:
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Cancel); break;
                case 4:
                    keyValues.Add(nameof(RB_Goods_Order.Recycled), 1); break;
                case 5://确认收货
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Received);
                    keyValues.Add(nameof(RB_Goods_Order.ReceivingTime), DateTime.Now);
                    break;
                case 6://确认完成
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Completed);
                    keyValues.Add(nameof(RB_Goods_Order.FinishTime), DateTime.Now);
                    break;
                case 7:
                    keyValues.Add(nameof(RB_Goods_Order.Recycled), 2); break;
                case 8:
                    keyValues.Add(nameof(RB_Goods_Order.Status), 1); break;
            }

            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.OrderId),
                      FiledValue=orderModel.OrderId,
                       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)
            {
                //记录日志
                string Content = "";
                switch (type)
                {
                    case 1:
                        Content = "修改备注信息"; break;
                    case 2:
                        Content = "修改付款金额"; break;
                    case 3:
                        Content = "强制取消订单"; break;
                    case 4:
                        Content = "放入回收站"; break;
                    case 5:
                        Content = "确认收货"; break;
                    case 6:
                        Content = "确认完成"; break;
                    case 7:
                        Content = "回收站恢复订单"; break;
                    case 8:
                        Content = "确认删除订单"; break;
                }
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = Content,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                });
                if (type == 6)
                {
                    bool IsUpdateCommission = true;
                    var mallModel = mallBaseRepository.GetEntity(mallBaseId);
                    if (mallModel != null && mallModel.AfterTime > 0)
                    {
                        var OrderM = goods_OrderRepository.GetEntity(orderModel.OrderId);
                        if (OrderM != null && OrderM.ReceivingTime.HasValue && OrderM.ReceivingTime.Value.AddDays(mallModel.AfterTime) > DateTime.Now)
                        {
                            IsUpdateCommission = false;
                        }
                    }
                    if (IsUpdateCommission)
                    {
                        //更新返佣为已返佣
                        var ocList = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                        if (ocList.Where(x => x.CommissionState == 1).Any())
                        {
                            foreach (var item in ocList.Where(x => x.CommissionState == 1))
                            {
                                //查询是否有申请退款
                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                if (!afterSaleList.Any())
                                {
                                    //获取分销商信息
                                    var disInfo = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = item.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                                    if (disInfo != null && disInfo.AuditStatus == DistributorAuditStatusEnum.Audited)
                                    {
                                        //更新分销商佣金
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Distributor_Info_Extend.TotalCommission),(disInfo.TotalCommission??0)+(item.Commission??0)},
                                        { nameof(RB_Distributor_Info_Extend.CommissionWithdrawal),(disInfo.CommissionWithdrawal??0)+(item.Commission??0)},
                                    };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disInfo.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                        bool flag1 = distributor_InfoRepository.Update(keyValues2, wheres2);
                                        if (flag1)
                                        {
                                            //更新返佣状态
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_OrderCommission_Extend.CommissionState),2},
                                            { nameof(RB_Goods_OrderCommission_Extend.UpdateDate),DateTime.Now},
                                        };
                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                  FiledValue=item.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                            goods_OrderCommissionRepository.Update(keyValues1, wheres1);
                                        }
                                    }
                                }
                            }
                        }
                        //更新推荐供应商返佣
                        var oiList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                        if (oiList.Any())
                        {
                            foreach (var item in oiList)
                            {
                                //查询是否有申请退款
                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                if (!afterSaleList.Any())
                                {
                                    //更新返佣状态
                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderIntroduction_Extend.CommissionState),2},
                                        { nameof(RB_Goods_OrderIntroduction_Extend.UpdateDate),DateTime.Now},
                                    };
                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_Goods_OrderIntroduction_Extend.Id),
                                                FiledValue=item.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    goods_OrderIntroductionRepository.Update(keyValues1, wheres1);
                                }
                            }
                        }

                        //更新微店返佣
                        var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                        if (ssList.Where(x => x.CommissionState == 1).Any())
                        {
                            //验证是否是自动结算
                            var ssbaseModel = microShop_BasicsRepository.GetMicroShopBasicsList(new Model.Entity.BaseSetUp.RB_MicroShop_Basics() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                            if (("," + (ssbaseModel?.SettlementType ?? "") + ",").Contains("," + ((int)DistrbutorWithdrawWayEnum.ZDXJ).ToString() + ","))
                            {
                                var ssmodel = ssList.FirstOrDefault();
                                //获取微店信息
                                var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                {
                                    //总佣金
                                    decimal TotalCommission = 0, OldCommission = 0;
                                    foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                    {
                                        var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                        if (!afterSaleList.Any())
                                        {
                                            TotalCommission += (item.Commission ?? 0);
                                        }
                                    }
                                    #region 看微店佣金是否是负数  是的话  需要走总佣金里减去
                                    OldCommission = TotalCommission;
                                    if ((smallModel.Commission ?? 0) < 0)
                                    {
                                        TotalCommission += (smallModel?.Commission ?? 0);
                                    }
                                    #endregion
                                    if (TotalCommission > 0)
                                    {
                                        decimal RemitMoney = TotalCommission, fee = 0;
                                        var feeValue = ssbaseModel?.WithdrawalFree ?? 0;
                                        if (feeValue > 0)
                                        {
                                            fee = Math.Round(TotalCommission * (feeValue) / 100, 2, MidpointRounding.AwayFromZero);
                                            RemitMoney = TotalCommission - fee;
                                        }
                                        var minModel = miniProgramRepository.GetEntity(mallBaseId);
                                        var umodel = member_UserRepository.GetEntity(ssmodel.UserId);
                                        //打款
                                        Random R = new Random();
                                        int Rstr = R.Next(111, 999);
                                        string OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                                        int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
                                        var flagpay = false;
                                        if (IsNormalServer == 1)
                                        {
                                            flagpay = Common.Pay.PayUtilWeiXin.GetTransfersOrder(OrderNum, RemitMoney, (ssmodel.UserId ?? 0).ToString(), umodel.OpenId, minModel.WeChatPayCertificateUrl, minModel.WeChatApiSecret, minModel.MiniAppId, _accessor);
                                        }
                                        if (flagpay)
                                        {
                                            //更新状态
                                            foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                            {
                                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                {
                                                    //更新返佣状态
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                        { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                        { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                    };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                FiledValue=item.Id,
                                                                OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                    smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                }
                                            }
                                            //写入已提现数据
                                            smallShops_RemitRepository.Insert(new Model.Entity.User.RB_SmallShops_Remit()
                                            {
                                                Id = 0,
                                                AccountName = "",
                                                AccountNumber = "",
                                                AppliedMoney = TotalCommission,
                                                AuditDate = DateTime.Now,
                                                AuditRemark = "",
                                                AuditStatus = DistributorRemitAuditStatusEnum.HaveMoney,
                                                BankName = "",
                                                CreateDate = DateTime.Now,
                                                Fee = fee,
                                                FinanceId = 0,
                                                MallBaseId = mallBaseId,
                                                OrderNum = OrderNum,
                                                RejectDate = null,
                                                RejectRemark = "",
                                                RemitDate = DateTime.Now,
                                                RemitMoney = RemitMoney,
                                                RemitRemark = "自动结算打款",
                                                ReOrderIds = "[" + (orderModel.OrderId).ToString() + "]",
                                                ReOrderNos = "\"" + orderModel.OrderNo + "\"：" + RemitMoney + "元",
                                                TenantId = tenantId,
                                                UserId = ssmodel.UserId,
                                                WithdrawalWay = DistrbutorWithdrawWayEnum.ZDXJ
                                            });
                                        }
                                        else
                                        {
                                            //更新状态
                                            foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                            {
                                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                {
                                                    //更新返佣状态
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                    { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                    { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                    { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                            FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                            FiledValue=item.Id,
                                                            OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                    smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                }
                                            }
                                            //写入已提现数据
                                            smallShops_RemitRepository.Insert(new Model.Entity.User.RB_SmallShops_Remit()
                                            {
                                                Id = 0,
                                                AccountName = "",
                                                AccountNumber = "",
                                                AppliedMoney = TotalCommission,
                                                AuditDate = DateTime.Now,
                                                AuditRemark = "自动现结失败，变更为手动打款",
                                                AuditStatus = DistributorRemitAuditStatusEnum.ToPlayWith,
                                                BankName = "",
                                                CreateDate = DateTime.Now,
                                                Fee = fee,
                                                FinanceId = 0,
                                                MallBaseId = mallBaseId,
                                                OrderNum = OrderNum,
                                                RejectDate = null,
                                                RejectRemark = "",
                                                RemitDate = DateTime.Now,
                                                RemitMoney = RemitMoney,
                                                RemitRemark = "",
                                                ReOrderIds = "[" + (orderModel.OrderId).ToString() + "]",
                                                ReOrderNos = "\"" + orderModel.OrderNo + "\"：" + RemitMoney + "元",
                                                TenantId = tenantId,
                                                UserId = ssmodel.UserId,
                                                WithdrawalWay = DistrbutorWithdrawWayEnum.ZDDK
                                            });
                                        }
                                        //更新微店佣金等于0                                            
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                            { nameof(RB_SmallShops_Info_Extend.Commission), TotalCommission}
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                    }
                                    else if (TotalCommission < 0)
                                    {
                                        //存在微店佣金里  继续负数累加                                      
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                            { nameof(RB_SmallShops_Info_Extend.Commission),TotalCommission},
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                    }
                                }
                            }
                            else
                            {
                                var ssmodel = ssList.FirstOrDefault();
                                //获取微店信息
                                var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                                foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                {
                                    //查询是否有申请退款
                                    var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                    if (!afterSaleList.Any())
                                    {
                                        if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                        {
                                            //更新微店佣金
                                            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0)+(item.Commission??0)},
                                            { nameof(RB_SmallShops_Info_Extend.Commission),(smallModel.Commission??0)+(item.Commission??0)},
                                        };
                                            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                            bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                            if (flag1)
                                            {
                                                //更新返佣状态
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                            };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                        FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                        FiledValue=item.Id,
                                                        OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                                smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //积分赠送
                    var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderModel.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
                    if (dlist.Any())
                    {
                        int IntegralGoodsPresent = 0;
                        foreach (var item in dlist)
                        {
                            if (item.IntegralGoodsPresent > 0)
                            {
                                IntegralGoodsPresent += (item.IntegralGoodsPresent ?? 0);
                            }
                        }
                        if (IntegralGoodsPresent > 0)
                        {
                            //保存积分赠送
                            var umodel = member_UserRepository.GetEntity(orderModel.UserId);
                            //用户订单数增加
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User_Extend.Integral), (umodel.Integral ?? 0)+IntegralGoodsPresent }
                            };
                            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);
                            member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                            {
                                Id = 0,
                                CreateDate = DateTime.Now,
                                Description = "订单购买赠送积分，订单号：" + orderModel.OrderNo,
                                Image = 0,
                                Integral = IntegralGoodsPresent,
                                MallBaseId = orderModel.MallBaseId,
                                PlatformType = orderModel.OrderSource,
                                Remarks = "",
                                TenantId = orderModel.TenantId,
                                Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                UserId = orderModel.UserId,
                                OrderId = orderModel.OrderId
                            });
                        }
                    }

                    #region 粉象等级赠送  2020-07-21
                    if (dlist.Where(x => x.PresentFXGrade > 0).Any())
                    {
                        var demodel = new RB_Goods_Order_Extend
                        {
                            TenantId = tenantId,
                            MallBaseId = mallBaseId,
                            DetailList = dlist,
                            OrderNo = orderModel.OrderNo
                        };
                        //InsertPresentFXGrade(demodel, orderModel.UserId ?? 0, orderModel.OrderId);   2020-08-03 刘东 已在付款时赠送了
                    }
                    #endregion

                }
                else if (type == 3)
                {
                    //强制取消 (作废  使用新方法)

                }
                else if (type == 5)
                {
                    //收货  自动确认订单
                    SetOrderOperation(orderModel, 6, "", 0, "", tenantId, mallBaseId, _accessor);
                }
            }
            return flag;
        }

        /// <summary>
        /// 修改订单明细价格
        /// </summary>
        /// <param name="orderDetailId"></param>
        /// <param name="income"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderDetialMoneyInfo(int orderDetailId, decimal income, int tenantId, int mallBaseId)
        {
            var detModel = goods_OrderDetailRepository.GetEntity(orderDetailId);
            if (detModel == null)
            {
                return false;
            }
            var orderModel = goods_OrderRepository.GetEntity(detModel.OrderId);
            if (orderModel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderDetail.Final_Price),income }
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderDetail.Id),
                      FiledValue=orderDetailId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                      FiledValue=tenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                      FiledValue=mallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderDetailRepository.Update(keyValues, wheres);
            if (flag)
            {
                //修改订单付款总额
                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                    { nameof(RB_Goods_Order.Income),orderModel.Income + (income - (detModel.Final_Price??0)) }
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.OrderId),
                          FiledValue=orderModel.OrderId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                          FiledValue=tenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                          FiledValue=mallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                goods_OrderRepository.Update(keyValues1, wheres1);
                //记录日志
                Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = "修改订单商品价格：" + income + ";历史：价格:" + detModel.Final_Price,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                }));
            }
            return flag;
        }

        /// <summary>
        /// 修改订单金额+运费
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="income"></param>
        /// <param name="freightMoney"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderMoneyOrFreightInfo(int orderId, decimal income, decimal freightMoney, int tenantId, int mallBaseId)
        {
            var orderModel = goods_OrderRepository.GetEntity(orderId);
            if (orderModel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                { nameof(RB_Goods_Order.Income),income },
                { nameof(RB_Goods_Order.FreightMoney),freightMoney }
            };
            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_Order.OrderId),
                        FiledValue=orderModel.OrderId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = goods_OrderRepository.Update(keyValues1, wheres1);
            if (flag)
            {
                //记录日志
                Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = "修改订单价格：" + income + " /运费:" + freightMoney + ";历史：价格:" + orderModel.Income + " /运费:" + orderModel.FreightMoney,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                }));
            }
            return flag;
        }

        /// <summary>
        /// 修改司导订单保险费用
        /// </summary>
        /// <param name="orderDetailId"></param>
        /// <param name="insuranceCostMoney"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderInsuranceCostMoney(int orderDetailId, decimal insuranceCostMoney, int tenantId, int mallBaseId)
        {
            var orderModel = goods_OrderDetailRepository.GetEntity(orderDetailId);
            if (orderModel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderDetail.InsuranceCostMoney),insuranceCostMoney }
            };
            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.Id),
                        FiledValue=orderModel.Id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = goods_OrderDetailRepository.Update(keyValues1, wheres1);
            if (flag)
            {
                //记录日志
                Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = "修改订单商品：" + orderModel.GoodsName + "司导保险成本:" + insuranceCostMoney + ";历史：价格:" + (orderModel.InsuranceCostMoney ?? 0).ToString(),
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                }));
            }
            return flag;
        }

        /// <summary>
        /// 修改商品订单运费成本价
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="income"></param>
        /// <param name="freightMoney"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderFreightCostMoney(int orderId, decimal freightMoney, int tenantId, int mallBaseId)
        {
            var orderModel = goods_OrderDetailRepository.GetEntity(orderId);
            if (orderModel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderDetail.FreightCostMoney),freightMoney }
            };
            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.Id),
                        FiledValue=orderModel.Id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = goods_OrderDetailRepository.Update(keyValues1, wheres1);
            if (flag)
            {
                //记录日志
                Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = "修改订单商品：" + orderModel.GoodsName + "运费成本:" + freightMoney + ";历史：价格:" + (orderModel.FreightCostMoney ?? 0).ToString(),
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                }));
            }
            return flag;
        }



        /// <summary>
        /// 修改商品订单成本价
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="income"></param>
        /// <param name="freightMoney"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderCostMoney(int orderId, decimal costMoney, int tenantId, int mallBaseId)
        {
            var orderModel = goods_OrderDetailRepository.GetEntity(orderId);
            if (orderModel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderDetail.CostMoney),costMoney }
            };
            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.Id),
                        FiledValue=orderModel.Id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = goods_OrderDetailRepository.Update(keyValues1, wheres1);
            if (flag)
            {
                //记录日志
                Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = "修改订单商品：" + orderModel.GoodsName + "成本:" + costMoney + ";历史：价格:" + (orderModel.CostMoney ?? 0).ToString(),
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                }));
            }
            return flag;
        }



        /// <summary>
        /// 修改商品订单成本价
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="income"></param>
        /// <param name="freightMoney"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderSupplierId(int orderId, int SupplierId, int tenantId, int mallBaseId)
        {
            var orderModel = goods_OrderDetailRepository.GetEntity(orderId);
            if (orderModel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderDetail.SupplierId),SupplierId }
            };
            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.Id),
                        FiledValue=orderModel.Id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = goods_OrderDetailRepository.Update(keyValues1, wheres1);
            if (flag)
            {
                //记录日志
                Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = "修改订单商品：" + orderModel.GoodsName + "供应商ID:" + SupplierId + ";供应商历史ID:" + orderModel.SupplierId.ToString(),
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                }));
            }
            return flag;
        }

        /// <summary>
        /// 修改订单其他费用
        /// </summary>
        /// <param name="model"></param>
        /// <param name="money"></param>
        /// <param name="otherType"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public bool SetECUpdateOrderOtherMoney(RB_Goods_OrderDetail_Extend model, int money, int otherType, int type, string remark)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (type == 1)
            {
                if (otherType == 21)
                {
                    keyValues.Add(nameof(RB_Goods_OrderDetail.YSMoney), (model.YSMoney ?? 0) + money);
                }
                else
                {
                    keyValues.Add(nameof(RB_Goods_OrderDetail.YFMoney), (model.YFMoney ?? 0) + money);
                }
            }
            else
            {
                if (otherType == 21)
                {
                    if ((model.YSMoney ?? 0) == 0)
                    {
                        //如果应收=0  实收不更新  ld  2020-10-11
                        keyValues.Add(nameof(RB_Goods_OrderDetail.RealMoney), (model.RealMoney ?? 0));
                    }
                    else
                    {
                        keyValues.Add(nameof(RB_Goods_OrderDetail.RealMoney), (model.RealMoney ?? 0) + money);
                    }
                }
                else
                {
                    keyValues.Add(nameof(RB_Goods_OrderDetail.PayMoney), (model.PayMoney ?? 0) + money);
                }
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderDetail.Id),
                      FiledValue=model.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            return goods_OrderDetailRepository.Update(keyValues, wheres);
        }


        /// <summary>
        /// 更新订单直播人数和提成
        /// </summary>
        /// <param name="type">//1-更新人数和金额，2-更新人数，3-更新金额</param>
        /// <param name="LivePeopleNum"></param>
        /// <param name="LiveCommission"></param>
        /// <param name="orderList"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool UpdateOrderDetailLive(int type, int LivePeopleNum, decimal LiveCommission, List<RB_Goods_OrderDetail_Extend> orderList, int tenantId, int mallBaseId)
        {

            Dictionary<string, object> keyValues;
            if (type == 1)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_OrderDetail.LiveCommission),LiveCommission},
                     { nameof(RB_Goods_OrderDetail.LivePeopleNum),LivePeopleNum}
                };
            }
            else if (type == 2)
            {
                keyValues = new Dictionary<string, object>() {
                     { nameof(RB_Goods_OrderDetail.LivePeopleNum),LivePeopleNum}
                };
            }
            else if (type == 3)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_OrderDetail.LiveCommission),LiveCommission},
                };
            }
            else
            {
                return false;
            }
            bool flag = false;
            var trans = goods_OrderDetailRepository.DbTransaction;
            try
            {
                foreach (var item in orderList)
                {
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Goods_OrderDetail.Id),
                                FiledValue=item.Id,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Goods_OrderDetail.TenantId),
                                FiledValue=tenantId,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Goods_OrderDetail.MallBaseId),
                                FiledValue=mallBaseId,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };

                    flag = goods_OrderDetailRepository.Update(keyValues, wheres1, trans);
                    if (flag)
                    {
                        //记录日志
                        goods_LogRepository.Insert(new RB_Goods_Log()
                        {
                            Content = "修改订单商品：" + item.GoodsName + ((type == 1 || type == 2) ? ("主播人数：" + LivePeopleNum + "原主播人数：" + item.LivePeopleNum) : "") + ((type == 1 || type == 3) ? ("主播返佣金额：" + LiveCommission + "原佣金：" + item.LiveCommission) : ""),
                            CreateDate = DateTime.Now,
                            Id = 0,
                            MallBaseId = mallBaseId,
                            SourceId = item.OrderId,
                            TenantId = tenantId,
                            Type = 1
                        }, trans);
                    }
                }
                goods_OrderDetailRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "UpdateOrderDetailLive");
                goods_OrderDetailRepository.DBSession.Rollback("UpdateOrderDetailLive");
                return false;
            }

            return flag;
        }


        /// <summary>
        /// 根据订单好获取物流id
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public List<RB_Goods_ExpressRelevance_Extend> GetGoodsExpressRelevanceByOrderId(int orderId, int tenantId, int mallBaseId)
        {
            var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            return erlist;
        }

        /// <summary>
        /// 获取物流信息
        /// </summary>
        /// <param name="orderExpressId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetOrderSendGoodsInfo(int orderExpressId, int tenantId, int mallBaseId)
        {
            var oeModel = goods_OrderExpressRepository.GetEntity(orderExpressId).RefMapperTo<RB_Goods_OrderExpress_Extend>();
            if (oeModel == null)
            {
                return "";
            }
            //查询绑定的订单明细
            var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderExpressId = oeModel.Id });
            List<RB_Goods_OrderDetail_Extend> dlist = new List<RB_Goods_OrderDetail_Extend>();
            RB_Goods_Order orderModel = new RB_Goods_Order();
            if (erlist.Any())
            {
                //查询绑定的订单明细
                dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderDetailIds = string.Join(",", erlist.Select(x => x.OrderDetailId)) });
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }
                orderModel = goods_OrderRepository.GetEntity(erlist.FirstOrDefault()?.OrderId);
            }
            return new
            {
                oeModel.Id,
                oeModel.ExpressId,
                oeModel.ExpressNumber,
                oeModel.OrderId,
                oeModel.PostCode,
                oeModel.Remark,
                oeModel.Type,
                DetailList = dlist.Select(x => new
                {
                    x.Id,
                    x.CoverImage,
                    x.CoverImagePath,
                    x.GoodsName,
                    x.Number,
                    x.Specification,
                    orderModel.OrderStatus,
                    OrderStatusName = orderModel.OrderStatus.GetEnumName()
                })
            };
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetGoodsOrderInfo(int orderId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }
            var storeModel = new RB_Stores();
            if (model.StoresId > 0)
            {
                storeModel = storesRepository.GetEntity(model.StoresId);
            }

            //查询订单所属微店  2020-08-14 Add By:W
            if (model.SmallShopsId.HasValue && model.SmallShopsId > 0)
            {
                var smallShop = smallShopsInfoRepository.GetEntity(model.SmallShopsId ?? 0);
                if (smallShop != null)
                {
                    model.SmallShopsName = smallShop.Name;
                }
            }
            // 2020-08-14 Add By:W End

            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            var erList = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            //查询图片
            List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
            if (dlist.Any())
            {
                string servicePersions = string.Join(",", dlist.Select(x => x.ServicepersonalId));
                var serviceList = reserve_ServicePersonalRepository.GetServicePersonalList(new Model.Extend.Reserve.RB_Reserve_ServicePersonal_Extend()
                {
                    QIds = servicePersions
                });
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsBindExpress = erList.Where(x => x.OrderDetailId == item.Id).Any() ? 1 : 2;
                    item.ServicepersonalName = serviceList?.Where(qitem => qitem.ID == item.ServicepersonalId)?.FirstOrDefault()?.Name ?? "";
                }
            }
            model.DetailList = dlist;
            //地址
            model.DistrictAddress = (destinationRepository.GetEntity((model?.Province??0))?.Name ?? "") + " " + (destinationRepository.GetEntity((model?.City??0))?.Name ?? "") + " " + (destinationRepository.GetEntity((model?.District??0))?.Name ?? "");
            //物流
            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;
                    }
                }
            }

            //获取返佣列表
            var ocList = goods_OrderCommissionRepository.GetListGroupByUser(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId }).OrderBy(x => x.Grade).ToList();
            if (ocList.Any())
            {
                var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (ocList.Where(x => x.Type == 3).Any())
                {
                    string gradeIds = string.Join(",", ocList.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = tenantId, MallBaseId = mallBaseId });
                }
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ocList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ocList)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";

                    if (item.Type == 1)
                    {
                        if (item.Grade == 0)
                        {
                            item.GradeDescription = "自购返利";
                        }
                        else if (item.Grade == 1)
                        {
                            item.GradeDescription = "一级佣金";
                        }
                        else if (item.Grade == 2)
                        {
                            item.GradeDescription = "二级佣金";
                        }
                        else if (item.Grade == 3)
                        {
                            item.GradeDescription = "三级佣金";
                        }
                    }
                    else if (item.Type == 3)
                    {
                        var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                    }
                }
            }

            var vipList = vip_BuyRepository.GetVipBuyList(new RB_Vip_Buy_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, ReOrderId = model.OrderId });
            List<RB_VipBuy_Commission_Extend> clist = new List<RB_VipBuy_Commission_Extend>();
            if (vipList.Any())
            {
                string vipIds = string.Join(",", vipList.Select(x => x.Id));
                clist = vipBuy_CommissionRepository.GetList(new RB_VipBuy_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderIds = vipIds });
                var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = tenantId, MallBaseId = mallBaseId });
                //获取用户
                var ulist = new List<RB_Member_User_Extend>();
                if (clist.Any())
                {
                    ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", clist.Select(x => x.UserId).Distinct()) });
                    foreach (var qitem in clist)
                    {
                        var fxmodel = FXList.Where(x => x.Id == qitem.Grade).FirstOrDefault();
                        qitem.GradeDescription = fxmodel.GradeName;
                        qitem.UserName = ulist.Where(x => x.Id == qitem.UserId).FirstOrDefault()?.Name ?? "";
                    }
                }
            }

            #region 推荐返佣
            List<RB_Goods_OrderIntroduction_Extend> OrderIntroduction = new List<RB_Goods_OrderIntroduction_Extend>();
            var introductList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (introductList.Any())
            {
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", introductList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ulist)
                {
                    decimal Commission = introductList.Where(x => x.UserId == item.Id).Sum(x => x.Commission ?? 0);
                    OrderIntroduction.Add(new RB_Goods_OrderIntroduction_Extend()
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        Commission = Commission
                    });
                }
            }
            #endregion

            #region 微店返佣
            List<RB_SmallShops_Commission_Extend> SmallShopsCommission = new List<RB_SmallShops_Commission_Extend>();
            var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (ssList.Any())
            {
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ssList.Select(x => x.UserId).Distinct()) });
                var slist = smallShops_InfoRepository.GetListForSingle(new RB_SmallShops_Info_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ssList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ulist)
                {
                    decimal Commission = ssList.Where(x => x.UserId == item.Id).Sum(x => x.Commission ?? 0);
                    var smodel = slist.Where(x => x.UserId == item.Id).FirstOrDefault();
                    SmallShopsCommission.Add(new RB_SmallShops_Commission_Extend()
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        Name = smodel?.Name ?? "",
                        Commission = Commission
                    });
                }
            }
            #endregion


            #region  优惠券 2020-08-25 Add By:W Start

            List<RB_Member_DiscountCoupon_Extend> memberCouponList = new List<RB_Member_DiscountCoupon_Extend>();
            if (!string.IsNullOrWhiteSpace(model.CouponsIds))
            {
                memberCouponList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, UseState = -1, Ids = model.CouponsIds });
            }
            #endregion 2020-08-25 Add By:W  End


            return ApiResult.Success("", new
            {
                model.OrderId,
                model.OrderStatus,
                OrderStatusName = model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                PaymentTime = model.PaymentTime.HasValue ? model.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = model.DeliveryTime.HasValue ? model.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = model.ReceivingTime.HasValue ? model.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = model.FinishTime.HasValue ? model.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.Remark,
                model.BuyerMessage,
                model.PreferPrice,
                model.Income,
                model.FreightMoney,
                CouponMoney = model.CouponMoney ?? 0,
                IntegralMoney = (model.DetailList != null && model.DetailList.Any()) ? (model.DetailList.Sum(x => x.IntegralMoney ?? 0)) : 0,
                IntegralNumber = (model.DetailList != null && model.DetailList.Any()) ? (model.DetailList.Sum(x => x.IntegralNumber ?? 0)) : 0,
                MemberDiscountCouponList = memberCouponList.Select(y => new
                {
                    y.Name,
                    y.MinConsumePrice,
                    y.MaxDiscountsPrice,
                    y.UseType,
                    y.CouponType,
                    y.DiscountsPrice
                }),
                OrderInfo = new
                {
                    model.OrderNo,
                    model.MerchantsNo,
                    model.PaymentWay,
                    PaymentWayName = model.PaymentWay.GetEnumName(),
                    model.DeliveryMethod,
                    DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                    UserName = member_UserRepository.GetEntity(model.UserId)?.Name ?? "",
                    model.Consignee,
                    model.Mobile,
                    model.DistrictAddress,
                    model.ShoppingAddress,
                    model.Country,
                    model.Province,
                    model.City,
                    model.District,
                    model.SmallShopsName,
                    model.SmallShopsId,
                    storeName = storeModel?.Name ?? "",
                    storeAddress = storeModel?.Address ?? "",
                    OrderExpressList = 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.CoverImage,
                            z.CoverImagePath,
                            z.GoodsName
                        })
                    })
                },
                DistributionInfo = ocList.Select(x => new
                {
                    x.Id,
                    x.Grade,
                    x.GradeDescription,
                    x.UserName,
                    x.Mobile,
                    x.Commission
                }),
                VipCommissionInfo = clist.Select(x => new
                {
                    x.Id,
                    x.Grade,
                    x.GradeDescription,
                    x.UserName,
                    x.Commission
                }),
                OrderIntroductionInfo = OrderIntroduction.Select(x => new
                {
                    x.UserId,
                    x.UserName,
                    x.Commission
                }),
                SmallShopsCommissionInfo = SmallShopsCommission.Select(x => new
                {
                    x.UserId,
                    x.UserName,
                    SmallShopsName = x.Name,
                    x.Commission
                }),
                DetailList = model.DetailList.Select(x => new
                {
                    x.Id,
                    x.GoodsName,
                    x.CoverImage,
                    x.CoverImagePath,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>((x?.Specification??"")),
                    x.Unit_Price,
                    x.Number,
                    x.Original_Price,
                    x.Final_Price,
                    x.IsBindExpress,
                    x.FreeShippingRemarks,
                    x.SmallShopsCostPrice,
                    CouponMoney = x.CouponMoney ?? 0,
                    InsuranceMoney = x.InsuranceMoney ?? 0,
                    IntegralMoney = x.IntegralMoney ?? 0,
                    IntegralNumber = x.IntegralNumber ?? 0,
                    x.ServiceTime,
                    x.ServiceDate,
                    x.ServicepersonalName,
                }),
            });
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetSDGoodsOrderInfo(int orderId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }

            //查询订单所属微店  2020-08-14 Add By:W
            if (model.SmallShopsId.HasValue && model.SmallShopsId > 0)
            {
                var smallShop = smallShopsInfoRepository.GetEntity(model.SmallShopsId ?? 0);
                if (smallShop != null)
                {
                    model.SmallShopsName = smallShop.Name;
                }
            }


            // 2020-08-14 Add By:W End

            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            var erList = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            //查询图片
            List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
            if (dlist.Any())
            {
                #region 查询司导信息
                string siteIds = string.Join(",", dlist.Select(x => x.SiteId));
                var sitelist = guideCar_SiteRepository.GetGuideCarSiteList(new RB_GuideCar_Site_Extend() { SiteIds = siteIds });
                string guideIds = string.Join(",", dlist.Select(x => x.GuideId));
                var guidelist = guideCar_GuideRepository.GetGuideCarGuideList(new RB_GuideCar_Guide_Extend() { GuideIds = guideIds });
                string carids = string.Join(",", dlist.Select(x => x.CarId));
                var carlist = guideCar_CarRepository.GetGuideCarCarList(new RB_GuideCar_Car_Extend() { GuideCarIds = carids });
                string colorIds = string.Join(",", dlist.Select(x => x.CarColorId));
                var carcolorlist = guideCar_CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend() { CarColorIds = colorIds });
                #endregion
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsBindExpress = erList.Where(x => x.OrderDetailId == item.Id).Any() ? 1 : 2;

                    item.SiteName = sitelist.Where(x => x.ID == item.SiteId).FirstOrDefault()?.SiteName ?? "";
                    item.GuideName = guidelist.Where(x => x.ID == item.GuideId).FirstOrDefault()?.Name ?? "";
                    item.CarName = carlist.Where(x => x.ID == item.CarId).FirstOrDefault()?.Name ?? "";
                    item.CarColorName = carcolorlist.Where(x => x.ID == item.CarColorId).FirstOrDefault()?.ColorName ?? "";
                }
            }
            model.DetailList = dlist;
            //地址
            model.DistrictAddress = (destinationRepository.GetEntity(model.Province)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.City)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.District)?.Name ?? "");

            //获取返佣列表
            var ocList = goods_OrderCommissionRepository.GetListGroupByUser(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId }).OrderBy(x => x.Grade).ToList();
            if (ocList.Any())
            {
                var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (ocList.Where(x => x.Type == 3).Any())
                {
                    string gradeIds = string.Join(",", ocList.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = tenantId, MallBaseId = mallBaseId });
                }
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ocList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ocList)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";

                    if (item.Type == 1)
                    {
                        if (item.Grade == 0)
                        {
                            item.GradeDescription = "自购返利";
                        }
                        else if (item.Grade == 1)
                        {
                            item.GradeDescription = "一级佣金";
                        }
                        else if (item.Grade == 2)
                        {
                            item.GradeDescription = "二级佣金";
                        }
                        else if (item.Grade == 3)
                        {
                            item.GradeDescription = "三级佣金";
                        }
                    }
                    else if (item.Type == 3)
                    {
                        var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                        item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                    }
                }
            }

            var vipList = vip_BuyRepository.GetVipBuyList(new RB_Vip_Buy_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, ReOrderId = model.OrderId });
            List<RB_VipBuy_Commission_Extend> clist = new List<RB_VipBuy_Commission_Extend>();
            if (vipList.Any())
            {
                string vipIds = string.Join(",", vipList.Select(x => x.Id));
                clist = vipBuy_CommissionRepository.GetList(new RB_VipBuy_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderIds = vipIds });
                var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = tenantId, MallBaseId = mallBaseId });
                //获取用户
                var ulist = new List<RB_Member_User_Extend>();
                if (clist.Any())
                {
                    ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", clist.Select(x => x.UserId).Distinct()) });
                    foreach (var qitem in clist)
                    {
                        var fxmodel = FXList.Where(x => x.Id == qitem.Grade).FirstOrDefault();
                        qitem.GradeDescription = fxmodel.GradeName;
                        qitem.UserName = ulist.Where(x => x.Id == qitem.UserId).FirstOrDefault()?.Name ?? "";
                    }
                }
            }

            #region 推荐返佣
            List<RB_Goods_OrderIntroduction_Extend> OrderIntroduction = new List<RB_Goods_OrderIntroduction_Extend>();
            var introductList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (introductList.Any())
            {
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", introductList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ulist)
                {
                    decimal Commission = introductList.Where(x => x.UserId == item.Id).Sum(x => x.Commission ?? 0);
                    OrderIntroduction.Add(new RB_Goods_OrderIntroduction_Extend()
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        Commission = Commission
                    });
                }
            }
            #endregion

            #region 微店返佣
            List<RB_SmallShops_Commission_Extend> SmallShopsCommission = new List<RB_SmallShops_Commission_Extend>();
            var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (ssList.Any())
            {
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ssList.Select(x => x.UserId).Distinct()) });
                var slist = smallShops_InfoRepository.GetListForSingle(new RB_SmallShops_Info_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, UserIds = string.Join(",", ssList.Select(x => x.UserId).Distinct()) });
                foreach (var item in ulist)
                {
                    decimal Commission = ssList.Where(x => x.UserId == item.Id).Sum(x => x.Commission ?? 0);
                    var smodel = slist.Where(x => x.UserId == item.Id).FirstOrDefault();
                    SmallShopsCommission.Add(new RB_SmallShops_Commission_Extend()
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        Name = smodel?.Name ?? "",
                        Commission = Commission
                    });
                }
            }
            #endregion


            #region  优惠券 2020-08-25 Add By:W Start

            List<RB_Member_DiscountCoupon_Extend> memberCouponList = new List<RB_Member_DiscountCoupon_Extend>();
            if (!string.IsNullOrWhiteSpace(model.CouponsIds))
            {
                memberCouponList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, UseState = -1, Ids = model.CouponsIds });
            }
            #endregion 2020-08-25 Add By:W  End


            return ApiResult.Success("", new
            {
                model.OrderId,
                model.OrderStatus,
                OrderStatusName = model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                PaymentTime = model.PaymentTime.HasValue ? model.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = model.DeliveryTime.HasValue ? model.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = model.ReceivingTime.HasValue ? model.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = model.FinishTime.HasValue ? model.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.Remark,
                model.BuyerMessage,
                model.PreferPrice,
                model.Income,
                model.FreightMoney,
                CouponMoney = model.CouponMoney ?? 0,
                InsuranceMoney = (model.DetailList != null && model.DetailList.Any()) ? (model.DetailList.Sum(x => x.InsuranceMoney ?? 0)) : 0,
                IntegralMoney = (model.DetailList != null && model.DetailList.Any()) ? (model.DetailList.Sum(x => x.IntegralMoney ?? 0)) : 0,
                IntegralNumber = (model.DetailList != null && model.DetailList.Any()) ? (model.DetailList.Sum(x => x.IntegralNumber ?? 0)) : 0,
                MemberDiscountCouponList = memberCouponList.Select(y => new
                {
                    y.Name,
                    y.MinConsumePrice,
                    y.MaxDiscountsPrice,
                    y.UseType,
                    y.CouponType,
                    y.DiscountsPrice
                }),
                OrderInfo = new
                {
                    model.OrderNo,
                    model.MerchantsNo,
                    model.PaymentWay,
                    PaymentWayName = model.PaymentWay.GetEnumName(),
                    model.DeliveryMethod,
                    DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                    UserName = member_UserRepository.GetEntity(model.UserId)?.Name ?? "",
                    model.Consignee,
                    model.Mobile,
                    model.DistrictAddress,
                    model.ShoppingAddress,
                    model.DestinationAddress,
                    model.Country,
                    model.Province,
                    model.City,
                    model.District,
                    model.SmallShopsName,
                    model.SmallShopsId,
                },
                DistributionInfo = ocList.Select(x => new
                {
                    x.Id,
                    x.Grade,
                    x.GradeDescription,
                    x.UserName,
                    x.Mobile,
                    x.Commission
                }),
                VipCommissionInfo = clist.Select(x => new
                {
                    x.Id,
                    x.Grade,
                    x.GradeDescription,
                    x.UserName,
                    x.Commission
                }),
                OrderIntroductionInfo = OrderIntroduction.Select(x => new
                {
                    x.UserId,
                    x.UserName,
                    x.Commission
                }),
                SmallShopsCommissionInfo = SmallShopsCommission.Select(x => new
                {
                    x.UserId,
                    x.UserName,
                    SmallShopsName = x.Name,
                    x.Commission
                }),
                DetailList = model.DetailList.Select(x => new
                {
                    x.Id,
                    x.GoodsName,
                    x.CoverImage,
                    x.CoverImagePath,
                    x.Unit_Price,
                    x.Number,
                    x.Original_Price,
                    x.Final_Price,
                    x.IsBindExpress,
                    x.FreeShippingRemarks,
                    x.SmallShopsCostPrice,
                    CouponMoney = x.CouponMoney ?? 0,
                    InsuranceMoney = x.InsuranceMoney ?? 0,
                    IntegralMoney = x.IntegralMoney ?? 0,
                    IntegralNumber = x.IntegralNumber ?? 0,
                    x.SiteName,
                    x.SiteId,
                    x.GuideId,
                    x.GuideName,
                    x.CarId,
                    x.CarName,
                    x.CarColorId,
                    x.CarColorName,
                    x.CarNumber,
                    x.LineName,
                    TripSTime = x.TripSTime.HasValue ? x.TripSTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                    TripETime = x.TripETime.HasValue ? x.TripETime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                    x.CarType,
                    CarTypeName = x.CarType.GetEnumName(),
                    x.UseDay,
                    x.IsSpell,
                    x.CommentGiveIntegral
                })
            });
        }

        /// <summary>
        /// 获取快递对应的商品
        /// </summary>
        /// <param name="dlist"></param>
        /// <param name="erlist"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private List<RB_Goods_OrderDetail_Extend> GetGoodsListForExpress(List<RB_Goods_OrderDetail_Extend> dlist, List<RB_Goods_ExpressRelevance_Extend> erlist, int id)
        {
            var er2List = erlist.Where(x => x.OrderExpressId == id).ToList();
            return dlist.Where(x => er2List.Select(y => y.OrderDetailId).Contains(x.Id)).ToList();
        }

        #endregion

        #region 司导订单
        /// <summary>
        /// 司导订单确认
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public bool SetSDOrderConfirm(int orderId, int Type, int empId, Microsoft.AspNetCore.Http.IHttpContextAccessor _accessor)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (Type == 1)
            {
                keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.WaitReceiving);
                keyValues.Add(nameof(RB_Goods_Order.DeliveryTime), DateTime.Now);
            }
            else if (Type == 2)
            {
                keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Received);
                keyValues.Add(nameof(RB_Goods_Order.ReceivingTime), DateTime.Now);
            }
            else if (Type == 3)
            {
                keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Completed);
                keyValues.Add(nameof(RB_Goods_Order.FinishTime), DateTime.Now);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderRepository.Update(keyValues, wheres);
            var orderModel = goods_OrderRepository.GetEntity(orderId);
            if (flag && Type == 1)
            {
                //发送短信通知导游接单
                var list = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderId });
                int IsNormalServer = Convert.ToInt32(Config.IsNormalServer);//为正式才发送短信
                if (IsNormalServer == 1)
                {
                    foreach (var item in list)
                    {
                        if (item.GuideId > 0)
                        {
                            //查询导游信息
                            var guideModel = guideCar_GuideRepository.GetEntity(item.GuideId ?? 0);
                            var carModel = guideCar_CarRepository.GetEntity(item.CarId ?? 0);
                            if (guideModel != null && carModel != null && !string.IsNullOrEmpty(guideModel.Telephone))
                            {
                                string Telephone = guideModel.Telephone;
                                MobileCodeTypeEnum mobileCodeType = MobileCodeTypeEnum.GuideMsg;//导游通知
                                if (ValidateHepler.IsMobileNumber(Telephone))
                                {
                                    object PhoneMessage = new
                                    {
                                        orderModel.OrderNo,
                                        Name = orderModel.Consignee,
                                        orderModel.Mobile,
                                        TripDate = item.TripSTime.Value.ToString("yyyy-MM-dd HH:mm") + " " + ((item.UseDay ?? 0) == Convert.ToDecimal(0.5) ? "半" : Convert.ToInt32(item.UseDay ?? 0).ToString()) + "日",
                                        Address = orderModel.ShoppingAddress,
                                        item.Number
                                    };
                                    SMSService.SendMsg(Telephone, PhoneMessage, EnumHelper.GetEnumName(mobileCodeType));
                                }

                                #region 给客人通知
                                try
                                {
                                    if (ValidateHepler.IsMobileNumber(orderModel.Mobile))
                                    {
                                        MobileCodeTypeEnum mobileCodeType1 = MobileCodeTypeEnum.SDClientMsg;//客人通知
                                        object PhoneMessage = new
                                        {
                                            orderModel.OrderNo,
                                            TripTime = item.TripSTime.Value.ToString("yyyy-MM-dd HH:mm") + " " + ((item.UseDay ?? 0) == Convert.ToDecimal(0.5) ? "半" : Convert.ToInt32(item.UseDay ?? 0).ToString()) + "日",
                                            guideModel.Name,
                                            Tel = Telephone
                                        };
                                        SMSService.SendMsg(orderModel.Mobile, PhoneMessage, EnumHelper.GetEnumName(mobileCodeType1));
                                    }
                                }
                                catch (Exception)
                                {
                                }
                                #endregion
                            }
                        }
                    }
                }
            }
            else if (flag && Type == 3)
            {
                //返佣
                bool IsUpdateCommission = true;
                int mallBaseId = orderModel.MallBaseId;
                int tenantId = orderModel.TenantId;
                var mallModel = mallBaseRepository.GetEntity(mallBaseId);
                if (mallModel != null && mallModel.AfterTime > 0)
                {
                    var OrderM = goods_OrderRepository.GetEntity(orderModel.OrderId);
                    if (OrderM != null && OrderM.ReceivingTime.HasValue && OrderM.ReceivingTime.Value.AddDays(mallModel.AfterTime) > DateTime.Now)
                    {
                        IsUpdateCommission = false;
                    }
                }
                if (IsUpdateCommission)
                {
                    //更新返佣为已返佣
                    var ocList = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                    if (ocList.Where(x => x.CommissionState == 1).Any())
                    {
                        foreach (var item in ocList.Where(x => x.CommissionState == 1))
                        {
                            //查询是否有申请退款
                            var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                            if (!afterSaleList.Any())
                            {
                                //获取分销商信息
                                var disInfo = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = item.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                                if (disInfo != null && disInfo.AuditStatus == DistributorAuditStatusEnum.Audited)
                                {
                                    //更新分销商佣金
                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Distributor_Info_Extend.TotalCommission),(disInfo.TotalCommission??0)+(item.Commission??0)},
                                        { nameof(RB_Distributor_Info_Extend.CommissionWithdrawal),(disInfo.CommissionWithdrawal??0)+(item.Commission??0)},
                                    };
                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disInfo.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    bool flag1 = distributor_InfoRepository.Update(keyValues2, wheres2);
                                    if (flag1)
                                    {
                                        //更新返佣状态
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_OrderCommission_Extend.CommissionState),2},
                                            { nameof(RB_Goods_OrderCommission_Extend.UpdateDate),DateTime.Now},
                                        };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                  FiledValue=item.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goods_OrderCommissionRepository.Update(keyValues1, wheres1);
                                    }
                                }
                            }
                        }
                    }
                    //更新推荐供应商返佣
                    var oiList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                    if (oiList.Any())
                    {
                        foreach (var item in oiList)
                        {
                            //查询是否有申请退款
                            var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                            if (!afterSaleList.Any())
                            {
                                //更新返佣状态
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderIntroduction_Extend.CommissionState),2},
                                        { nameof(RB_Goods_OrderIntroduction_Extend.UpdateDate),DateTime.Now},
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_Goods_OrderIntroduction_Extend.Id),
                                                FiledValue=item.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                goods_OrderIntroductionRepository.Update(keyValues1, wheres1);
                            }
                        }
                    }

                    //更新微店返佣
                    var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                    if (ssList.Where(x => x.CommissionState == 1).Any())
                    {
                        //验证是否是自动结算
                        var ssbaseModel = microShop_BasicsRepository.GetMicroShopBasicsList(new Model.Entity.BaseSetUp.RB_MicroShop_Basics() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                        if (("," + (ssbaseModel?.SettlementType ?? "") + ",").Contains("," + ((int)DistrbutorWithdrawWayEnum.ZDXJ).ToString() + ","))
                        {
                            var ssmodel = ssList.FirstOrDefault();
                            //获取微店信息
                            var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                            if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                            {
                                //总佣金
                                decimal TotalCommission = 0, OldCommission = 0;
                                foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                {
                                    var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                    if (!afterSaleList.Any())
                                    {
                                        TotalCommission += (item.Commission ?? 0);
                                    }
                                }
                                #region 看微店佣金是否是负数  是的话  需要走总佣金里减去
                                OldCommission = TotalCommission;
                                if ((smallModel.Commission ?? 0) < 0)
                                {
                                    TotalCommission += (smallModel?.Commission ?? 0);
                                }
                                #endregion
                                if (TotalCommission > 0)
                                {
                                    decimal RemitMoney = TotalCommission, fee = 0;
                                    var feeValue = ssbaseModel?.WithdrawalFree ?? 0;
                                    if (feeValue > 0)
                                    {
                                        fee = Math.Round(TotalCommission * (feeValue) / 100, 2, MidpointRounding.AwayFromZero);
                                        RemitMoney = TotalCommission - fee;
                                    }
                                    var minModel = miniProgramRepository.GetEntity(mallBaseId);
                                    var umodel = member_UserRepository.GetEntity(ssmodel.UserId);
                                    //打款
                                    Random R = new Random();
                                    int Rstr = R.Next(111, 999);
                                    string OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                                    int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
                                    var flagpay = false;
                                    if (IsNormalServer == 1)
                                    {
                                        flagpay = Common.Pay.PayUtilWeiXin.GetTransfersOrder(OrderNum, RemitMoney, (ssmodel.UserId ?? 0).ToString(), umodel.OpenId, minModel.WeChatPayCertificateUrl, minModel.WeChatApiSecret, minModel.MiniAppId, _accessor);
                                    }
                                    if (flagpay)
                                    {
                                        //更新状态
                                        foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                        {
                                            if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                            {
                                                //更新返佣状态
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                        { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                        { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                    };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                FiledValue=item.Id,
                                                                OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                            }
                                        }
                                        //写入已提现数据
                                        smallShops_RemitRepository.Insert(new Model.Entity.User.RB_SmallShops_Remit()
                                        {
                                            Id = 0,
                                            AccountName = "",
                                            AccountNumber = "",
                                            AppliedMoney = TotalCommission,
                                            AuditDate = DateTime.Now,
                                            AuditRemark = "",
                                            AuditStatus = DistributorRemitAuditStatusEnum.HaveMoney,
                                            BankName = "",
                                            CreateDate = DateTime.Now,
                                            Fee = fee,
                                            FinanceId = 0,
                                            MallBaseId = mallBaseId,
                                            OrderNum = OrderNum,
                                            RejectDate = null,
                                            RejectRemark = "",
                                            RemitDate = DateTime.Now,
                                            RemitMoney = RemitMoney,
                                            RemitRemark = "自动结算打款",
                                            ReOrderIds = "[" + (orderModel.OrderId).ToString() + "]",
                                            ReOrderNos = "\"" + orderModel.OrderNo + "\"：" + RemitMoney + "元",
                                            TenantId = tenantId,
                                            UserId = ssmodel.UserId,
                                            WithdrawalWay = DistrbutorWithdrawWayEnum.ZDXJ
                                        });
                                    }
                                    else
                                    {
                                        //更新状态
                                        foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                        {
                                            if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                            {
                                                //更新返佣状态
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                    { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                    { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                    { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                            FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                            FiledValue=item.Id,
                                                            OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                            }
                                        }
                                        //写入已提现数据
                                        smallShops_RemitRepository.Insert(new Model.Entity.User.RB_SmallShops_Remit()
                                        {
                                            Id = 0,
                                            AccountName = "",
                                            AccountNumber = "",
                                            AppliedMoney = TotalCommission,
                                            AuditDate = DateTime.Now,
                                            AuditRemark = "自动现结失败，变更为手动打款",
                                            AuditStatus = DistributorRemitAuditStatusEnum.ToPlayWith,
                                            BankName = "",
                                            CreateDate = DateTime.Now,
                                            Fee = fee,
                                            FinanceId = 0,
                                            MallBaseId = mallBaseId,
                                            OrderNum = OrderNum,
                                            RejectDate = null,
                                            RejectRemark = "",
                                            RemitDate = DateTime.Now,
                                            RemitMoney = RemitMoney,
                                            RemitRemark = "",
                                            ReOrderIds = "[" + (orderModel.OrderId).ToString() + "]",
                                            ReOrderNos = "\"" + orderModel.OrderNo + "\"：" + RemitMoney + "元",
                                            TenantId = tenantId,
                                            UserId = ssmodel.UserId,
                                            WithdrawalWay = DistrbutorWithdrawWayEnum.ZDDK
                                        });
                                    }
                                    //更新微店佣金等于0                                            
                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                            { nameof(RB_SmallShops_Info_Extend.Commission), TotalCommission}
                                        };
                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                    bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                }
                                else if (TotalCommission < 0)
                                {
                                    //存在微店佣金里  继续负数累加                                      
                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                            { nameof(RB_SmallShops_Info_Extend.Commission),TotalCommission},
                                        };
                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                    bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                }
                            }
                        }
                        else
                        {
                            var ssmodel = ssList.FirstOrDefault();
                            //获取微店信息
                            var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                            foreach (var item in ssList.Where(x => x.CommissionState == 1))
                            {
                                //查询是否有申请退款
                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                if (!afterSaleList.Any())
                                {
                                    if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                    {
                                        //更新微店佣金
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0)+(item.Commission??0)},
                                            { nameof(RB_SmallShops_Info_Extend.Commission),(smallModel.Commission??0)+(item.Commission??0)},
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                        if (flag1)
                                        {
                                            //更新返佣状态
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                            };
                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                        FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                        FiledValue=item.Id,
                                                        OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                            smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //积分赠送
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderModel.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
                if (dlist.Any())
                {
                    int IntegralGoodsPresent = 0;
                    foreach (var item in dlist)
                    {
                        if (item.IntegralGoodsPresent > 0)
                        {
                            IntegralGoodsPresent += (item.IntegralGoodsPresent ?? 0);
                        }
                    }
                    if (IntegralGoodsPresent > 0)
                    {
                        //保存积分赠送
                        var umodel = member_UserRepository.GetEntity(orderModel.UserId);
                        //用户订单数增加
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User_Extend.Integral), (umodel.Integral ?? 0)+IntegralGoodsPresent }
                            };
                        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);
                        member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                        {
                            Id = 0,
                            CreateDate = DateTime.Now,
                            Description = "订单购买赠送积分，订单号：" + orderModel.OrderNo,
                            Image = 0,
                            Integral = IntegralGoodsPresent,
                            MallBaseId = orderModel.MallBaseId,
                            PlatformType = orderModel.OrderSource,
                            Remarks = "",
                            TenantId = orderModel.TenantId,
                            Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                            UserId = orderModel.UserId,
                            OrderId = orderModel.OrderId
                        });
                    }
                }
            }
            if (flag)
            {
                string content = "";
                if (Type == 1)
                {
                    content = "empId:" + empId + "司导确认订单";
                }
                else if (Type == 2)
                {
                    content = "empId:" + empId + "司导设置订单出行";
                }
                else if (Type == 3)
                {
                    content = "empId:" + empId + "司导设置订单完成";
                }
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = content,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = orderModel.MallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = orderModel.TenantId,
                    Type = 1
                });
            }
            return flag;
        }

        /// <summary>
        /// 验证司导订单是否可以取消
        /// </summary>
        /// <param name="orderModel"></param>
        /// <returns></returns>
        public string ValidateSDOrderCanCancel(RB_Goods_Order_Extend orderModel)
        {
            var gbmodel = guideCar_BaseRepository.GetList(new Model.Extend.GuideCar.RB_GuideCar_Base_Extend() { TenantId = orderModel.TenantId, MallBaseId = orderModel.MallBaseId }).FirstOrDefault();
            if (gbmodel == null || gbmodel.CancelHour <= 0)
            {
                return "";
            }
            var detailList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderModel.OrderId });
            foreach (var item in detailList)
            {
                if (Convert.ToDateTime(item.TripSTime.Value.ToString("yyyy-MM-dd")).AddHours(-gbmodel.CancelHour) < DateTime.Now)
                {
                    return "订单取消超时，需出发日提前" + gbmodel.CancelHour + "小时";
                }
            }
            return "";
        }
        #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_CommentTemplate_Extend> GetGoodsCommentTemplatePageList(int pageIndex, int pageSize, out long count, RB_Goods_CommentTemplate_Extend demodel)
        {
            var list = goods_CommentTemplateRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            return list;
        }

        /// <summary>
        /// 新增修改评论模板
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGoodsCommentTemplateInfo(RB_Goods_CommentTemplate_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_CommentTemplate.Name),demodel.Name},
                    { nameof(RB_Goods_CommentTemplate.Content),demodel.Content},
                    { nameof(RB_Goods_CommentTemplate.CommentGrade),demodel.CommentGrade},
                    { nameof(RB_Goods_CommentTemplate.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                          FiledName=nameof(RB_Goods_CommentTemplate.Id),
                           FiledValue=demodel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                return goods_CommentTemplateRepository.Update(keyValues, wheres);
            }
            else
            {
                return goods_CommentTemplateRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除评论模板
        /// </summary>
        /// <param name="templateId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelGoodsCommentTemplateInfo(int templateId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_CommentTemplate.Status),1},
                { nameof(RB_Goods_CommentTemplate.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_CommentTemplate.Id),
                        FiledValue=templateId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_CommentTemplate.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_CommentTemplate.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goods_CommentTemplateRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取订单评论分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Comment_Extend> GetGoodsCommentPageList(int pageIndex, int pageSize, out long count, RB_Goods_Comment_Extend demodel)
        {
            var list = goods_CommentRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    //商品图片
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                    //评论图片
                    item.CommentImgList = new List<string>();
                    if (!string.IsNullOrEmpty(item.CommentImage))
                    {
                        item.CommentImgList = JsonConvert.DeserializeObject<List<string>>(item.CommentImage);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取待评论商品列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetAppletGoodsWaitCommentPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderDetail_Extend demodel)
        {
            var list = goods_OrderDetailRepository.GetAppletGoodsWaitCommentPageList(pageIndex, pageSize, out count, demodel);
            foreach (var item in list)
            {
                item.SpecificationList = new List<string>();
                if (!string.IsNullOrEmpty(item.Specification) && item.Specification != "[]")
                {
                    item.SpecificationList = JsonConvert.DeserializeObject<List<string>>(item.Specification);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取订单评价列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Comment_Extend> GetAppletGoodsCommentPageList(int pageIndex, int pageSize, out long count, RB_Goods_Comment_Extend demodel)
        {
            var list = goods_CommentRepository.GetAppletPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                List<RB_Member_User_Extend> userList = new List<RB_Member_User_Extend>();
                if (list.Where(x => x.UserId > 0).Any())
                {
                    string uids = string.Join(",", list.Where(x => x.UserId > 0).Select(x => x.UserId ?? 0));
                    userList = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = uids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    //评论图片
                    item.CommentImgList = new List<string>();
                    if (!string.IsNullOrEmpty(item.CommentImage))
                    {
                        item.CommentImgList = JsonConvert.DeserializeObject<List<string>>(item.CommentImage);
                    }
                    if (item.UserId > 0)
                    {
                        item.UserPhotoPath = userList.Where(x => x.Id == item.UserId).FirstOrDefault()?.Photo ?? "";
                    }
                    if (item.UserId == 0 && item.UserPhoto > 0)
                    {
                        item.UserPhotoPath = material_InfoRepository.GetEntity(item.UserPhoto)?.Path ?? "";
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 管理新增评论
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGoodsCommentInfo(RB_Goods_Comment_Extend demodel)
        {
            var omodel = new RB_Goods_Order();
            int OrderId = 0;
            var dmodel = new RB_Goods_OrderDetail();
            if (demodel.OrderDetailId > 0)
            {
                dmodel = goods_OrderDetailRepository.GetEntity(demodel.OrderDetailId);
                if (dmodel == null) { return false; }
                OrderId = dmodel.OrderId ?? 0;
                if (dmodel.IsComment == 1) { return false; }
                //omodel = goods_OrderRepository.GetEntity(OrderId);
                //if (omodel == null) { return false; }
                //if (omodel.OrderStatus != OrderStatusEnum.Received) { return false; }
            }
            bool flag = goods_CommentRepository.Insert(demodel) > 0;
            if (flag)
            {
                if (demodel.OrderDetailId > 0)
                {

                    //if (dmodel.CommentGiveIntegral > 0 && demodel.UserId > 0)//评论返积分大于0，赠送积分
                    //{
                    //    Model.Entity.User.RB_Member_Integral memberIntegralModel = new Model.Entity.User.RB_Member_Integral
                    //    {
                    //        UserId = demodel.UserId,
                    //        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                    //        PlatformType = demodel.PlatformSource,
                    //        Integral = dmodel.CommentGiveIntegral,
                    //        Description = "评论赠送" + dmodel.CommentGiveIntegral + "积分",
                    //        TenantId = demodel.TenantId,
                    //        MallBaseId = demodel.MallBaseId,
                    //        Remarks = "评论商品" + dmodel.GoodsName + "赠送" + dmodel.CommentGiveIntegral + "积分",
                    //        CreateDate = demodel.CreateDate,
                    //        OrderId = dmodel.OrderId
                    //    };
                    //    member_IntegralRepository.Insert(memberIntegralModel);
                    //}


                    //更新订单商品为已评价
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Goods_OrderDetail.IsComment),1}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderDetail.Id),
                              FiledValue=demodel.OrderDetailId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    goods_OrderDetailRepository.Update(keyValues, wheres);

                    #region 更新课程评分
                    var goodsModel = goodsRepository.GetEntity(demodel.GoodsId ?? 0);
                    if (goodsModel != null && goodsModel.GoodsClassify == 2)
                    {
                        var gcsModel = goods_CommentRepository.GetGoodsCommentScore(demodel.GoodsId ?? 0);
                        if (gcsModel != null)
                        {
                            decimal score = 0;
                            if (gcsModel.CommentNum > 0)
                            {
                                score = Math.Round(Convert.ToDecimal(gcsModel.CommentScore ?? 0) / gcsModel.CommentNum, 2, MidpointRounding.AwayFromZero);
                            }
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Goods.CourseScore),score}
                        };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods.Id),
                                  FiledValue=demodel.GoodsId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                            goodsRepository.Update(keyValues1, wheres1);
                        }
                    }
                    #endregion

                    if (OrderId < 0)
                    {
                        var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = OrderId, IsComment = 2, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        if (!dlist.Any())
                        {
                            //更新订单为已完成
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Goods_Order.OrderStatus),OrderStatusEnum.Completed}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Goods_Order.OrderId),
                                      FiledValue=OrderId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderRepository.Update(keyValues1, wheres1);

                            //更新返佣为已返佣
                            var ocList = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderId = OrderId });
                            if (ocList.Any())
                            {
                                foreach (var item in ocList)
                                {
                                    //查询是否有申请退款
                                    var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId });
                                    if (!afterSaleList.Any())
                                    {
                                        //获取分销商信息
                                        var disInfo = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = item.UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                                        if (disInfo != null && disInfo.AuditStatus == DistributorAuditStatusEnum.Audited)
                                        {
                                            //更新分销商佣金
                                            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                { nameof(RB_Distributor_Info_Extend.TotalCommission),(disInfo.TotalCommission??0)+(item.Commission??0)},
                                                { nameof(RB_Distributor_Info_Extend.CommissionWithdrawal),(disInfo.CommissionWithdrawal??0)+(item.Commission??0)},
                                            };
                                            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                     FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                                      FiledValue=disInfo.Id,
                                                       OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                            bool flag1 = distributor_InfoRepository.Update(keyValues2, wheres2);
                                            if (flag1)
                                            {
                                                //更新返佣状态
                                                Dictionary<string, object> keyValues3 = new Dictionary<string, object>() {
                                                    { nameof(RB_Goods_OrderCommission_Extend.CommissionState),2},
                                                    { nameof(RB_Goods_OrderCommission_Extend.UpdateDate),DateTime.Now},
                                                };
                                                List<WhereHelper> wheres3 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                         FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                          FiledValue=item.Id,
                                                           OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                goods_OrderCommissionRepository.Update(keyValues3, wheres3);
                                            }
                                        }
                                    }
                                }
                            }

                            //积分赠送
                            var d2list = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = omodel.OrderId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                            if (d2list.Any())
                            {
                                int IntegralGoodsPresent = 0;
                                foreach (var item in d2list)
                                {
                                    if (item.IntegralGoodsPresent > 0)
                                    {
                                        IntegralGoodsPresent += (item.IntegralGoodsPresent ?? 0);
                                    }
                                }
                                if (IntegralGoodsPresent > 0)
                                {
                                    //保存积分赠送
                                    var umodel = member_UserRepository.GetEntity(demodel.UserId);
                                    //用户订单数增加
                                    Dictionary<string, object> keyValues12 = new Dictionary<string, object>() {
                                        { nameof(RB_Member_User_Extend.Integral), (umodel.Integral ?? 0)+IntegralGoodsPresent }
                                    };
                                    List<WhereHelper> wheres12 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Member_User_Extend.Id),
                                              FiledValue=umodel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    member_UserRepository.Update(keyValues12, wheres12);
                                    member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                                    {
                                        Id = 0,
                                        CreateDate = DateTime.Now,
                                        Description = "订单购买赠送积分，订单号：" + omodel.OrderNo,
                                        Image = 0,
                                        Integral = IntegralGoodsPresent,
                                        MallBaseId = demodel.MallBaseId,
                                        PlatformType = omodel.OrderSource,
                                        Remarks = "",
                                        TenantId = demodel.TenantId,
                                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                        UserId = demodel.UserId,
                                        OrderId = omodel.OrderId
                                    });
                                }
                            }
                        }
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="commentIds"></param>
        /// <param name="type"></param>
        /// <param name="content"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetGoodsCommentBatch(string commentIds, int type, string content, int tenantId, int mallBaseId)
        {
            //1批量回复   2批量隐藏  3批量显示  4批量置顶  5取消置顶  6批量删除
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (type == 1)
            { //回复
                keyValues.Add(nameof(RB_Goods_Comment.Reply), content);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 2)
            { //影藏
                keyValues.Add(nameof(RB_Goods_Comment.Is_Show), 2);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 3)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Is_Show), 1);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 4)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Is_Top), 1);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 5)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Is_Top), 2);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 6)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Status), 1);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else
            {
                return false;
            }

            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_Comment.Id),
                        FiledValue=commentIds,
                        OperatorEnum=OperatorEnum.IN
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_Comment.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_Comment.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goods_CommentRepository.Update(keyValues, wheres);
        }




        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="commentIds"></param>
        /// <param name="type"></param>
        /// <param name="content"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetCommentBatchByOrderDetailId(string orderDetailIds, int type, string content, int tenantId, int mallBaseId)
        {
            //1批量回复   2批量隐藏  3批量显示  4批量置顶  5取消置顶  6批量删除
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (type == 1)
            { //回复
                keyValues.Add(nameof(RB_Goods_Comment.Reply), content);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 2)
            { //影藏
                keyValues.Add(nameof(RB_Goods_Comment.Is_Show), 2);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 3)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Is_Show), 1);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 4)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Is_Top), 1);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 5)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Is_Top), 2);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else if (type == 6)
            {
                keyValues.Add(nameof(RB_Goods_Comment.Status), 1);
                keyValues.Add(nameof(RB_Goods_Comment.UpdateDate), DateTime.Now);
            }
            else
            {
                return false;
            }

            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_Comment.OrderDetailId),
                        FiledValue=orderDetailIds,
                        OperatorEnum=OperatorEnum.IN
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_Comment.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods_Comment.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goods_CommentRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取商品评论统计
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletGoodsCommentStatistics(int goodsId, int tenantId, int mallBaseId)
        {
            var list = EnumHelper.GetEnumList(typeof(GoodsCommentTypeEnum));
            var clist = goods_CommentRepository.GetAppletGoodsCommentStatistics(goodsId, tenantId, mallBaseId);
            List<object> RList = new List<object>();
            foreach (var item in list)
            {
                var cmodel = clist.Where(x => (int)x.CommentGrade == Convert.ToInt32(item.Value)).FirstOrDefault();
                RList.Add(new
                {
                    Id = Convert.ToInt32(item.Value),
                    Name = item.Key,
                    Count = cmodel?.CommentNum ?? 0
                });
            }
            return ApiResult.Success("", new
            {
                TotalNum = clist.Sum(x => x.CommentNum),
                List = RList
            });
        }

        #endregion

        #region 订单批量发货

        /// <summary>
        /// 订单批量发货
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="expressId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string SetOrderBatchSendGoods(string path_server, int expressId, int tenantId, int mallBaseId)
        {
            if (!System.IO.File.Exists(path_server))
            {
                return "导入文件已删除，请刷新后重新导入再试";
            }
            //处理文件内容读取
            List<RB_Goods_OrderExpress_Extend> list = DataHelper.SendGoodsBetchDataHelper.ImportClaimData(path_server);
            list = list.Where(x => !string.IsNullOrWhiteSpace(x.OrderNo)).ToList();
            if (list.Any())
            {
                if (list.Count() != list.Select(x => x.OrderNo).Distinct().Count())
                {
                    return "订单号有重复，请核实后再试";
                }
                string orderNos = string.Join(",", list.Select(x => "'" + x.OrderNo + "'"));
                var orderList = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { orderNos = orderNos, TenantId = tenantId, MallBaseId = mallBaseId });
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                var detailList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderIds = orderIds, TenantId = tenantId, MallBaseId = mallBaseId });
                var erList = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { OrderIds = orderIds, TenantId = tenantId, MallBaseId = mallBaseId });

                foreach (var item in list)
                {
                    var orderModel = orderList.Where(x => x.OrderNo == item.OrderNo).FirstOrDefault();
                    if (orderModel == null)
                    {
                        return "订单号：" + item.OrderNo + " 不存在";
                    }
                    if (orderModel.OrderStatus != OrderStatusEnum.WaitSendGoods)
                    {
                        return "订单号：" + item.OrderNo + " 状态不对";
                    }
                }

                var trans = goods_ExpressRelevanceRepository.DbTransaction;
                DateTime dt = DateTime.Now;
                try
                {
                    foreach (var item in list)
                    {
                        var orderModel = orderList.Where(x => x.OrderNo == item.OrderNo).FirstOrDefault();
                        var dList = detailList.Where(x => x.OrderId == orderModel.OrderId).ToList();
                        var er2List = erList.Where(x => x.OrderId == orderModel.OrderId).ToList();
                        //创建关联表
                        var ddList = dList.Where(x => !er2List.Select(y => y.OrderDetailId).Contains(x.Id)).ToList();
                        if (ddList.Any())
                        {
                            int eid = goods_OrderExpressRepository.Insert(new RB_Goods_OrderExpress()
                            {
                                Id = 0,
                                AfterSaleOrderId = 0,
                                CreateDate = dt,
                                ExpressId = expressId,
                                ExpressNumber = item.ExpressNumber,
                                MallBaseId = mallBaseId,
                                PostCode = "",
                                Remark = "批量发货",
                                TenantId = tenantId,
                                Type = 1,
                                UpdateDate = dt
                            }, trans);
                            foreach (var qitem in ddList)
                            {
                                goods_ExpressRelevanceRepository.Insert(new RB_Goods_ExpressRelevance()
                                {
                                    CreateDate = dt,
                                    Id = 0,
                                    MallBaseId = mallBaseId,
                                    OrderDetailId = qitem.Id,
                                    OrderExpressId = eid,
                                    OrderId = orderModel.OrderId,
                                    UpdateDate = dt,
                                    TenantId = tenantId
                                }, trans);
                            }
                            Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                            {
                                Content = "新增快递信息",
                                CreateDate = dt,
                                Id = 0,
                                MallBaseId = mallBaseId,
                                SourceId = orderModel.OrderId,
                                TenantId = tenantId,
                                Type = 1
                            }));
                            //修改订单状态为已发货
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Goods_Order.OrderStatus),OrderStatusEnum.WaitReceiving}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Goods_Order.OrderId),
                                      FiledValue=orderModel.OrderId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderRepository.Update(keyValues, wheres, trans);
                            Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                            {
                                Content = "修改订单状态为：待收货",
                                CreateDate = dt,
                                Id = 0,
                                MallBaseId = mallBaseId,
                                SourceId = orderModel.OrderId,
                                TenantId = tenantId,
                                Type = 1
                            }));
                        }
                    }
                    goods_ExpressRelevanceRepository.DBSession.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetOrderBatchSendGoods");
                    goods_ExpressRelevanceRepository.DBSession.Rollback();
                    System.IO.File.Delete(path_server);
                    return "出错啦，请联系管理员";
                }
            }
            System.IO.File.Delete(path_server);
            return "";
        }
        #endregion

        #region 查询物流

        /// <summary>
        /// 获取物流信息
        /// </summary>
        /// <param name="expressId"></param>
        /// <returns></returns>
        public Model.Entity.BaseSetUp.RB_Logistics_Express GerExpressModel(int expressId)
        {
            return logistics_ExpressRepository.GetEntity(expressId);
        }

        /// <summary>
        /// 查询物料信息
        /// </summary>
        /// <param name="expressCode"></param>
        /// <param name="expressNumber"></param>
        /// <returns></returns>
        public string GetOrderExpressInfo(string expressCode, string expressNumber)
        {
            return new KdApiSearchDemo().getOrderTracesByJson(expressCode, expressNumber);
        }

        #endregion

        #region 赞羊订单导入

        /// <summary>
        /// 订单导入
        /// </summary>
        /// <param name="path_server"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string SetGoodsOrderBatchImport(string path_server, int tenantId, int mallBaseId)
        {
            if (!System.IO.File.Exists(path_server))
            {
                return "导入文件已删除，请刷新后重新导入再试";
            }
            int FileType = path_server.Contains(".csv") ? 1 : 2;//1 赞羊导入   2 和平导入
            if (FileType != 1)
            {
                return "暂不支持该格式导入";
            }
            //处理文件内容读取
            List<RB_Goods_Order_Extend> list = DataHelper.GoodsOrderBetchDataHelper.ImportClaimData(path_server);
            list = list.Where(x => !string.IsNullOrWhiteSpace(x.OrderNo)).ToList();
            if (list.Any())
            {
                List<string> OrderNoList = new List<string>();
                List<string> CityList = new List<string>();
                foreach (var item in list)
                {
                    item.OrderNo = item.OrderNo.Replace("\t", "");
                    OrderNoList.Add(item.OrderNo);
                    #region 验证数据

                    if (string.IsNullOrEmpty(item.PlatformNameImport))
                    {
                        return "订单所属平台为空，订单号：" + item.OrderNo;
                    }
                    if (string.IsNullOrEmpty(item.UserName))
                    {
                        return "订单下单用户为空，订单号：" + item.OrderNo;
                    }
                    if (string.IsNullOrEmpty(item.GoodsName))
                    {
                        return "订单商品名称为空，订单号：" + item.OrderNo;
                    }
                    if (string.IsNullOrEmpty(item.SpecificationImport))
                    {
                        return "订单规格为空，订单号：" + item.OrderNo;
                    }
                    if ((item.OrderNum ?? 0) <= 0)
                    {
                        return "订单数量为空，订单号：" + item.OrderNo;
                    }
                    if (string.IsNullOrEmpty(item.Consignee))
                    {
                        return "订单收件人为空，订单号：" + item.OrderNo;
                    }
                    if (string.IsNullOrEmpty(item.Mobile))
                    {
                        return "订单收件人电话为空，订单号：" + item.OrderNo;
                    }
                    if (string.IsNullOrEmpty(item.DistrictAddress))
                    {
                        return "订单收件人地址为空，订单号：" + item.OrderNo;
                    }
                    if ((item.Income ?? 0) < 0)
                    {
                        return "订单实际付款为空，订单号：" + item.OrderNo;
                    }
                    if (string.IsNullOrEmpty(item.OrderStatusImport))
                    {
                        return "订单状态为空，订单号：" + item.OrderNo;
                    }
                    #endregion

                    #region 处理地区
                    if (!string.IsNullOrEmpty(item.DistrictAddress))
                    {
                        string[] arr = item.DistrictAddress.Split(' ');
                        if (arr.Length < 4)
                        {
                            return "收件人地址不正确，订单号：" + item.OrderNo;
                        }

                        CityList.Add("'" + arr[0].Replace("省", "") + "'");
                        CityList.Add("'" + arr[1].Replace("市", "") + "'");
                        CityList.Add("'" + arr[2] + "'");
                        item.PName = arr[0].Replace("省", "");
                        item.CName = arr[1].Replace("市", "");
                        item.DName = arr[2];

                        for (int i = 3; i < arr.Length; i++)
                        {
                            item.ShoppingAddress += arr[i] + " ";
                        }
                    }
                    #endregion

                    #region 去除/t

                    item.GoodsName = item.GoodsName.Replace("\t", "");
                    item.PlatformNameImport = item.PlatformNameImport.Replace("\t", "");
                    item.OrderStatusImport = item.OrderStatusImport.Replace("\t", "");
                    item.PaymentWayImport = item.PaymentWayImport.Replace("\t", "");
                    item.SpecificationImport = item.SpecificationImport.Replace("\t", "");
                    #endregion
                }

                if (OrderNoList.Any())
                {
                    //验证订单号是否有重复
                    var goList = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { orderNos = string.Join(",", OrderNoList.Select(x => "'" + x + "'")), TenantId = tenantId, MallBaseId = mallBaseId });
                    if (goList.Any())
                    {
                        string msg = string.Join(",", goList.Select(x => x.OrderNo));
                        return "订单号有重复，订单号：" + msg;
                    }
                }

                #region 初始化数据
                //平台
                var PlatformList = EnumHelper.GetEnumList(typeof(UserSourceEnum));
                //订单状态
                var OrderStatusList = EnumHelper.GetEnumList(typeof(OrderStatusEnum));
                //支付方式
                var PayWayList = EnumHelper.GetEnumList(typeof(OrderPaymentTypeEnum));

                //根据用户名  查询用户id
                //string UserNameStr = string.Join(",", list.Select(x => "'" + x.UserName + "'").Distinct());
                //var userList = member_UserRepository.GetList(new RB_Member_User_Extend() { UserNameStr = UserNameStr, TenantId = tenantId, MallBaseId = mallBaseId });
                //根据商品名  查询商品id
                string GoodsNameStr = string.Join(",", list.Select(x => "'" + x.GoodsName + "'").Distinct());
                var goodsList = goodsRepository.GetSingleList(new RB_Goods_Extend() { GoodsNameStr = GoodsNameStr, TenantId = tenantId, MallBaseId = mallBaseId });
                //根据城市名  查询城市id
                string CityStr = string.Join(",", CityList);
                var cityList = destinationRepository.GetListExt(new Model.Extend.BaseSetUp.RB_Destination_Extend() { NameStr = CityStr });
                #endregion

                //根据订单号分组
                List<RB_Goods_Order_Extend> OrderList = new List<RB_Goods_Order_Extend>();
                OrderNoList = OrderNoList.Distinct().ToList();
                foreach (var OrderNo in OrderNoList)
                {
                    var DetailList = list.Where(x => x.OrderNo == OrderNo).ToList();
                    var OrderModel1 = DetailList.FirstOrDefault();
                    var OrderModel = new RB_Goods_Order_Extend()
                    {
                        OrderId = OrderModel1.OrderId,
                        OrderNo = OrderModel1.OrderNo,
                        MerchantsNo = OrderModel1.MerchantsNo,
                        UserId = OrderModel1.UserId,
                        OrderSource = OrderModel1.OrderSource,
                        PaymentWay = OrderModel1.PaymentWay,
                        PreferPrice = OrderModel1.PreferPrice,
                        Income = OrderModel1.Income,
                        FreightMoney = OrderModel1.FreightMoney,
                        Fee = OrderModel1.Fee,
                        Refund = OrderModel1.Refund,
                        CouponMoney = OrderModel1.CouponMoney,
                        CouponsIds = OrderModel1.CouponsIds,
                        DeliveryMethod = OrderModel1.DeliveryMethod,
                        Consignee = OrderModel1.Consignee,
                        Mobile = OrderModel1.Mobile,
                        Country = OrderModel1.Country,
                        Province = OrderModel1.Province,
                        City = OrderModel1.City,
                        District = OrderModel1.District,
                        ShoppingAddress = OrderModel1.ShoppingAddress,
                        BuyerMessage = OrderModel1.BuyerMessage,
                        Remark = OrderModel1.Remark,
                        OrderStatus = OrderModel1.OrderStatus,
                        Recycled = OrderModel1.Recycled,
                        Status = OrderModel1.Status,
                        TenantId = OrderModel1.TenantId,
                        MallBaseId = OrderModel1.MallBaseId,
                        CreateDate = OrderModel1.CreateDate,
                        UpdateDate = OrderModel1.UpdateDate,
                        PaymentTime = OrderModel1.PaymentTime,
                        DeliveryTime = OrderModel1.DeliveryTime,
                        ReceivingTime = OrderModel1.ReceivingTime,
                        FinishTime = OrderModel1.FinishTime,
                        CancelTime = OrderModel1.CancelTime,
                        IsApplyForCancel = OrderModel1.IsApplyForCancel,
                        HistoryOrderStatus = OrderModel1.HistoryOrderStatus,
                        CancelRemark = OrderModel1.CancelRemark,
                        ApplyForCancelStatus = OrderModel1.ApplyForCancelStatus,
                        RejectRemark = OrderModel1.RejectRemark,
                        UserName = OrderModel1.UserName,
                        PName = OrderModel1.PName,
                        CName = OrderModel1.CName,
                        DName = OrderModel1.DName,
                        PlatformNameImport = OrderModel1.PlatformNameImport,
                        CostMoneyImport = OrderModel1.CostMoneyImport,
                        OrderStatusImport = OrderModel1.OrderStatusImport,
                        OriginalMoneyImport = OrderModel1.OriginalMoneyImport,
                        PaymentStatusImport = OrderModel1.PaymentStatusImport,
                        PaymentWayImport = OrderModel1.PaymentWayImport,
                        SellMoneyImport = OrderModel1.SellMoneyImport,
                        SpecificationImport = OrderModel1.SpecificationImport,
                        DistrictAddress = OrderModel1.DistrictAddress,
                        GoodsName = OrderModel1.GoodsName,
                        OrderNum = OrderModel1.OrderNum,
                        ProductCode = OrderModel1.ProductCode,
                        OrderType = OrderModel1.OrderType,
                        Use_Integral = OrderModel1.Use_Integral,
                        AddressId = OrderModel1.AddressId,
                        DetailList = OrderModel1.DetailList,
                        EndTime = OrderModel1.EndTime,
                        ExcelEnumIds = OrderModel1.ExcelEnumIds,
                        GoodsId = OrderModel1.GoodsId,
                        GoodsTotalNum = OrderModel1.GoodsTotalNum,
                        IsFormShoppingCart = OrderModel1.IsFormShoppingCart,
                        IsOrderCommission = OrderModel1.IsOrderCommission,
                        OrderCommissionList = OrderModel1.OrderCommissionList,
                        OrderIds = OrderModel1.OrderIds,
                        orderNos = OrderModel1.orderNos,
                        OrderStatusIds = OrderModel1.OrderStatusIds,
                        ShoppingAddressId = OrderModel1.ShoppingAddressId,
                        ShoppingCartIdList = OrderModel1.ShoppingCartIdList,
                        StartTime = OrderModel1.StartTime,
                        User_Coupon_Id = OrderModel1.User_Coupon_Id
                    };
                    #region 订单主表赋值
                    //订单平台
                    var platformModel = PlatformList.Where(x => x.Key == OrderModel.PlatformNameImport).FirstOrDefault();
                    OrderModel.OrderSource = (UserSourceEnum)(Convert.ToInt32(platformModel.Value));
                    //订单状态
                    var orderstatusMode = OrderStatusList.Where(x => x.Key == OrderModel.OrderStatusImport).FirstOrDefault();
                    OrderModel.OrderStatus = (OrderStatusEnum)(Convert.ToInt32(orderstatusMode.Value));
                    //支付方式
                    OrderModel.PaymentWay = OrderPaymentTypeEnum.OnlinePayment;
                    if (!string.IsNullOrEmpty(OrderModel.PaymentWayImport))
                    {
                        var payModel = PayWayList.Where(x => x.Key == OrderModel.PaymentWayImport).FirstOrDefault();
                        OrderModel.PaymentWay = (OrderPaymentTypeEnum)(Convert.ToInt32(payModel.Value));
                    }
                    //用户 通过正则表达式 提取用户id
                    //var uModel = userList.Where(x => x.Name == OrderModel.UserName).FirstOrDefault();
                    //OrderModel.UserId = uModel?.Id ?? -1;// -1 表示抓取用户失败
                    try
                    {
                        OrderModel.UserName = OrderModel.UserName.Replace("\t", "");
                        var reg = new System.Text.RegularExpressions.Regex("id:.*", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        string aa = reg.Match(OrderModel.UserName).ToString().Replace("id:", "").Replace(")", "");
                        OrderModel.UserId = Convert.ToInt32(aa);
                    }
                    catch (Exception)
                    {
                        return "用户id有误，订单号：" + OrderNo;
                    }



                    //主表价格
                    OrderModel.PreferPrice = DetailList.Sum(x => x.PreferPrice ?? 0);
                    OrderModel.Income = DetailList.Sum(x => x.Income ?? 0);
                    OrderModel.FreightMoney = DetailList.Sum(x => x.FreightMoney ?? 0);
                    OrderModel.Fee = 0;
                    OrderModel.Refund = 0;
                    OrderModel.CouponMoney = 0;
                    OrderModel.CouponsIds = "";
                    OrderModel.DeliveryMethod = OrderDeliveryMethodEnum.ExpressDistribution;
                    OrderModel.Country = 2;
                    OrderModel.Province = cityList.Where(x => x.Name == OrderModel.PName).FirstOrDefault()?.ID ?? 0;
                    OrderModel.City = cityList.Where(x => x.Name == OrderModel.CName).FirstOrDefault()?.ID ?? 0;
                    OrderModel.District = cityList.Where(x => x.Name == OrderModel.DName).FirstOrDefault()?.ID ?? 0;
                    OrderModel.Recycled = 2;
                    OrderModel.Status = 0;
                    OrderModel.TenantId = tenantId;
                    OrderModel.MallBaseId = mallBaseId;
                    OrderModel.CreateDate = DateTime.Now;
                    OrderModel.UpdateDate = DateTime.Now;
                    OrderModel.FinishTime = OrderModel.ReceivingTime;
                    OrderModel.IsApplyForCancel = 2;
                    OrderModel.HistoryOrderStatus = 0;
                    OrderModel.CancelRemark = "";
                    OrderModel.ApplyForCancelStatus = 0;
                    OrderModel.RejectRemark = "";
                    //OrderModel.ChangePrice = 0;
                    #endregion

                    OrderModel.DetailList = new List<RB_Goods_OrderDetail_Extend>();
                    //组装订单详情
                    foreach (var item in DetailList)
                    {
                        //商品
                        var goodsModel = goodsList.Where(x => x.Name == item.GoodsName).FirstOrDefault();
                        string CoverImage = "";
                        if (!string.IsNullOrEmpty(goodsModel?.CarouselImage) && (goodsModel?.CarouselImage ?? "") != "[]")
                        {
                            List<string> carouseList = JsonConvert.DeserializeObject<List<string>>(goodsModel?.CarouselImage ?? "");
                            CoverImage = carouseList[0];
                        }
                        List<string> SpecificationList = new List<string>();
                        if (!string.IsNullOrEmpty(item.SpecificationImport))
                        {
                            string[] arr = item.SpecificationImport.Split('，');
                            foreach (var qitem in arr)
                            {
                                if (!string.IsNullOrEmpty(qitem))
                                {
                                    SpecificationList.Add(qitem);
                                }
                            }
                        }
                        OrderModel.DetailList.Add(new RB_Goods_OrderDetail_Extend()
                        {
                            Id = 0,
                            OrderId = 0,
                            GoodsId = goodsModel?.Id ?? -1,
                            OrderType = OrderTypeEnum.Mall,
                            GoodsName = item.GoodsName,
                            CoverImage = CoverImage,
                            Specification = JsonConvert.SerializeObject(SpecificationList),
                            SpecificationSort = "",
                            ProductCode = item.ProductCode,
                            Unit_Price = item.SellMoneyImport,
                            Number = item.OrderNum,
                            Original_Price = item.PreferPrice,
                            Final_Price = item.Income,
                            CostMoney = item.CostMoneyImport,
                            DiscountRate = 0,
                            IsMemberPrice = 2,
                            TenantId = tenantId,
                            MallBaseId = mallBaseId,
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            IsComment = 1,
                            FreightMoney = item.FreightMoney,
                            IntegralNumber = 0,
                            IntegralMoney = 0,
                            CouponMoney = 0,
                        });
                    }
                    OrderList.Add(OrderModel);
                }

                var trans = goods_OrderRepository.DbTransaction;
                try
                {
                    foreach (var item in OrderList)
                    {
                        bool flag = GoodsOrderInsert(item, trans);
                        if (flag == false)
                        {
                            goods_OrderRepository.DBSession.Rollback();
                            return "请联系管理员，订单导入失败：" + item.OrderNo;
                        }
                    }
                    goods_OrderRepository.DBSession.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetAppletGoodsOrderInfo");
                    goods_OrderRepository.DBSession.Rollback("SetAppletGoodsOrderInfo");
                    return "出错啦，请联系管理员";
                }
            }
            System.IO.File.Delete(path_server);
            return "";
        }

        /// <summary>
        /// 订单导入
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="trans"></param>
        /// <returns></returns>
        public bool GoodsOrderInsert(RB_Goods_Order_Extend demodel, System.Data.IDbTransaction trans)
        {
            int OrderId = goods_OrderRepository.Insert(demodel, trans);
            if (OrderId > 0)
            {
                //插入订单明细
                foreach (var item in demodel.DetailList)
                {
                    item.OrderId = OrderId;
                    //插入订单明细表
                    int detailId = goods_OrderDetailRepository.Insert(item, trans);
                }
                //记录日志
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Id = 0,
                    Type = 1,
                    SourceId = OrderId,
                    Content = "赞羊导入订单",
                    CreateDate = DateTime.Now,
                    MallBaseId = demodel.MallBaseId,
                    TenantId = demodel.TenantId
                });
            }
            return OrderId > 0;
        }
        #endregion

        #region 快递公司
        #region 快递公司
        /// <summary>
        /// 快递公司列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<Model.Entity.BaseSetUp.RB_Logistics_Express> GetLogisticsExpressList(Model.Entity.BaseSetUp.RB_Logistics_Express query)
        {
            return logistics_ExpressRepository.GetLogisticsExpressList(query);
        }
        #endregion
        #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_OrderDetail_Extend> GetRecommendOrdersCommissionPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderIntroduction_Extend demodel)
        {
            List<RB_Goods_OrderDetail_Extend> RList = new List<RB_Goods_OrderDetail_Extend>();
            var list = goods_OrderIntroductionRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //获取订单明细
                string DetailIds = string.Join(",", list.Select(x => x.OrderDetailId ?? 0));
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderDetailIds = DetailIds });
                //获取订单列表
                string OrderIds = string.Join(",", list.Select(x => x.OrderId ?? 0));
                var olist = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = OrderIds });

                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", list.Select(x => x.UserId).Distinct()) });
                //获取分销商
                var dislist = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", list.Select(x => x.UserId).Distinct()) });

                foreach (var item in list)
                {
                    var dmodel = dlist.Where(x => x.Id == item.OrderDetailId).FirstOrDefault();
                    if (dmodel != null)
                    {
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        item.UserName = umodel?.Name ?? "";
                        item.Mobile = umodel?.Moblie ?? "";
                        item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";

                        var omodel = olist.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        dmodel.OrderNo = omodel?.OrderNo ?? "";
                        dmodel.OrderIntroduction = item;
                        RList.Add(dmodel);
                    }
                }
            }
            return RList;
        }

        /// <summary>
        /// 设置推荐供应商返佣
        /// </summary>
        /// <param name="orderDetailId"></param>
        /// <param name="commission"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetRecommendOrdersCommission(int orderDetailId, decimal commission, int tenantId, int mallBaseId, int empId)
        {
            var introductionModel = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { OrderDetailId = orderDetailId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (introductionModel == null) { return false; }
            if (introductionModel.CommissionState != 1) { return false; }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderIntroduction.Commission),commission},
                { nameof(RB_Goods_OrderIntroduction.Remark),(introductionModel.Remark??"")+"  "+"修改返佣：由" + (introductionModel.Commission ?? 0) + "=>" + commission}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderIntroduction.Id),
                      FiledValue=introductionModel.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderIntroductionRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = empId + " 修改推荐供应商返佣：由" + (introductionModel.Commission ?? 0) + "=>" + commission,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = introductionModel.Id,
                    TenantId = tenantId,
                    Type = 3
                });
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 设置微店返佣金额
        /// </summary>
        /// <param name="orderDetailId"></param>
        /// <param name="commission"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetSmallShopsOrdersCommission(int orderDetailId, decimal commission, int tenantId, int mallBaseId, int empId)
        {
            var ssModel = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { OrderDetailId = orderDetailId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (ssModel == null) { return false; }
            if (ssModel.CommissionState != 1) { return false; }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_SmallShops_Commission_Extend.Commission),commission},
                { nameof(RB_SmallShops_Commission_Extend.Remark),(ssModel.Remark??"")+"  "+"修改返佣：由" + (ssModel.Commission ?? 0) + "=>" + commission}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                      FiledValue=ssModel.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = smallShops_CommissionRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = empId + " 修改微店返佣金额：由" + (ssModel.Commission ?? 0) + "=>" + commission,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = ssModel.Id,
                    TenantId = tenantId,
                    Type = 4
                });
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 供应商订单商品信息
        /// <summary>
        /// 获取订单商品分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetSupplierOrderPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderDetail_Extend dmodel)
        {
            return goods_OrderDetailRepository.GetSupplierOrderPageList(pageIndex, pageSize, out count, dmodel);
        }


        /// <summary>
        /// 获取订单商品列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetSupplierOrderList(RB_Goods_OrderDetail_Extend dmodel)
        {
            return goods_OrderDetailRepository.GetSupplierOrderList(dmodel);
        }


        /// <summary>
        /// 获取订单商品列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetOrderGoodsList(RB_Goods_OrderDetail_Extend dmodel)
        {
            return goods_OrderDetailRepository.GetOrderGoodsList(dmodel);
        }

        /// <summary>
        /// 获取订单明细列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetOrderDetailList(RB_Goods_OrderDetail_Extend dmodel)
        {
            return goods_OrderDetailRepository.GetOrderDetailList(dmodel);
        }


        /// <summary>
        /// 获取未出库的订单商品列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetNoOutOrderGoodsList(int pageIndex, int pageSize, out long count, RB_Goods_OrderDetail_Extend dmodel)
        {
            return goods_OrderDetailRepository.GetNoOutOrderGoodsList(pageIndex, pageSize, out count, dmodel);
        }

        public List<RB_Distributor_Info_Extend> GetDistributorInfoList(RB_Distributor_Info_Extend dmodel)
        {
            return distributor_InfoRepository.GetList(dmodel);
        }

        #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> GetSmallShopOrdersPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetSmallShopOrdersPageList(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)) });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    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);
                //分销情况
                var oclist = smallShopsCommissionRepository.GetListGroupByUser(new RB_SmallShops_Commission_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                if (oclist.Any())
                {
                    //获取用户
                    var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                    //获取分销商
                    var dislist = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                    foreach (var item in oclist)
                    {
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        item.UserName = umodel?.Name ?? "";
                        item.Mobile = umodel?.Moblie ?? "";
                        item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";

                    }
                }
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    string areaName = (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 ?? "");
                    item.ShoppingAddress = areaName + " " + item.ShoppingAddress;

                    item.SmallShopsCommissionOrderList = oclist.Where(x => x.OrderId == item.OrderId).ToList();
                    item.IsOrderCommission = 2;
                    if (item.SmallShopsCommissionOrderList.Where(x => x.CommissionState == 2).Any())
                    {
                        item.IsOrderCommission = 1;
                    }
                }
            }
            return list;
        }
        #endregion

        #region 订单评论返积分
        /// <summary>
        /// 订单评论返积分
        /// </summary>
        /// <param name="memberIntegralModel"></param>
        /// <returns></returns>
        public bool AddMemberIntegral(Model.Entity.User.RB_Member_Integral memberIntegralModel)
        {
            if (memberIntegralModel.Id == 0)
            {
                bool result = member_IntegralRepository.Insert(memberIntegralModel) > 0;
                if (result && memberIntegralModel.UserId > 0)//更新当前用户的积分
                {
                    try
                    {
                        var memberUserModel = member_UserRepository.GetEntity(memberIntegralModel.UserId);
                        memberUserModel.Integral += (memberIntegralModel.Integral ?? 0);
                        //更新订单商品为已评价
                        Dictionary<string, object> keyValuesCar = new Dictionary<string, object>() {
                                { nameof(Model.Entity.User.RB_Member_User.Integral),memberUserModel.Integral}
                            };
                        List<WhereHelper> wheresCar = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(Model.Entity.User.RB_Member_User.Id),
                                      FiledValue=memberIntegralModel.UserId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                        member_UserRepository.Update(keyValuesCar, wheresCar);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write(ex);
                    }
                }
                return result;
            }
            return false;

        }
        #endregion
    }
}
