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.Reserve;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.Repository.Education;
using Mall.Repository.Reserve;
using Mall.ThirdCore.Message;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using VT.FW.DB;

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

        /// <summary>
        /// 套餐卡
        /// </summary>
        private RB_Reserve_MemberCouponRepository reserve_MemberCouponRepository = new RB_Reserve_MemberCouponRepository();

        /// <summary>
        /// 套餐卡实体
        /// </summary>
        private RB_Reserve_CouponRepository reserve_CouponRepository = new RB_Reserve_CouponRepository();
        /// <summary>
        /// 套餐卡适配
        /// </summary>
        private RB_Reserve_CouponProductRepository reserve_CouponProductRepository = new RB_Reserve_CouponProductRepository();
        /// <summary>
        /// 套餐卡使用
        /// </summary>
        private RB_Reserve_MemberUseCouponRepository reserve_MemberUseCouponRepository = new RB_Reserve_MemberUseCouponRepository();
        /// <summary>
        /// 教育商品订单
        /// </summary>
        private readonly RB_EduGoods_OrderRepository eduGoods_OrderRepository = new RB_EduGoods_OrderRepository();
        private readonly RB_EduGoods_OrderDetailRepository eduGoods_OrderDetailRepository = new RB_EduGoods_OrderDetailRepository();
        /// <summary>
        /// 财务单据配置
        /// </summary>
        private readonly RB_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();
        /// <summary>
        /// 教育创建人
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();



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

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

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

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

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

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

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

                    }
                    #endregion

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

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

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

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

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

                        item.Final_Price -= integral_price;
                    }
                    #endregion

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

                    }
                    #endregion

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

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

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

                    decimal couponMoney = 0;//优惠金额
                    if (demodel.User_Coupon_Id > 0)
                    {
                        var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                        if (couponModel != null)
                        {
                            couponMoney = couponModel.CouponMoney;
                            TotalGoodsMoney -= couponMoney;//总价格需减去优惠券金额
                        }
                    }
                    bool IsUseEducation = false;
                    if (demodel.Use_Education_Id > 0) {
                        var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                        if (couponModel != null) {
                            EducationNum += 1;
                            EducationMoney += couponModel.TotalMoney;
                            TotalGoodsMoney -= couponModel.TotalMoney;//总价格需减去课程卡金额
                            IsUseEducation = true;
                        }
                    }
                    var tempLogo = new MarketingLogoItem();
                    if (!string.IsNullOrEmpty(gmodel?.MarketingLogo))
                    {
                        try
                        {
                            tempLogo = Common.Plugin.JsonHelper.DeserializeObject<MarketingLogoItem>(gmodel?.MarketingLogo);
                        }
                        catch
                        {
                            tempLogo = new MarketingLogoItem();
                        }
                    }
                    goods_list.Add(new
                    {
                        id = gmodel.Id,
                        name = gmodel.Name,
                        categoryIdList = item.CategoryIdList,
                        num = item.Number,
                        forehead_integral = gmodel.PointsDeduction,
                        forehead_integral_type = gmodel.PointsDeductionType,
                        accumulative = gmodel.IsMultipleDeduction,//累计多件抵扣
                        unit_price = item.Unit_Price,
                        total_original_price = (item.Original_Price ?? 0) * (item.Number ?? 0),
                        total_price = (item.Unit_Price ?? 0) * (item.Number ?? 0),//优惠券（有平摊情况） 积分抵扣 （默认从第一个商品抵扣）
                        goods_attr = new
                        {
                            id = 0,
                            goods_id = gmodel.Id,
                            price = item.Unit_Price ?? 0,
                            original_price = item.Original_Price ?? 0,
                            pic_url = gmodel.CoverImage,
                            individual_share = umodel?.IsDistributor ?? 2,// 是否分销商
                            share_type = gmodel.SeparateDistributionMoneyType,//分销佣金类型,
                            member_price = item.MemberPrice,
                            integral_price = demodel.Use_Integral == 1 ? item.IntegralMoney : 0,//积分抵扣金额
                            use_integral = demodel.Use_Integral == 1 ? item.IntegralNumber : 0,
                            couponMoney,
                            is_use_education = IsUseEducation,
                            name = gmodel.Name,
                            cover_pic = gmodel.CoverImage,
                            detail = gmodel.GoodsDetails,
                            number = item.Number,
                            goods_share_level = DistributionCommissionList.Where(x => x.GoodsId == gmodel.Id).Select(x => new
                            {
                                share_commission_first = x.OneCommission,
                                share_commission_second = x.TwoCommission,
                                share_commission_third = x.ThreeCommission,
                                level = x.DistributorGrade
                            }),
                            attr_setting_type = gmodel.SeparateDistributionType,
                            course_score = gmodel.CourseScore
                        },
                        discounts = item.Discounts,
                        member_discount = ((item.Unit_Price ?? 0) * (item.Number ?? 0)) - (item.MemberPrice * (item.Number ?? 0)),
                        cover_pic = gmodel.CoverImage,
                        is_level_alone = gmodel.SeparateSetMember,//是否单独设置会员价
                        is_level = gmodel.EnjoyMember,//是否销售会员价格
                        marketingLogo = JsonHelper.Serialize(tempLogo)
                    });
                }
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    }
                    #endregion

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

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

                }

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

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

                    item.FreightMoney = 0;

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

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

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

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

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

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

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

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

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


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


        #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 || demodel.TenantId == 15))
                {
                    //查询所有财务单据
                    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 OrderDetialIds = string.Join(",", dlist.Select(x => x.Id));
                    var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetailIds = OrderDetialIds, Type = 1, MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId });
                    #endregion
                    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 新增财务单据列表
                        #region 是否申请售后
                        item.IsApplyForAfterSale = 2;
                        if (afterSaleList.Where(x => x.OrderDetialId == item.Id).Any())
                        {
                            item.IsApplyForAfterSale = 1;
                        }
                        #endregion
                    }
                }
                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
                    });
                    //查询订单详情对应的课程卡信息
                    string educationCouponIds = string.Join(",", dlist.Where(x => x.EducationCouponId > 0).Select(x => x.EducationCouponId).Distinct());
                    List<RB_Reserve_MemberCoupon_Extend> educationCouponList = new List<RB_Reserve_MemberCoupon_Extend>();
                    if (!string.IsNullOrWhiteSpace(educationCouponIds))
                    {
                        educationCouponList = reserveMemberCouponRepository.GetList(new RB_Reserve_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.ServicepersonalName = persionList?.Where(qitem => qitem.ID == item.ServicepersonalId)?.FirstOrDefault()?.Name ?? "";
                        item.ReserveCouponList = 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="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);
                    }
                }
                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)
        {
            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

                #region 储值卡退回
                if (omodel.DepositId > 0) {
                    var remodel = goods_OrderAfterSaleRepository.GetEntity(reOrderId);
                    var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = omodel.OrderId });
                    if (dlist.Where(x => x.DepositMoney > 0 && x.DepositRefundMoney == 0).Count() == 1)
                    {
                        //最后一个退款 对比一下总额  与 明细金额
                        var dmodel = dlist.Where(x => x.DepositMoney > 0 && x.DepositRefundMoney == 0).FirstOrDefault();
                        if (dmodel.Id == remodel.OrderDetialId) {
                            decimal RMoney = omodel.DepositMoney - (dlist.Sum(x => x.DepositRefundMoney));//怕运费产生四舍五入问题，直接用总的 - 其他已退回的
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Goods_OrderDetail_Extend.DepositRefundMoney),RMoney}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_OrderDetail_Extend.Id),
                                        FiledValue=dmodel.Id,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderDetailRepository.Update(keyValues1, wheres1);
                            var depositModel = member_DepositBuyRepository.GetEntity(omodel.DepositId);
                            if (depositModel != null)
                            {
                                Dictionary<string, object> keyValues12 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DepositBuy_Extend.SurplusPrice),depositModel.SurplusPrice + RMoney}
                                };
                                List<WhereHelper> wheres12 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_DepositBuy_Extend.Id),
                                          FiledValue=depositModel.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_DepositBuyRepository.Update(keyValues12, wheres12);
                                member_DepositBalanceRepository.Insert(new RB_Member_DepositBalance()
                                {
                                    Id = 0,
                                    UserId = omodel.UserId,
                                    Balance = depositModel.SurplusPrice,
                                    CouponIco = depositModel.CouponIco,
                                    CreateDate = DateTime.Now,
                                    DepositPrice = depositModel.DepositPrice,
                                    MallBaseId = omodel.MallBaseId,
                                    MergeType = 3,
                                    Name = depositModel.Name,
                                    NewDepositBuyId = 0,
                                    OldDepositBuyId = 0,
                                    Remarks = "订单" + omodel.OrderNo + "申请售后退款，退回使用储值卡抵扣" + RMoney + "金额",
                                    SalePrice = depositModel.SalePrice,
                                    Status = 0,
                                    Surplus = depositModel.SurplusPrice + RMoney,
                                    TenantId = omodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income
                                });
                            }
                        }
                    }
                    else {
                        var dmodel = dlist.Where(x => x.Id == remodel.OrderDetialId).FirstOrDefault();
                        if (dmodel != null && dmodel.DepositMoney > 0 && dmodel.DepositRefundMoney == 0) {
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Goods_OrderDetail_Extend.DepositRefundMoney),dmodel.DepositMoney + dmodel.DepositFreightMoney}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_OrderDetail_Extend.Id),
                                        FiledValue=dmodel.Id,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderDetailRepository.Update(keyValues1, wheres1);
                            var depositModel = member_DepositBuyRepository.GetEntity(omodel.DepositId);
                            if (depositModel != null)
                            {
                                Dictionary<string, object> keyValues12 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DepositBuy_Extend.SurplusPrice),depositModel.SurplusPrice + (dmodel.DepositMoney + dmodel.DepositFreightMoney)}
                                };
                                List<WhereHelper> wheres12 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_DepositBuy_Extend.Id),
                                          FiledValue=depositModel.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_DepositBuyRepository.Update(keyValues12, wheres12);
                                member_DepositBalanceRepository.Insert(new RB_Member_DepositBalance()
                                {
                                    Id = 0,
                                    UserId = omodel.UserId,
                                    Balance = depositModel.SurplusPrice,
                                    CouponIco = depositModel.CouponIco,
                                    CreateDate = DateTime.Now,
                                    DepositPrice = depositModel.DepositPrice,
                                    MallBaseId = omodel.MallBaseId,
                                    MergeType = 3,
                                    Name = depositModel.Name,
                                    NewDepositBuyId = 0,
                                    OldDepositBuyId = 0,
                                    Remarks = "订单" + omodel.OrderNo + "申请售后退款，退回使用储值卡抵扣" + (dmodel.DepositMoney + dmodel.DepositFreightMoney) + "金额",
                                    SalePrice = depositModel.SalePrice,
                                    Status = 0,
                                    Surplus = depositModel.SurplusPrice + (dmodel.DepositMoney + dmodel.DepositFreightMoney),
                                    TenantId = omodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income
                                });
                            }
                        }
                    }
                }
                #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);
                                }
                                if (omodel.DepositId > 0)
                                {
                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderDetail_Extend.DepositRefundMoney),item.DepositMoney + item.DepositFreightMoney}
                                    };
                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Goods_OrderDetail_Extend.Id),
                                              FiledValue=item.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    goods_OrderDetailRepository.Update(keyValues1, wheres1, trans);
                                }
                                goods_LogRepository.Insert(new RB_Goods_Log()
                                {
                                    Id = 0,
                                    Type = 2,
                                    SourceId = item.GoodsId,
                                    Content = $"同意客人申请取消订单{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);
                            }
                        }
                        //储值卡回滚
                        if (omodel.DepositId > 0)
                        {
                            var depositModel = member_DepositBuyRepository.GetEntity(omodel.DepositId);
                            if (depositModel != null)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DepositBuy_Extend.SurplusPrice),depositModel.SurplusPrice + omodel.DepositMoney}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_DepositBuy_Extend.Id),
                                          FiledValue=depositModel.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_DepositBuyRepository.Update(keyValues1, wheres1, trans);
                                member_DepositBalanceRepository.Insert(new RB_Member_DepositBalance()
                                {
                                    Id = 0,
                                    UserId = umodel.Id,
                                    Balance = depositModel.SurplusPrice,
                                    CouponIco = depositModel.CouponIco,
                                    CreateDate = DateTime.Now,
                                    DepositPrice = depositModel.DepositPrice,
                                    MallBaseId = umodel.MallBaseId,
                                    MergeType = 3,
                                    Name = depositModel.Name,
                                    NewDepositBuyId = 0,
                                    OldDepositBuyId = 0,
                                    Remarks = "订单" + omodel.OrderNo + "取消，退回使用储值卡抵扣" + omodel.DepositMoney + "金额",
                                    SalePrice = depositModel.SalePrice,
                                    Status = 0,
                                    Surplus = depositModel.SurplusPrice + omodel.DepositMoney,
                                    TenantId = umodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income
                                }, trans);
                            }
                        }
                        //余额支付回滚

                        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);
                            }
                        }
                        try
                        {
                            new MiniProgramMsgModule().SendOrderCancelMsg(tenantId, mallBaseId, umodel.OpenId, omodel.OrderNo, "订单已取消", (omodel.Income ?? 0).ToString(), goodsName);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "SendOrderCancelMsg订单强制取消发送订阅消息失败");
                        }
                    }
                    //记录日志
                    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);
                                }
                            }
                            if (omodel.DepositId > 0) {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods_OrderDetail_Extend.DepositRefundMoney),item.DepositMoney + item.DepositFreightMoney}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods_OrderDetail_Extend.Id),
                                          FiledValue=item.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goods_OrderDetailRepository.Update(keyValues1, wheres1, trans);
                            }
                            goods_LogRepository.Insert(new RB_Goods_Log()
                            {
                                Id = 0,
                                Type = 2,
                                SourceId = item.GoodsId,
                                Content = $"后台强制取消订单{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);
                            }
                        }
                        //储值卡回滚
                        if (omodel.DepositId > 0) {
                            var depositModel = member_DepositBuyRepository.GetEntity(omodel.DepositId);
                            if (depositModel != null) {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DepositBuy_Extend.SurplusPrice),depositModel.SurplusPrice + omodel.DepositMoney}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_DepositBuy_Extend.Id),
                                          FiledValue=depositModel.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_DepositBuyRepository.Update(keyValues1, wheres1, trans);
                                member_DepositBalanceRepository.Insert(new RB_Member_DepositBalance()
                                {
                                    Id = 0,
                                    UserId = umodel.Id,
                                    Balance = depositModel.SurplusPrice,
                                    CouponIco = depositModel.CouponIco,
                                    CreateDate = DateTime.Now,
                                    DepositPrice = depositModel.DepositPrice,
                                    MallBaseId = umodel.MallBaseId,
                                    MergeType = 3,
                                    Name = depositModel.Name,
                                    NewDepositBuyId = 0,
                                    OldDepositBuyId = 0,
                                    Remarks = "订单" + omodel.OrderNo + "取消，退回使用储值卡抵扣" + omodel.DepositMoney + "金额",
                                    SalePrice = depositModel.SalePrice,
                                    Status = 0,
                                    Surplus = depositModel.SurplusPrice + omodel.DepositMoney,
                                    TenantId = umodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income
                                }, trans);
                            }
                        }
                        //余额支付回滚

                        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);
                            }
                        }
                        try
                        {
                            new MiniProgramMsgModule().SendOrderCancelMsg(tenantId, mallBaseId, umodel.OpenId, omodel.OrderNo, "订单已取消", (omodel.Income ?? 0).ToString(), goodsName);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "SendOrderCancelMsg订单强制取消发送订阅消息失败");
                        }
                        #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);
                    }
                }
                else if (flag && tenantId == 15 && omodel.OrderEduType == 2)
                {
                    OrderRefundFinanceModuleForEdu(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="omodel"></param>
        /// <returns></returns>
        public bool OrderRefundFinanceModuleForEdu(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 financeConfig = finance_ConfigRepository.GetList(new Model.Entity.Education.RB_Finance_Config { Group_Id = 100000, Type = Common.Enum.Education.FinanceConfigTypeEnum.EduPropertyRefund }).FirstOrDefault();

                string dstr = "客人付款:" + (omodel.Income ?? 0) + "金额，退款:" + (omodel.Income ?? 0);
                if (financeConfig != null)
                {
                    int CreateBy = financeConfig.CreateBy;// 看学生  甲鹤用户  谁是制单人 （全都使用配置的）
                    string DeptName = accountRepository.GetDeptmentName(financeConfig.UpdateBy);// updateBy 存部门
                    var userInfo = accountRepository.GetEmployeeListRepository(new Employee_ViewModel { Id = CreateBy, Group_Id = financeConfig.Group_Id }).ToList().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
                        {   
                            financeConfig.CostTypeId,
                            Number = 1,
                            OriginalMoney = Money,
                            UnitPrice = Money,
                            Remark = Remark1 + "单号：" + omodel.OrderNo  + "   " + dstr
                        }
                    };

                    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日") + " 自动生成财务单据";
                    }
                    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
                        });
                    }
                    int eduOrderId = eduGoods_OrderRepository.GetList(new RB_Goods_Order_ViewModel() { Group_Id = financeConfig.Group_Id, MallOrderId = omodel.OrderId }).FirstOrDefault()?.OrderId ?? 0;
                    var financeObj = new
                    {
                        ClientType = 0,
                        ClientID = 0,
                        IsPublic = 8,
                        financeConfig.CurrencyId,
                        BType = 1,
                        WBMoney = Money,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        TemplateId = financeConfig?.TempleteId ?? 0,
                        OrderSource = 17,
                        Remark = DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                        detailList,
                        CreateBy = userInfo.Id,
                        RemitterName = umodel.Name,
                        RB_Branch_Id = userInfo.School_Id,
                        RB_Group_Id = userInfo.Group_Id,
                        RB_Depart_Id = financeConfig.UpdateBy,
                        RB_CreateByName = userInfo.EmployeeName,
                        RB_DepartName = DeptName,
                        RB_BranchName = userInfo.SchoolName,
                        RB_GroupName = userInfo.GroupName,
                        FinanceType = 2,
                        OtherType = 54,
                        ReFinanceId = eduOrderId,
                        ReFinanceId2 = omodel.OrderId,
                        ECOrderList = ECList
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign
                    };

                    string apiResult = 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);

                        //更新教育那边订单
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Goods_Order_ViewModel.OrderStatus), 3},
                            { nameof(RB_Goods_Order_ViewModel.Refund), omodel.Income??0},
                            { nameof(RB_Goods_Order_ViewModel.CancelTime), DateTime.Now }
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_ViewModel.OrderId),
                              FiledValue=eduOrderId,
                               OperatorEnum=OperatorEnum.Equal
                            },
                        };
                        eduGoods_OrderRepository.Update(keyValues1, wheres1);
                    }
                    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, "OrderRefundFinanceModuleForEdu");
            }

            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="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderOperation(RB_Goods_Order_Extend orderModel, int type, string remark, decimal income, 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 CreateBy, 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(() => orderGoodsLogRepository.Insert(new RB_OrderGoods_Log()
                {
                    Content = "修改订单商品：" + orderModel.GoodsName + "运费成本:" + freightMoney + ";历史：价格:" + (orderModel.FreightCostMoney ?? 0).ToString(),
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    OrderId = orderModel.OrderId,
                    OrderDetailId = orderModel.Id,
                    CreateBy = CreateBy,
                    TenantId = tenantId,
                    OldCostPrice = (orderModel.FreightCostMoney ?? 0),
                    NewCostPrice = freightMoney,
                    Type = 2
                }));
            }
            return flag;
        }



        /// <summary>
        /// 修改商品订单成本价
        /// </summary>
        /// <param name="OrderDetailId"></param>
        /// <param name="costMoney"></param>
        /// <param name="CreateBy"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string SetOrderCostMoney(int OrderDetailId, decimal costMoney, int CreateBy, int tenantId, int mallBaseId)
        {
            var orderModel = goods_OrderDetailRepository.GetEntity(OrderDetailId);
            if (orderModel == null)
            {
                return "订单明细不存在";
            }
            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(() => orderGoodsLogRepository.Insert(new RB_OrderGoods_Log()
                {
                    Content = "修改订单商品：" + orderModel.GoodsName + "成本:" + costMoney + ";历史：价格:" + (orderModel.CostMoney ?? 0).ToString(),
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    OrderId = orderModel.OrderId,
                    OrderDetailId = orderModel.Id,
                    CreateBy = CreateBy,
                    TenantId = tenantId,
                    OldCostPrice = (orderModel.CostMoney ?? 0),
                    NewCostPrice = costMoney,
                    Type = 1
                }));

                #region 调高成本重新返佣
                // ld 2021-09-17
                //暂只有  赞羊使用
                if (orderModel.MallBaseId == 1 && orderModel.FXCommission > 0 && orderModel.OriginalCostMoney > 0 && costMoney > orderModel.OriginalCostMoney && (orderModel.Unit_Price ?? 0) - orderModel.OriginalCostMoney > 0) {
                    //先计算 调高返佣后  应发佣金
                    decimal NewCommission = (orderModel.FXCommission / ((orderModel.Unit_Price ?? 0) - orderModel.OriginalCostMoney)) * ((orderModel.Unit_Price ?? 0) - costMoney);
                    NewCommission -= Math.Round((orderModel.DeductionCommission ?? 0) / (orderModel.Number ?? 1), 2, MidpointRounding.AwayFromZero);// 减去下单已抵扣的佣金 （这个佣金 需除以数量）

                    var trans = goods_OrderCommissionRepository.DbTransaction;
                    try
                    {
                        #region 重新跑返佣
                        //只重置粉象模式
                        var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = orderModel.TenantId, MallBaseId = orderModel.MallBaseId }).FirstOrDefault();
                        if ((basicModel?.IsEnableFXGrade ?? 2) == 1)
                        {
                            bool IsReset = false;
                            #region 先清除当前商品返佣
                            var commissionList = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { MallBaseId = orderModel.MallBaseId, OrderId = orderModel.OrderId, OrderDetailId = orderModel.Id });
                            if (commissionList.Any())
                            {
                                if (!commissionList.Where(x => x.CommissionState == 2).Any())
                                {
                                    IsReset = true;
                                    //删除原返佣记录   排除抵扣的
                                    var dellist = commissionList.Where(x => !((x.Commission ?? 0) == 0 && (x.DeductionCommission ?? 0) > 0)).ToList();
                                    if (dellist.Any())
                                    {
                                        goods_OrderCommissionRepository.DeleteBatch(dellist);
                                    }
                                }
                            }
                            #endregion
                            if (IsReset && NewCommission > 0)
                            {
                                var demodel = goods_OrderRepository.GetEntity<RB_Goods_Order_Extend>(orderModel.OrderId);
                                demodel.DetailList = new List<RB_Goods_OrderDetail_Extend>() { };
                                demodel.DetailList.Add(orderModel.RefMapperTo<RB_Goods_OrderDetail_Extend>());
                                int userId = demodel.UserId ?? 0;
                                var umodel = member_UserRepository.GetEntity(userId);
                                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.EducationCouponId ?? 0) == 0).ToList();
                                            foreach (var item in DetailList)
                                            {
                                                item.CommissionPrice = NewCommission;//直接赋值当前商品应发佣金
                                                if ((item.PresentFXGrade ?? 0) > 0)
                                                {
                                                    //是赠送VIP等级的  暂直接表示 反购买VIP佣金  2020-08-03  ld
                                                    continue;
                                                }
                                                //返佣
                                                List<RB_Goods_OrderCommission> gocList = new List<RB_Goods_OrderCommission>();
                                                List<FXOrderCommissionNumModel> fxNumList = new List<FXOrderCommissionNumModel>();
                                                decimal TotalCommission = item.CommissionPrice;
                                                int UserId = umodel.Id;
                                                int Num = 1;
                                                while (UserId > 0 && TotalCommission > 0)
                                                {
                                                    var numodel = ulist.Where(x => x.Id == UserId).FirstOrDefault();
                                                    if (numodel == null)
                                                    {
                                                        UserId = 0;
                                                        break;
                                                    }
                                                    if (numodel.Id == umodel.Id)
                                                    {
                                                        //第一个进来  按等级的返佣比例给佣金
                                                        UserId = numodel.SuperiorId ?? 0;
                                                        decimal DcommionMoney = 0;
                                                        if (FXModel.DecimalType == 1)
                                                        {
                                                            DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0) / 100);
                                                        }
                                                        else
                                                        {
                                                            DcommionMoney = Math.Ceiling(item.CommissionPrice * (FXModel.CommissionRatio ?? 0)) / 100;
                                                        }
                                                        fxNumList.Add(new FXOrderCommissionNumModel()
                                                        {
                                                            GradeId = FXModel.Id,
                                                            Grade = FXModel.Grade ?? 0,
                                                            Money = DcommionMoney,
                                                            Sort = Num,
                                                            IsSelfBuy = 1
                                                        });
                                                        Num++;
                                                        TotalCommission -= DcommionMoney;

                                                        RB_Goods_OrderCommission gocModel = new RB_Goods_OrderCommission()
                                                        {
                                                            Id = 0,
                                                            Commission = FXModel.CommissionType == 2 ? 0 : DcommionMoney,//下单抵扣了  返佣金额=0
                                                            CommissionState = 1,
                                                            CreateDate = DateTime.Now,
                                                            Grade = FXModel.Id,
                                                            IsGoodsDistribution = 2,
                                                            MallBaseId = demodel.MallBaseId,
                                                            OrderDetailId = item.Id,
                                                            OrderId = orderModel.OrderId,
                                                            Remark = "粉象 " + FXModel.GradeName + "下单返佣，返佣比例:" + (FXModel.CommissionRatio ?? 0) + "%;" + (FXModel.CommissionType == 2 ? "已抵扣" + (DcommionMoney * (item.Number ?? 0)) + "金额" : ""),
                                                            TenantId = demodel.TenantId,
                                                            UpdateDate = DateTime.Now,
                                                            UserId = numodel.Id,
                                                            Type = 3,
                                                            IsRemit = 0,
                                                            DeductionCommission = (DcommionMoney * (item.Number ?? 0))
                                                        };
                                                        gocList.Add(gocModel);
                                                    }
                                                    else
                                                    {
                                                        var d2Model = dlist.Where(x => x.UserId == numodel.Id).FirstOrDefault();
                                                        var FXGModel = new RB_Distributor_FXGrade_Extend();
                                                        if (d2Model == null)
                                                        {
                                                            LogHelper.Write("粉象返佣 用户分销商信息不存在：UserId:" + numodel.Id);
                                                            FXGModel = FXPModel;
                                                        }
                                                        else
                                                        {
                                                            FXGModel = FXList.Where(x => x.Id == d2Model.FXGradeId).FirstOrDefault();
                                                            if (FXGModel == null)
                                                            {
                                                                FXGModel = FXPModel;
                                                            }
                                                        }
                                                        int MaxGrade = fxNumList.Max(x => x.Grade);
                                                        if (FXGModel.Grade < MaxGrade)
                                                        {
                                                            //后面的全部不返佣  2020-08-06  刘东 继续找下一级返佣
                                                            UserId = numodel.SuperiorId ?? 0;
                                                            continue;
                                                        }
                                                        int MaxGradeNum = fxNumList.Where(x => x.Grade == FXGModel.Grade).Count();
                                                        int MaxGradeId = fxNumList.Where(x => x.Grade == MaxGrade).FirstOrDefault()?.GradeId ?? 0;
                                                        if ((FXGModel.SiblingRebatesNum ?? 0) + 1 > MaxGradeNum)
                                                        {
                                                            UserId = numodel.SuperiorId ?? 0;
                                                            decimal DcommionMoney = 0;
                                                            decimal CommissionRatio = 0;
                                                            if (FXGModel.Grade > MaxGrade && fxNumList.Where(x => x.GradeId == FXPModel.Id).Count() == 2 && MaxGrade == FXPModel.Grade)
                                                            {
                                                                //需要提间接普会
                                                                CommissionRatio = GetFXGradeRatioCommon(FXList, FXGModel.Id, FXPModel.Id, 2);
                                                            }
                                                            else
                                                            {
                                                                CommissionRatio = GetFXGradeRatioCommon(FXList, FXGModel.Id, MaxGradeId, 1);
                                                            }
                                                            if (FXGModel.DecimalType == 1)
                                                            {
                                                                DcommionMoney = Math.Ceiling(item.CommissionPrice * CommissionRatio / 100);
                                                            }
                                                            else
                                                            {
                                                                DcommionMoney = Math.Ceiling(item.CommissionPrice * CommissionRatio) / 100;
                                                            }
                                                            fxNumList.Add(new FXOrderCommissionNumModel()
                                                            {
                                                                GradeId = FXGModel.Id,
                                                                Grade = FXGModel.Grade ?? 0,
                                                                Money = DcommionMoney,
                                                                Sort = Num,
                                                                IsSelfBuy = 2
                                                            });
                                                            Num++;
                                                            bool IsMoneyLack = false;
                                                            if (TotalCommission < DcommionMoney)
                                                            {
                                                                DcommionMoney = TotalCommission;
                                                                IsMoneyLack = true;
                                                            }
                                                            RB_Goods_OrderCommission gocModel = new RB_Goods_OrderCommission()
                                                            {
                                                                Id = 0,
                                                                Commission = DcommionMoney,
                                                                CommissionState = 1,
                                                                CreateDate = DateTime.Now,
                                                                Grade = FXGModel.Id,
                                                                IsGoodsDistribution = 2,
                                                                MallBaseId = demodel.MallBaseId,
                                                                OrderDetailId = item.Id,
                                                                OrderId = orderModel.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;//继续查找下一级
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                //只插入非抵扣类型的佣金
                                                foreach (var qitem in gocList.Where(x => !((x.Commission ?? 0) == 0 && (x.DeductionCommission??0) >0)))
                                                {
                                                    qitem.Commission = (qitem.Commission ?? 0) * (item.Number ?? 0);
                                                    goods_OrderCommissionRepository.Insert(qitem, trans);
                                                }
                                            }
                                        }
                                    }
                                }

                                #region 记录操作日志
                                goods_LogRepository.Insert(new RB_Goods_Log()
                                {
                                    Id = 0,
                                    Type = 1,
                                    SourceId = orderModel.OrderId,
                                    Content = "调整订单商品成本为：" + costMoney + "，触发重置该商品返佣",
                                    CreateDate = DateTime.Now,
                                    MallBaseId = orderModel.MallBaseId,
                                    TenantId = orderModel.TenantId
                                }, trans);

                                //更新订单备注
                                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                    { nameof(RB_Goods_Order_Extend.Remark), demodel.Remark + "；修改订单商品"+orderModel.Id+"成本，返佣已更新"}
                                };
                                List<WhereHelper> wheres = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName= nameof(RB_Goods_Order_Extend.OrderId ),
                                          FiledValue= demodel.OrderId,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goods_OrderRepository.Update(keyValues, wheres, trans);
                                #endregion
                            }
                        }
                        #endregion
                        goods_OrderCommissionRepository.DBSession.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write(ex, "SetOrderCostMoney 重置返佣失败");
                        goods_OrderCommissionRepository.DBSession.Rollback();
                    }
                }
                #endregion
            }
            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>
        /// <returns></returns>
        public bool SetECUpdateOrderOtherMoney(RB_Goods_OrderDetail_Extend model, int money, int otherType, int type)
        {
            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
                });
                List<RB_Reserve_MemberCoupon_Extend> educationCouponList = new List<RB_Reserve_MemberCoupon_Extend>();
                // 查询订单详情对应的套餐卡信息
                string educationCouponIds = string.Join(",", dlist.Where(x => x.EducationCouponId > 0).Select(x => x.EducationCouponId).Distinct());
                if (!string.IsNullOrWhiteSpace(educationCouponIds))
                {
                    educationCouponList = reserveMemberCouponRepository.GetList(new RB_Reserve_MemberCoupon_Extend { TenantId = tenantId, MallBaseId = mallBaseId, Ids = educationCouponIds });
                }
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsBindExpress = erList.Where(x => x.OrderDetailId == item.Id).Any() ? 1 : 2;
                    item.ServicepersonalName = serviceList?.Where(qitem => qitem.ID == item.ServicepersonalId)?.FirstOrDefault()?.Name ?? "";
                    item.ReserveCouponList = educationCouponList.Where(x => x.Id == item.EducationCouponId).ToList();// 2020-10-11 订单详情对应的套餐卡
                }
            }
            model.DetailList = dlist;
            //地址
            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,
                EducationMoney = (model?.EducationMoney ?? 0),
                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,
                model.DepositId,
                model.DepositMoney,
                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 ?? "",
                    DeductionCommission = model.DeductionCommission ?? 0,
                    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,
                    DeductionCommission = x.DeductionCommission ?? 0
                }),
                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,
                    x.DeductionCommission,
                    CouponMoney = x.CouponMoney ?? 0,
                    InsuranceMoney = x.InsuranceMoney ?? 0,
                    IntegralMoney = x.IntegralMoney ?? 0,
                    IntegralNumber = x.IntegralNumber ?? 0,
                    x.ServiceTime,
                    x.ServiceDate,
                    x.ServicepersonalName,
                    MemberEducationCouponList = x?.ReserveCouponList.Select(z => new
                    {
                        z.Name,
                        z.UseHeXiao,
                        z.HeXiao
                    }),
                }),
            });
        }

        /// <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);
            List<RB_Reserve_ServicePersonal_Extend> persionList = new List<RB_Reserve_ServicePersonal_Extend>();
            if (list != null && list.Count > 0)
            {
                string persionIds = string.Join(",", list.Where(qitem => qitem.ServicepersonalId > 0).Select(qitem => qitem.ServicepersonalId));
                if (!string.IsNullOrEmpty(persionIds))
                {
                    persionList = reserve_ServicePersonalRepository.GetServicePersonalList(new RB_Reserve_ServicePersonal_Extend()
                    {
                        QIds = persionIds
                    });
                }

            }
            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);
                }
                if (item.ServicepersonalId > 0)
                {
                    var personModel = persionList?.Where(qitem => qitem.ID == item.ServicepersonalId)?.FirstOrDefault();
                    item.ServicepersonalName = personModel?.Name ?? "";
                    item.ServicepersonalHead = personModel?.ServiceLogo ?? "";
                }
            }
            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;
            RB_Goods_OrderDetail dmodel;
            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; }
            }
            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, string EBusinessID, string AppKey, string ReqURL)
        {
            return new KdApiSearchDemo().getOrderTracesByJson(expressCode, expressNumber, EBusinessID, AppKey, ReqURL);
        }

        /// <summary>
        /// 查询物流信息
        /// </summary>
        /// <param name="expressCode"></param>
        /// <param name="expressNumber"></param>
        /// <returns></returns>
        public string GetOrderExpressInfoForAliyun(string expressNumber, string expressCode, string AppCode, string ReqUrl)
        {
            return AliyunApiSearchDemo.GetExpressInfo(expressNumber, expressCode, AppCode, ReqUrl);
        }

        /// <summary>
        /// 获取快递配置
        /// </summary>
        /// <returns></returns>
        public Model.Entity.BaseSetUp.RB_Express_Config GetExpressConfig(int tenantId, int mallBaseId)
        {
            return express_ConfigRepository.GetListRepository(new Model.Entity.BaseSetUp.RB_Express_Config() { TenantId = tenantId, MallBaseId = mallBaseId, IsDefault = 1 }).FirstOrDefault();
        }

        #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;
                    //插入订单明细表
                    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

        #region 不可开发票商品记录
        public bool AddInvoiceRecordDetail(RB_Invoice_RecordDetail model)
        {
            return invoiceRecordDetailRepository.Insert(model) > 0;
        }


        /// <summary>
        /// 获取不开发票商品提现记录
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Invoice_Online_Trade_Extend> GetInvoiceOnlineTradePageList(int pageIndex, int pageSize, out long rowCount, RB_Invoice_Online_Trade_Extend query)
        {
            return invoiceOnlineTradeRepository.GetInvoiceOnlineTradePageList(pageIndex, pageSize, out rowCount, query);
        }


        /// <summary>
        /// 获取不开发票商品提现记录
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Invoice_Online_Trade_Extend> GetToDayInvoiceOnlineTradeList(RB_Invoice_Online_Trade_Extend query)
        {
            return invoiceOnlineTradeRepository.GetToDayInvoiceOnlineTradeList(query);
        }

        /// <summary>
        /// 新增提现记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddInvoiceOnlineTrade(RB_Invoice_Online_Trade_Extend model)
        {
            int id = invoiceOnlineTradeRepository.Insert(model);
            return id;
        }

        /// <summary>
        /// 新增提现记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateInvoiceOnlineTrade(RB_Invoice_Online_Trade_Extend model)
        {
            bool flag = false;
            try
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Invoice_Online_Trade.Transaction_Id),model.Transaction_Id },
                    {nameof(RB_Invoice_Online_Trade.Pay_Date),model.Pay_Date },
                    {nameof(RB_Invoice_Online_Trade.Pay_Result),model.Pay_Result }
                };
                flag = invoiceOnlineTradeRepository.Update(fileds, new WhereHelper(nameof(RB_Invoice_Online_Trade.Id), model.Id));
            }
            catch (Exception ex)
            {
                LogHelper.WriteInfo("UpdateInvoiceOnlineTrade更新提现记录失败Transaction_Id:" + model.Transaction_Id + " Pay_Result:" + model.Pay_Result + " 错误原因：" + ex.ToString());
            }
            return flag;


        }

        #endregion

        #region 订单成本修改记录
        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_OrderGoods_Log_Extend> GetOrderGoodsLogPageList(int pageIndex, int pageSize, out long rowCount, RB_OrderGoods_Log_Extend dmodel)
        {
            return orderGoodsLogRepository.GetPageList(pageIndex, pageSize, out rowCount, dmodel);

        }
        #endregion


        #region 教育资产商品

        /// <summary>
        /// 一键生成商品运费成本单据
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userInfo1"></param>
        /// <returns></returns>
        public string SetEduGoodsFreightCostFinance(int orderId, UserInfo userInfo1)
        {
            var omodel = goods_OrderRepository.GetEntity(orderId);
            if (omodel == null || omodel.OrderStatus == OrderStatusEnum.Cancel || omodel.OrderStatus == OrderStatusEnum.NonPayment) { return "订单不存在或者状态有误"; }
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { MallBaseId = userInfo1.MallBaseId, OrderId = orderId });
            if (dlist.Where(x => x.FreightFinanceId > 0).Any())
            {
                return "已生成单据，无法重复生成";
            }

            var financeConfig = finance_ConfigRepository.GetList(new Model.Entity.Education.RB_Finance_Config { Group_Id = 100000, Type = Common.Enum.Education.FinanceConfigTypeEnum.EduFreightCost }).FirstOrDefault();

            if (financeConfig != null)
            {
                int CreateBy = financeConfig.CreateBy;// 看学生  甲鹤用户  谁是制单人 （全都使用配置的）
                string DeptName = accountRepository.GetDeptmentName(financeConfig.UpdateBy);// updateBy 存部门
                var userInfo = accountRepository.GetEmployeeListRepository(new Employee_ViewModel { Id = CreateBy, Group_Id = financeConfig.Group_Id }).ToList().FirstOrDefault();

                var detailList = new List<object>();
                List<RB_ECFinanceId_Relation> ECList = new List<RB_ECFinanceId_Relation>();
                foreach (var qitem in dlist)
                {
                    detailList.Add(new
                    {
                        financeConfig.CostTypeId,
                        Number = 1,
                        OriginalMoney = qitem.FreightCostMoney ?? 0,
                        UnitPrice = qitem.FreightCostMoney ?? 0,
                        Remark = qitem.GoodsName + "，单号：" + omodel.OrderNo
                    });
                    ECList.Add(new RB_ECFinanceId_Relation()
                    {
                        ECOrderId = qitem.OrderId,
                        ECOrderDetailId = qitem.Id
                    });
                }
                int eduOrderId = eduGoods_OrderRepository.GetList(new RB_Goods_Order_ViewModel() { Group_Id = financeConfig.Group_Id, MallOrderId = omodel.OrderId }).FirstOrDefault()?.OrderId ?? 0;
                var financeObj = new
                {
                    ClientType = 10,
                    financeConfig.ClientID,
                    IsPublic = 1,
                    financeConfig.CurrencyId,
                    BType = 1,
                    WBMoney = dlist.Sum(x => x.FreightCostMoney ?? 0),
                    PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    TemplateId = financeConfig?.TempleteId ?? 0,
                    OrderSource = 17,
                    Remark = DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                    detailList,
                    CreateBy = userInfo.Id,
                    RemitterName = "",
                    RB_Branch_Id = userInfo.School_Id,
                    RB_Group_Id = userInfo.Group_Id,
                    RB_Depart_Id = financeConfig.UpdateBy,
                    RB_CreateByName = userInfo.EmployeeName,
                    RB_DepartName = DeptName,
                    RB_BranchName = userInfo.SchoolName,
                    RB_GroupName = userInfo.GroupName,
                    FinanceType = 2,
                    OtherType = 54,
                    ReFinanceId = eduOrderId,
                    ReFinanceId2 = omodel.OrderId,
                    ECOrderList = ECList
                };
                string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                var resultInfo = new
                {
                    msg = sign
                };

                string apiResult = HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                LogHelper.Write(apiResult);
                var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                if (apir.resultCode == 1)
                {
                    //更新电商订单 运费成本单据号
                    foreach (var qitem in dlist)
                    {
                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                            { nameof(RB_Goods_OrderDetail_Extend.FreightFinanceId), Convert.ToInt32(apir.data)}
                        };
                        List<WhereHelper> wheres2 = new List<WhereHelper>()
                        {
                            new WhereHelper()
                            {
                                FiledName = nameof(RB_Goods_OrderDetail_Extend.Id),
                                FiledValue = qitem.Id,
                                 OperatorEnum =OperatorEnum.Equal
                            }
                        };
                        goods_OrderDetailRepository.Update(keyValues2, wheres2);
                    }
                    //更新教育那边订单
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        { nameof(RB_Goods_Order_ViewModel.FreightCostMoney), dlist.Sum(x=>x.FreightCostMoney??0)}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper(){
                            FiledName=nameof(RB_Goods_Order_ViewModel.OrderId),
                            FiledValue=eduOrderId,
                            OperatorEnum=OperatorEnum.Equal
                        },
                    };
                    bool flag = eduGoods_OrderRepository.Update(keyValues1, wheres1);
                    if (flag) {
                        var eduList = eduGoods_OrderDetailRepository.GetList(new RB_Goods_OrderDetail_ViewModel() { OrderId = eduOrderId });
                        foreach (var qitem in eduList) {
                            var dmdoel = dlist.Where(x => x.Id == qitem.MallOrderDetailId).FirstOrDefault();
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Goods_OrderDetail_ViewModel.FreightCostMoney), dmdoel?.FreightCostMoney??0}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_Goods_OrderDetail_ViewModel.Id),
                                      FiledValue = qitem.Id,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            eduGoods_OrderDetailRepository.Update(keyValues, wheres);
                        }
                    }
                }
                return "";
            }
            else
            {
                return "规则配置不存在";
            }
        }

        #endregion
    }
}
