using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Enum.Goods;
using Mall.Common.Enum.User;
using Mall.Common.Plugin;
using Mall.Model.Entity.Product;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Finance;
using Mall.Repository.MarketingCenter;
using Mall.Repository.Product;
using Mall.Repository.User;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;

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

        /// <summary>
        /// 和平返佣
        /// </summary>
        private readonly RB_Distributor_HPCommissionRepository distributor_HPCommissionRepository = new RB_Distributor_HPCommissionRepository();
        /// <summary>
        /// 和平返佣比例
        /// </summary>
        private readonly RB_Distributor_HPGradeRatioRepository distributor_HPGradeRatioRepository = new RB_Distributor_HPGradeRatioRepository();
        /// <summary>
        /// 和平等级
        /// </summary>
        private readonly RB_Distributor_HPGradeInfoRepository distributor_HPGradeInfoRepository = new RB_Distributor_HPGradeInfoRepository();
        /// <summary>
        /// 商品限购区域
        /// </summary>
        private readonly RB_Goods_AreaRepository goods_AreaRepository = new RB_Goods_AreaRepository();
        /// <summary>
        /// 财务单据规则
        /// </summary>
        private static RB_Finance_ConfigurineRepository financeConfigurineRepository = new RB_Finance_ConfigurineRepository();


        #region 购物车

        /// <summary>
        /// 获取购物车分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_ShoppingCart_Extend> GetGoodsShoppingCartPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                count = 0;
                return new List<RB_Goods_ShoppingCart_Extend>();
            }
            var list = goods_ShoppingCartRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string goodsIds = string.Join(",", list.Select(x => x.GoodsId));
                var speciList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciVList = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var mpriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in list)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                    //验证规格是否已失效
                    if (item.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            item.GoodsStatus = 3;
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            item.GoodsStatus = 3;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            item.GoodsStatus = 3;
                        }
                    }
                    //规格赋值
                    item.SpecificationList = new List<string>();
                    if (item.GoodsStatus != 3)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            item.SpecificationList.Add("规格:" + item.DefaultSpecificationName);
                        }
                        else
                        {
                            var KeyArr = item.SpecificationSort.Split(':');
                            for (var i = 0; i < KeyArr.Length; i++)
                            {
                                if (!string.IsNullOrEmpty(KeyArr[i]))
                                {
                                    var sModel = speciList.Where(x => x.GoodsId == item.GoodsId).ToList()[i];
                                    var svModel = speciVList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationId == sModel.Id && x.Sort == Convert.ToInt32(KeyArr[i])).FirstOrDefault();
                                    item.SpecificationList.Add(sModel.Name + ":" + svModel.Name);
                                }
                            }
                            var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                            item.Price = speciPModel?.SellingPrice ?? 0;
                            item.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        }
                        //会员价格
                        if (umodel.MemberGrade > 0)
                        {
                            if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                            {
                                item.Price = mpriceList.Where(x => x.GoodsId == item.GoodsId && x.MemberGrade == umodel.MemberGrade && x.SpecificationSort == item.SpecificationSort).FirstOrDefault()?.MemberPrice ?? 0;
                            }
                            else
                            {
                                //求会员等级折扣
                                var gradeModel = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { Grade = umodel.MemberGrade, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                                item.Price = Math.Round(item.Price * (gradeModel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                    }
                }
            }
            return list;
        }

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

            var scList = goods_ShoppingCartRepository.GetList(new RB_Goods_ShoppingCart_Extend() { GoodsId = demodel.GoodsId, UserId = demodel.UserId, SpecificationSort = demodel.SpecificationSort, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            if (scList.Any())
            {
                //更新数量
                var scModel = scList.FirstOrDefault();
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_ShoppingCart.Number),scModel.Number + demodel.Number},
                    { nameof(RB_Goods_ShoppingCart.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_ShoppingCart.Id),
                          FiledValue=scModel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = goods_ShoppingCartRepository.Update(keyValues, wheres);
            }
            else
            {
                flag = goods_ShoppingCartRepository.Insert(new RB_Goods_ShoppingCart()
                {
                    Id = 0,
                    MallBaseId = demodel.MallBaseId,
                    CreateDate = DateTime.Now,
                    GoodsId = demodel.GoodsId,
                    Number = demodel.Number,
                    SpecificationSort = demodel.SpecificationSort,
                    Status = 0,
                    TenantId = demodel.TenantId,
                    UpdateDate = DateTime.Now,
                    UserId = demodel.UserId
                }) > 0;
            }
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

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

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

        #endregion

        #region 小程序

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

                    item.DistrictAddress = (arealist.Where(x => x.ID == item.Province).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.City).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.District).FirstOrDefault()?.Name ?? "");
                }
            }
            return list;
        }

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

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

        /// <summary>
        /// 获取我的订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletMyOrderInfo(int orderId, int userId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null || model.UserId != userId)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }
            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            if (dlist.Any())
            {
                string orderDetailIds = string.Join(",", dlist.Select(x => x.Id));
                var oasList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetailIds = orderDetailIds, TenantId = tenantId, MallBaseId = mallBaseId });
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsApplyForAfterSale = 2;
                    if (oasList.Where(x => x.OrderDetialId == item.Id).Any())
                    {
                        item.IsApplyForAfterSale = 1;
                    }
                }
            }
            model.DetailList = dlist;
            //地址
            model.DistrictAddress = (destinationRepository.GetEntity(model.Province)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.City)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.District)?.Name ?? "");
            //物流
            var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            //List<RB_Goods_OrderExpress_Extend> oeList = new List<RB_Goods_OrderExpress_Extend>();
            //if (erlist.Any())
            //{
            //    oeList = goods_OrderExpressRepository.GetList(new RB_Goods_OrderExpress_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderExpressIds = string.Join(",", erlist.Select(x => x.OrderExpressId)) });
            //    foreach (var item in oeList)
            //    {
            //        item.ExpressName = logistics_ExpressRepository.GetEntity(item.ExpressId)?.Name ?? "";
            //    }
            //}

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

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

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

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

            return ApiResult.Success("", new
            {
                template_message_list,
                model.OrderId,
                model.OrderNo,
                model.OrderStatus,
                OrderStatusName = model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.PaymentWay,
                PaymentWayName = model.PaymentWay.GetEnumName(),
                model.DeliveryMethod,
                DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                model.PreferPrice,
                model.Income,
                model.CouponMoney,
                model.FreightMoney,
                model.Consignee,
                model.Mobile,
                model.DistrictAddress,
                model.ShoppingAddress,
                IsHaveExpress = erlist.Any() ? 1 : 2,
                DetailList = model.DetailList.Select(x => new
                {
                    DetailId = x.Id,
                    x.GoodsId,
                    x.GoodsName,
                    x.CoverImagePath,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(x.Specification),
                    x.Number,
                    x.Final_Price,
                    x.IsApplyForAfterSale
                }),
                model.IsApplyForCancel,
                model.RejectRemark,
                model.IsCanApplyForAfterSale
            });
        }

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

        /// <summary>
        /// 获取售后页面
        /// </summary>
        /// <param name="orderDetailId"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletMyOrderAfterSaleInfo(int orderDetailId, int userId, int tenantId, int mallBaseId)
        {
            var dModel = goods_OrderDetailRepository.GetEntity<RB_Goods_OrderDetail_Extend>(orderDetailId);
            if (dModel == null)
            {
                return ApiResult.Failed("未查询到订单商品信息");
            }
            dModel.CoverImagePath = dModel.CoverImage;
            var omodel = goods_OrderRepository.GetEntity(dModel.OrderId);
            if (omodel == null) {
                return ApiResult.Failed("未查询到订单信息");
            }
            decimal Final_Price = dModel.Final_Price ?? 0;
            if (omodel.Income < dModel.Final_Price) {
                Final_Price = omodel.Income ?? 0;
            }
            //获取订阅消息
            var miniModel = miniProgramRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId }).FirstOrDefault();

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

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

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


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

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

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

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

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

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

                    if (string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        gmodel.SpecificationNameList.Add("规格:" + gmodel.DefaultSpecificationName);
                        if (item.Number > gmodel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    else
                    {
                        var KeyArr = item.SpecificationSort.Split(':');
                        for (var i = 0; i < KeyArr.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(KeyArr[i]))
                            {
                                var sModel = speciList.Where(x => x.GoodsId == item.GoodsId).ToList()[i];
                                var svModel = speciVList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationId == sModel.Id && x.Sort == Convert.ToInt32(KeyArr[i])).FirstOrDefault();
                                gmodel.SpecificationNameList.Add(sModel.Name + ":" + svModel.Name);
                            }
                        }
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        gmodel.SellingPrice = speciPModel?.SellingPrice ?? 0;
                        gmodel.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        GoodsWeight = speciPModel?.GoodsWeight ?? 0;
                        if (item.Number > speciPModel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    #endregion
                    //会员价格
                    gmodel.MemberPrice = gmodel.SellingPrice ?? 0;
                    if (umodel.MemberGrade > 0)
                    {
                        if (gmodel.EnjoyMember == 1 && gmodel.SeparateSetMember == 1)
                        {
                            gmodel.MemberPrice = mpriceList.Where(x => x.GoodsId == item.GoodsId && x.MemberGrade == umodel.MemberGrade && x.SpecificationSort == item.SpecificationSort).FirstOrDefault()?.MemberPrice ?? 0;
                        }
                        else
                        {
                            //求会员等级折扣
                            var gradeModel = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { Grade = umodel.MemberGrade, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                            gmodel.MemberPrice = Math.Round((gmodel.SellingPrice ?? 0) * (gradeModel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                    //运费
                    decimal Express = 0;
                    if (defModel.Id > 0)
                    {
                        int FreightId2 = gmodel.FreightId ?? 0;
                        if (gmodel.FreightId == 0)
                        {
                            FreightId2 = DefFreightId;
                        }
                        if (FreightId2 > 0)
                        {
                            var rulesModel = rulesList.Where(x => x.ID == FreightId2).FirstOrDefault();
                            List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList2 = priceList.Where(x => x.RulesId == FreightId2).ToList();
                            if (priceList2.Any())
                            {
                                var priceIds = priceList2.Select(x => x.ID).ToList();
                                var regionList2 = regionList.Where(x => priceIds.Contains(x.RulesPriceId)).ToList();

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

        /// <summary>
        /// 获取小程序结算页面详情
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult GetAppletGoodsSettlementInfoForZY(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            //积分
            Model.Entity.MarketingCenter.RB_Integral_Settings integralModel = new Model.Entity.MarketingCenter.RB_Integral_Settings();
            if (umodel.Integral > 0)
            {
                integralModel = integral_SettingsRepository.GetIntegralSettingsList(new Model.Entity.MarketingCenter.RB_Integral_Settings() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            }
            //快递默认
            //demodel.DeliveryMethod ??= OrderDeliveryMethodEnum.ExpressDistribution;
            #region 快递列表
            var mallbaseModel = mallBaseRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_MallBase_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            var Delivery = new object();
            if (!string.IsNullOrEmpty(mallbaseModel?.DeliverWay))
            {
                var DelivertList = EnumHelper.GetEnumList(typeof(OrderDeliveryMethodEnum));
                string[] arr = mallbaseModel?.DeliverWay.Split(',');
                var send_type_list = new List<object>();
                foreach (var item in arr)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        var delmodel = DelivertList.Where(x => x.Value == item).FirstOrDefault();
                        send_type_list.Add(new
                        {
                            name = delmodel.Key,
                            value = delmodel.Value
                        });
                    }
                }
                if (arr.Any() && demodel.DeliveryMethod == 0)
                {//设置默认发货方式
                    var delmodel = DelivertList.Where(x => x.Value == arr[0]).FirstOrDefault();
                    demodel.DeliveryMethod = (OrderDeliveryMethodEnum)Convert.ToInt32(delmodel.Value);
                }
                Delivery = new
                {
                    send_type = demodel.DeliveryMethod,
                    disabled = false,
                    send_type_list
                };
            }
            #endregion

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

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

                disList.Add(defModel.Province ?? 0);
                disList.Add(defModel.City ?? 0);
                disList.Add(defModel.District ?? 0);
            }
            List<object> DList = new List<object>();
            decimal TotalExpress = 0, TotalGoodsMoney = 0, TotalGoodsOriginalMoney = 0, TotalGoodsSellMoney = 0;//总快递费  总商品价格  总原价  总售价
            int DefFreightId = 0;
            decimal member_discount = 0;//总会员优惠
            decimal Total_integral_price = 0;//总积分金额
            int Total_use_integral = 0;//总积分
            decimal CouponsMoney = 0;//优惠总金额
            bool IsPointsDeduction = false;//是否有商品可使用积分抵扣
            bool address_enable = true;//地址Ok
            List<object> goods_list = new List<object>();
            if (demodel.DetailList.Any())
            {
                string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var speciList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciVList = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var mpriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                //区域
                var AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                //返佣
                var DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
                if (demodel.DetailList.Where(x => x.SeparateDistribution == 1).Any())
                {
                    string goodsIds = string.Join(",", demodel.DetailList.Where(x => x.SeparateDistribution == 1).Select(x => x.GoodsId));
                    DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

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

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

                }

                #region 优惠卷初始化
                List<RB_Member_DiscountCoupon_Extend> cList = new List<RB_Member_DiscountCoupon_Extend>();
                List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend> dcList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend>();
                List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend> dcpList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend>();
                if (demodel.User_Coupon_Id > 0)
                {
                    demodel.CouponsIds = demodel.User_Coupon_Id.ToString();
                    if (!string.IsNullOrEmpty(demodel.CouponsIds))
                    {
                        cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 0, Ids = demodel.CouponsIds, UserId = umodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        if (cList.Any())
                        {
                            string cIds = string.Join(",", cList.Select(x => x.CouponId).Distinct());
                            dcList = discountCouponRepository.GetDiscountCouponList(new Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend() { CouponIds = cIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, true);
                            dcpList = discountCoupon_ProductRepository.GetListByDiscountCouponIds(new Model.Entity.MarketingCenter.RB_DiscountCoupon() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, cIds, true);
                            if (dcList.Any())
                            {
                                foreach (var item in cList)
                                {
                                    if (item.CouponId > 0)
                                    {
                                        if (!dcList.Where(x => x.ID == item.CouponId).Any())
                                        {
                                            return ApiResult.Failed("优惠券不存在，请核实后再试");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion
                List<RB_Goods_CouponModel> GoodsCouponList = new List<RB_Goods_CouponModel>();//商品优惠卷 价格（每个商品优惠的价格）
                //初始化值
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    int GoodsWeight = gmodel.GoodsWeight ?? 0;//商品重量
                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();

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

                    }
                    #endregion

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

                    //规格赋值
                    //gmodel.SpecificationNameList = new List<string>();
                    item.SpecificationNameList = new List<string>();
                    List<object> attr_list = new List<object>();
                    if (string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        gmodel.SpecificationNameList.Add("规格:" + gmodel.DefaultSpecificationName);
                        if (item.Number > gmodel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                        attr_list = new List<object>(){ new
                        {
                            attr_group_name = "规格",
                            attr_group_id = 0,
                            attr_id = 0,
                            attr_name = gmodel.DefaultSpecificationName
                        } };
                    }
                    else
                    {
                        var KeyArr = item.SpecificationSort.Split(':');
                        for (var i = 0; i < KeyArr.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(KeyArr[i]))
                            {
                                var sModel = speciList.Where(x => x.GoodsId == item.GoodsId).ToList()[i];
                                var svModel = speciVList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationId == sModel.Id && x.Sort == Convert.ToInt32(KeyArr[i])).FirstOrDefault();
                                item.SpecificationNameList.Add(sModel.Name + ":" + svModel.Name);
                                attr_list.Add(new
                                {
                                    attr_group_name = sModel.Name,
                                    attr_group_id = sModel.Sort,
                                    attr_id = svModel.Id,
                                    attr_name = svModel.Name
                                });
                            }
                        }
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        gmodel.SellingPrice = speciPModel?.SellingPrice ?? 0;
                        gmodel.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        gmodel.GoodsNumbers = speciPModel?.GoodsNumbers ?? "";
                        GoodsWeight = speciPModel?.GoodsWeight ?? 0;
                        if (item.Number > speciPModel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    #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;
                        }
                        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 优惠券
                    //decimal CouponsMoney = 0;
                    if (demodel.User_Coupon_Id > 0)
                    {
                        var ccmodel = cList.Where(x => x.Id == demodel.User_Coupon_Id).FirstOrDefault();
                        string couponItem = (ccmodel?.CouponId ?? 0).ToString();
                        if (!string.IsNullOrEmpty(couponItem))
                        {
                            var dcModel = dcList.Where(x => x.ID == Convert.ToInt32(couponItem)).FirstOrDefault();
                            if (dcModel == null)
                            {
                                return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                            }
                            dcModel.DiscountsPrice = dcModel.DiscountsPrice == 0 ? 10 : dcModel.DiscountsPrice;
                            if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category)  //指定分类
                            {
                                var categoryList1 = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Category).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (categoryList.Select(x => x.Id).Where(x => categoryList1.Contains(x)).Any())
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                            else if (dcModel.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)//指定商品
                            {
                                var goodsList = dcpList.Where(x => x.DiscountCouponId == Convert.ToInt32(couponItem) && x.DiscountCouponType == Common.Enum.MarketingCenter.UseTypeEnum.Product).Select(x => x.ProductId).ToList();//获取特殊优惠卷
                                if (goodsList.Contains(item.GoodsId ?? 0))
                                {
                                    GoodsCouponList.Add(new RB_Goods_CouponModel()
                                    {
                                        GoodsId = item.GoodsId ?? 0,
                                        Key = item.SpecificationSort,
                                        TotalMoney = item.Final_Price ?? 0,
                                        CouponMoney = 0
                                    });
                                }
                            }
                            else
                            {
                                GoodsCouponList.Add(new RB_Goods_CouponModel()
                                {
                                    GoodsId = item.GoodsId ?? 0,
                                    Key = item.SpecificationSort,
                                    TotalMoney = item.Final_Price ?? 0,
                                    CouponMoney = 0
                                });
                            }
                        }

                    }
                    #endregion

                    #region 运费
                    decimal Express = 0;
                    if (defModel.Id > 0 && demodel.DeliveryMethod == OrderDeliveryMethodEnum.ExpressDistribution)
                    {
                        if (!((gmodel.FullNumPinkage > 0 && item.Number >= gmodel.FullNumPinkage) || (gmodel.FullMoneyPinkage > 0 && item.Final_Price >= gmodel.FullMoneyPinkage)))
                        {
                            int FreightId2 = gmodel.FreightId ?? 0;
                            if (gmodel.FreightId == 0)
                            {
                                FreightId2 = DefFreightId;
                            }
                            if (FreightId2 > 0)
                            {
                                var rulesModel = rulesList.Where(x => x.ID == FreightId2).FirstOrDefault();
                                List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList2 = priceList.Where(x => x.RulesId == FreightId2).ToList();
                                if (priceList2.Any())
                                {
                                    var priceIds = priceList2.Select(x => x.ID).ToList();
                                    var regionList2 = regionList.Where(x => priceIds.Contains(x.RulesPriceId)).ToList();

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

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

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

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

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

                    var areaGoods = AreaList.Where(x => x.GoodsId == item.GoodsId).ToList();
                    bool address_disabled = false;
                    if (gmodel.IsAreaBuy == 1 && areaGoods.Any())
                    {
                        if (!areaGoods.Where(x => disList.Contains(x.AreaId ?? 0)).Any())
                        {
                            address_disabled = true;
                            address_enable = false;
                        }
                    }

                    goods_list.Add(new
                    {
                        id = gmodel.Id,
                        name = gmodel.Name,
                        categoryIdList = item.CategoryIdList,
                        specificationNameList = item.SpecificationNameList,
                        num = item.Number,
                        forehead_integral = gmodel.PointsDeduction,
                        forehead_integral_type = gmodel.PointsDeductionType,
                        accumulative = gmodel.IsMultipleDeduction,//累计多件抵扣
                        address_disabled,
                        pieces = gmodel.FullNumPinkage,//满件包邮
                        forehead = gmodel.FullMoneyPinkage,//满额包邮
                        freight_id = gmodel.FreightId,
                        express_price = item.Express,
                        unit_price = item.Unit_Price,
                        total_original_price = (item.Original_Price ?? 0) * (item.Number ?? 0),
                        total_price = (item.Unit_Price ?? 0) * (item.Number ?? 0),//优惠券（有平摊情况） 积分抵扣 （默认从第一个商品抵扣）
                        goods_attr = new
                        {
                            id = 0,
                            goods_id = gmodel.Id,
                            sign_id = item.SpecificationSort,
                            stock = gmodel.InventoryNum,
                            price = item.Unit_Price??0,
                            original_price = item.Original_Price ?? 0,
                            no = gmodel.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url = gmodel.CoverImage,
                            individual_share = umodel?.IsDistributor ?? 2,// 是否分销商
                            share_type = gmodel.SeparateDistributionMoneyType,//分销佣金类型,
                            member_price = item.MemberPrice,
                            integral_price = demodel.Use_Integral == 1 ? item.IntegralMoney : 0,//积分抵扣金额
                            use_integral = demodel.Use_Integral == 1 ? item.IntegralNumber : 0,
                            couponMoney,
                            //discount= [],
                            //extra= [],
                            //goods_warehouse_id = 19813,
                            name = gmodel.Name,
                            cover_pic = gmodel.CoverImage,
                            detail = gmodel.GoodsDetails,
                            pic_list = gmodel.CarouselImageList.Select(x => new
                            {
                                id = x.Id,
                                pic_url = x.Path
                            }),
                            number = item.Number,
                            goods_share_level = DistributionCommissionList.Where(x => x.GoodsId == gmodel.Id).Select(x => new
                            {
                                share_commission_first = x.OneCommission,
                                share_commission_second = x.TwoCommission,
                                share_commission_third = x.ThreeCommission,
                                level = x.DistributorGrade
                            }),
                            attr_setting_type = gmodel.SeparateDistributionType
                        },
                        attr_list = item.Attr_list,
                        discounts = item.Discounts,
                        member_discount = ((item.Unit_Price ?? 0) * (item.Number ?? 0)) - (item.MemberPrice * (item.Number ?? 0)),
                        cover_pic = gmodel.CoverImage,
                        is_level_alone = gmodel.SeparateSetMember,//是否单独设置会员价
                        //custom_currency= [],
                        is_level = gmodel.EnjoyMember,//是否销售会员价格
                        //goods_warehouse_id = 19813,
                        sign = "",
                        confine_order_count = gmodel.LimitBuyOrderNum,//限制订单数量
                        form_id = gmodel.FormsId,//表单id
                        //goodsWarehouse = new
                        //{
                        //    id = 19813,
                        //    mall_id = 1285,
                        //    name = "测试商品【勿拍】",
                        //    original_price = "100000.00",
                        //    cost_price = "0.00",
                        //    detail = "<p>测试</p>",
                        //    cover_pic = "https://cdnimg.iotweixin.com/uploads/mall1285/20200303/0729b37fd19a002733018a1ece30ca55.jpg",
                        //    pic_url = "[{\"id=\"77531\",\"pic_url=\"https:\\/\\/cdnimg.iotweixin.com\\/uploads\\/mall1285\\/20200303\\/0729b37fd19a002733018a1ece30ca55.jpg\"},{\"id=\"77530\",\"pic_url=\"https:\\/\\/cdnimg.iotweixin.com\\/uploads\\/mall1285\\/20200303\\/8eebc4fc427d7d2bbd2625f5f3448c5b.jpg\"}]",
                        //    video_url = "https://cdnimg.iotweixin.com/uploads/mall1285/20200303/5f26c823c9118e7646681152ef441fd7.mp4",
                        //    unit = "件",
                        //    created_at = "2020-05-25 16:05:02",
                        //    updated_at = "2020-05-25 16:05:02",
                        //    deleted_at = "0000-00-00 00:00:00",
                        //    is_delete = 0
                        //},
                        //form_data= null,
                        //form= null
                    });
                }
            }

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

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

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

            //minModel

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

            if (minModel != null)
            {
                if (!string.IsNullOrWhiteSpace(minModel.OrderSuccessTpl))
                {
                    template_message_list.Add(minModel.OrderSuccessTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderCancelTpl))
                {
                    template_message_list.Add(minModel.OrderCancelTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderDeliverGoodsTpl))
                {
                    template_message_list.Add(minModel.OrderDeliverGoodsTpl);
                }
            }
            var Robj = new
            {
                mch_list,
                total_price = TotalGoodsMoney,
                price_enable = true,
                address = new
                {
                    id = defModel?.Id ?? 0,
                    user_id = demodel.UserId,
                    name = defModel?.Name ?? "",
                    province_id = defModel?.Province ?? 0,
                    province = defModel?.PName ?? "",
                    city_id = defModel?.City ?? 0,
                    city = defModel?.CName ?? "",
                    district_id = defModel?.District ?? 0,
                    district = defModel?.DName ?? "",
                    mobile = defModel?.Mobile ?? "",
                    detail = defModel?.Address ?? "",
                    is_default = defModel?.IsDefault ?? 2,
                    lonlat = defModel?.Lonlat
                },
                address_enable,
                //has_ziti= false,
                //custom_currency_all= [],
                //allZiti= false,
                //hasCity= false,
                template_message_list = template_message_list //new List<string>() { "WPELErDfYO3JnizA5Zikta6Y8qrBBAgecuj2aLoucuY", "pCmTJwvTqNpyRREo7vvqIYBcrATNWoitfbLS61fLhzU", "i6QPsaOHgfNwlIRMwmvFGSCqX28g0cRa8XaLZ5_gpgc" }
            };
            #endregion
            return ApiResult.Success("", Robj);
        }

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

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

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

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

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

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

        /// <summary>
        /// 下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult SetAppletGoodsOrderInfo(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            if (umodel.Blacklist == 1)
            {
                return ApiResult.Failed("您在黑名单状态无法下单，请联系管理员核实");
            }
            List<int> disList = new List<int>();
            disList.Add(demodel.Province ?? 0);
            disList.Add(demodel.City ?? 0);
            disList.Add(demodel.District ?? 0);


            decimal TotalExpress = 0;
            decimal TotalMoney = 0;
            string GoodsIds = "";
            int TotalIntegralNumber = 0;//总使用积分
            decimal TotalIntegralMoney = 0;//总使用积分抵扣金额
            List<RB_Goods_CouponModel> GoodsCouponList = new List<RB_Goods_CouponModel>();//商品优惠卷 价格（每个商品优惠的价格）
            decimal CouponsMoney = 0;//优惠卷验证
            #region 优惠卷初始化
            List<RB_Member_DiscountCoupon_Extend> cList = new List<RB_Member_DiscountCoupon_Extend>();
            List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend> dcList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend>();
            List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend> dcpList = new List<Model.Extend.MarketingCenter.RB_DiscountCoupon_Product_Extend>();
            demodel.CouponsIds = "";
            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
            if (demodel.DetailList.Any())
            {
                //积分
                Model.Entity.MarketingCenter.RB_Integral_Settings integralModel = new Model.Entity.MarketingCenter.RB_Integral_Settings();
                if (demodel.Use_Integral == 1 && umodel.Integral > 0)
                {
                    integralModel = integral_SettingsRepository.GetIntegralSettingsList(new Model.Entity.MarketingCenter.RB_Integral_Settings() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                }
                int DefFreightId = 0;//默认运费id
                GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

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

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

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

                        #endregion
                    }
                }

                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("有商品不存在或者商品已失效");
                    }

                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();
                    item.InventoryNum = gmodel.InventoryNum ?? 0;
                    item.CostMoney = gmodel.CostPrice ?? 0;
                    item.ProductCode = gmodel.GoodsNumbers;
                    item.CategoryIdList = categoryList.Select(x => x.CategoryId ?? 0).ToList();
                    int GoodsWeight = gmodel.GoodsWeight ?? 0;//商品重量
                    #region 规格
                    //验证规格是否已失效
                    if (gmodel.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            return ApiResult.Failed("有商品已失效，请重新下单");
                        }
                        if (!speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).Any())
                        {
                            return ApiResult.Failed("有商品已失效，请重新下单");
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            return ApiResult.Failed("有商品已失效，请重新下单");
                        }
                    }

                    if (!string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        var speciPModel = speciPList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                        gmodel.SellingPrice = speciPModel?.SellingPrice ?? 0;
                        gmodel.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        GoodsWeight = speciPModel?.GoodsWeight ?? 0;
                        item.InventoryNum = speciPModel?.InventoryNum ?? 0;
                        item.SpeciPriceId = speciPModel?.Id ?? 0;
                        item.ProductCode = speciPModel?.GoodsNumbers ?? "";
                        if (item.Number > speciPModel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    else
                    {
                        if (item.Number > gmodel.InventoryNum)
                        {
                            return ApiResult.Failed("商品库存不足:" + gmodel.Name);
                        }
                    }
                    #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;
                        }
                        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.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 运费
                    decimal Express = 0;
                    if (demodel.DeliveryMethod == OrderDeliveryMethodEnum.ExpressDistribution)
                    {
                        if (!((gmodel.FullNumPinkage > 0 && item.Number >= gmodel.FullNumPinkage) || (gmodel.FullMoneyPinkage > 0 && item.Final_Price >= gmodel.FullMoneyPinkage)))
                        {
                            int FreightId2 = gmodel.FreightId ?? 0;
                            if (gmodel.FreightId == 0)
                            {
                                FreightId2 = DefFreightId;
                            }
                            if (FreightId2 > 0)
                            {
                                var rulesModel = rulesList.Where(x => x.ID == FreightId2).FirstOrDefault();
                                List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList2 = priceList.Where(x => x.RulesId == FreightId2).ToList();
                                if (priceList2.Any())
                                {
                                    var priceIds = priceList2.Select(x => x.ID).ToList();
                                    var regionList2 = regionList.Where(x => priceIds.Contains(x.RulesPriceId)).ToList();

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

                    item.FreightMoney = Express;
                    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);
                    }
                    #endregion

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

                    }
                    #endregion

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

                }
                if (demodel.User_Coupon_Id > 0 && GoodsCouponList.Any())
                {
                    decimal FinalMoney = GoodsCouponList.Sum(x => x.TotalMoney);
                    var ccmodel = cList.Where(x => x.Id == demodel.User_Coupon_Id).FirstOrDefault();
                    var dcModel = dcList.Where(x => x.ID == (ccmodel?.CouponId ?? 0)).FirstOrDefault();
                    if (dcModel == null)
                    {
                        return ApiResult.Failed("优惠卷不存在，亲核实后再试");
                    }
                    if (dcModel.MinConsumePrice > 0)
                    {
                        if (FinalMoney < dcModel.MinConsumePrice)
                        {
                            FinalMoney = 0;
                        }
                    }
                    if (dcModel.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.FullReduction && FinalMoney > 0)
                    {
                        CouponsMoney = dcModel.DiscountsPrice;
                    }
                    else if (dcModel.CouponType == Common.Enum.MarketingCenter.CouponTypeEnum.Discount && FinalMoney > 0)
                    {
                        decimal disMoney = Math.Round(FinalMoney * (10 - dcModel.DiscountsPrice) / 10, 2, MidpointRounding.AwayFromZero);
                        if (dcModel.MaxDiscountsPrice > 0 && dcModel.MaxDiscountsPrice < disMoney)
                        {
                            disMoney = dcModel.MaxDiscountsPrice;
                        }
                        CouponsMoney = disMoney;
                    }
                    //每个商品优惠券分摊金额
                    if (CouponsMoney > 0)
                    {
                        foreach (var item in GoodsCouponList)
                        {
                            item.CouponMoney = Math.Round((item.TotalMoney / FinalMoney) * CouponsMoney, 2, MidpointRounding.AwayFromZero);
                        }
                        if (CouponsMoney != GoodsCouponList.Sum(x => x.CouponMoney))
                        {
                            //四舍五入存在差值
                            decimal diffMoney = CouponsMoney - GoodsCouponList.Sum(x => x.CouponMoney);
                            var gcModel = GoodsCouponList.OrderBy(x => x.CouponMoney).Take(1).FirstOrDefault();
                            gcModel.CouponMoney += diffMoney;
                        }
                    }
                }
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        continue;
                    }
                    item.SupplierId = gmodel.SupplierId;
                    item.CouponMoney = 0;
                    var couponModel = GoodsCouponList.Where(x => x.GoodsId == item.GoodsId).FirstOrDefault();
                    if (couponModel != null)
                    {
                        item.CouponMoney = couponModel.CouponMoney;
                        TotalMoney -= (item.CouponMoney ?? 0);//总价格需减去优惠券金额
                        item.Final_Price -= (item.CouponMoney ?? 0);
                    }
                }
            }
            if (demodel.FreightMoney != TotalExpress)
            {
                return ApiResult.Failed("运费不正确");
            }
            if (CouponsMoney != demodel.CouponMoney)
            {
                return ApiResult.Failed("优惠金额计算有误");
            }
            //验证总额
            if (demodel.Income != (TotalMoney + TotalExpress))
            {
                return ApiResult.Failed("订单合计金额不正确");
            }
            demodel.PreferPrice = TotalMoney + CouponsMoney;

            var trans = goods_OrderRepository.DbTransaction;
            try
            {
                Random R = new Random();
                int Rstr = R.Next(111, 999);
                demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                demodel.PaymentWay = OrderPaymentTypeEnum.OnlinePayment;//先默认在线支付
                demodel.Remark ??= "";
                demodel.ApplyForCancelStatus ??= 0;
                int OrderId = goods_OrderRepository.Insert(demodel, trans);
                if (OrderId > 0)
                {
                    //插入订单明细+ 商品库存更新 
                    InsertOrderDetail(demodel, trans, OrderId);
                    //用户订单数增加
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Member_User_Extend.OrderNum),(umodel.OrderNum??0)+1}
                    };

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

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

                    //来自购物车的话  需清除购物车数据
                    if (demodel.IsFormShoppingCart == 1)
                    {
                        foreach (var cartItem in demodel.ShoppingCartIdList)
                        {
                            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                { nameof(RB_Goods_ShoppingCart.Status),1},
                                { nameof(RB_Goods_ShoppingCart.UpdateDate),DateTime.Now}
                            };
                            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.Id),
                                        FiledValue=cartItem,
                                        OperatorEnum=OperatorEnum.IN
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.UserId),
                                        FiledValue=demodel.UserId,
                                        OperatorEnum=OperatorEnum.IN
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.TenantId),
                                        FiledValue=demodel.TenantId,
                                        OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods_ShoppingCart.MallBaseId),
                                        FiledValue=demodel.MallBaseId,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_ShoppingCartRepository.Update(keyValues2, wheres2);
                        }
                    }
                    //下线
                    if (umodel.DownlineCondition == Common.Enum.User.DistrbutorReferralsEnum.SCXD && umodel.IsBeDownline == 2)
                    {
                        //首次下单成为下线
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            {nameof(RB_Member_User_Extend.SuperiorId),umodel.WaitSuperiorId },
                            {nameof(RB_Member_User_Extend.IsBeDownline),1 },
                            {nameof(RB_Member_User_Extend.BeDownlineDate),DateTime.Now },
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                  FiledValue=umodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        member_UserRepository.Update(keyValues1, wheres1, trans);
                    }
                    //任务执行返佣  失败查看日志，手动返佣(空闲可增加手动返佣接口)
                    Task.Run(() => InsertOrderCommission(demodel, umodel, GoodsIds, OrderId));
                    //记录日志
                    Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                    {
                        Id = 0,
                        Type = 1,
                        SourceId = OrderId,
                        Content = "新增订单",
                        CreateDate = DateTime.Now,
                        MallBaseId = demodel.MallBaseId,
                        TenantId = demodel.TenantId
                    }));
                }
                goods_OrderRepository.DBSession.Commit();
                return ApiResult.Success("", new { OrderId });
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetAppletGoodsOrderInfo");
                goods_OrderRepository.DBSession.Rollback("SetAppletGoodsOrderInfo");
                return ApiResult.Failed();
            }
        }

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

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

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

            var detList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderId });
            demodel.DetailList = detList;
            string GoodsIds = "";
            if (demodel.DetailList.Any()) {
                GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1)
                    {
                        return false;
                    }

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

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

        /// <summary>
        /// 插入返佣
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="umodel"></param>
        /// <param name="GoodsIds"></param>
        /// <param name="OrderId"></param>
        private void InsertOrderCommission(RB_Goods_Order_Extend demodel, Model.Entity.User.RB_Member_User umodel, string GoodsIds, int OrderId)
        {
            var trans = goods_OrderCommissionRepository.DbTransaction;
            try
            {
                var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                //判断是否开启和平返佣
                List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.Status),
                                FiledValue=0,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.Enabled),
                                FiledValue=1,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.TenantId),
                                FiledValue=demodel.TenantId,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission_Extend.MallBaseId),
                                FiledValue=demodel.MallBaseId,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                if (distributor_HPCommissionRepository.Exists(wheres))
                {
                    int OneUserId = umodel.SuperiorId ?? 0;
                    //获取分销商信息
                    var disModel = new RB_Distributor_Info_Extend();
                    if ((basicModel?.InPurchasing ?? 2) == 1)
                    {
                        disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = umodel.Id, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                        if (disModel != null && (disModel.HPGradeId ?? 0) > 0)
                        {
                            OneUserId = umodel.Id;//设置了分销内购   并且自己是分销商  并且设置了和平等级 ， 那么就是自购返佣
                        }
                    }
                    if (OneUserId != umodel.Id)
                    {
                        //求其上级
                        disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = OneUserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                        if (disModel != null && (disModel.HPGradeId ?? 0) > 0)
                        {
                            OneUserId = umodel.SuperiorId ?? 0;//其上级可返佣
                        }
                        else
                        {
                            OneUserId = 0;
                        }
                    }
                    if (OneUserId > 0)
                    {
                        foreach (var item in demodel.DetailList)
                        {
                            if (item.CostMoney > 0)
                            {
                                //成本价格大于0的才进行返佣
                                string categoryids = string.Join(",", item.CategoryIdList);
                                var hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIdsT = categoryids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                if (hpcList.Any())
                                {
                                    RB_Distributor_HPCommission_Extend hpcModel;
                                    if (hpcList.Where(x => x.IsCommon != 1).Any())
                                    {
                                        //有使用非通用返佣
                                        hpcModel = hpcList.Where(x => x.IsCommon != 1).FirstOrDefault();
                                    }
                                    else
                                    {
                                        //查询通用返佣
                                        hpcModel = hpcList.Where(x => x.IsCommon == 1).FirstOrDefault();
                                    }
                                    //查询所有返佣比例
                                    var gList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = hpcModel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

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

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

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

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

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

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

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

        /// <summary>
        /// 插入订单明细，以及更新商品库存
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="trans"></param>
        /// <param name="OrderId"></param>
        private void InsertOrderDetail(RB_Goods_Order_Extend demodel, System.Data.IDbTransaction trans, int OrderId)
        {
            foreach (var item in demodel.DetailList)
            {
                int IntegralPresent = item.IntegralPresent ?? 0;
                //积分
                if (item.IntegralPresent > 0)
                {
                    if (item.IntegralPresentType == 1)
                    {
                        IntegralPresent = Convert.ToInt32((item.Final_Price ?? 0) * (item.IntegralPresent ?? 0) / 100);
                    }
                }
                //插入订单明细表
                int detailId = goods_OrderDetailRepository.Insert(new RB_Goods_OrderDetail()
                {
                    Id = 0,
                    CostMoney = item.CostMoney,
                    CoverImage = item.CoverImage,
                    CreateDate = DateTime.Now,
                    DiscountRate = item.DiscountRate ?? 0,
                    Final_Price = item.Final_Price,
                    GoodsId = item.GoodsId,
                    GoodsName = item.GoodsName,
                    IsMemberPrice = item.IsMemberPrice ?? 2,
                    MallBaseId = demodel.MallBaseId,
                    Number = item.Number,
                    OrderId = OrderId,
                    OrderType = item.OrderType,
                    Original_Price = item.Original_Price,
                    ProductCode = item.ProductCode,
                    Specification = item.Specification,//前端传递过来
                    SpecificationSort = item.SpecificationSort,
                    Unit_Price = item.Unit_Price,
                    TenantId = demodel.TenantId,
                    UpdateDate = DateTime.Now,
                    IsComment = 2,
                    FreightMoney = item.FreightMoney,
                    IntegralMoney = item.IntegralMoney,
                    IntegralNumber = item.IntegralNumber,
                    CouponMoney = item.CouponMoney,
                    IntegralGoodsPresent = IntegralPresent,
                    SupplierId = item.SupplierId
                }, trans);
                item.Id = detailId;

                //更新商品数量
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Goods.InventoryNum),item.InventoryNum-(item.Number??0)}
                        };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods.Id),
                                  FiledValue=item.GoodsId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods.TenantId),
                                  FiledValue=demodel.TenantId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods.MallBaseId),
                                  FiledValue=demodel.MallBaseId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                bool flagg = goodsRepository.Update(keyValues, wheres, trans);
                if (flagg)
                {
                    if (!string.IsNullOrEmpty(item.SpecificationSort) && item.SpeciPriceId > 0)
                    {
                        //更新规格价格库存
                        Dictionary<string, object> keyValuesp = new Dictionary<string, object>() {
                                    { nameof(RB_Goods_SpecificationPrice.InventoryNum),item.InventoryNum-(item.Number??0)}
                                };
                        List<WhereHelper> wheresp = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                          FiledValue=item.SpeciPriceId,
                                           OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods_SpecificationPrice.GoodsId),
                                          FiledValue=item.GoodsId,
                                           OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.TenantId),
                                          FiledValue=demodel.TenantId,
                                           OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.MallBaseId),
                                          FiledValue=demodel.MallBaseId,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                        goods_SpecificationPriceRepository.Update(keyValuesp, wheresp, trans);
                    }
                    //记录日志
                    goods_LogRepository.Insert(new RB_Goods_Log()
                    {
                        Id = 0,
                        Type = 2,
                        SourceId = item.GoodsId,
                        Content = "新增订单，Key:" + item.SpecificationSort + "，商品库存减少:" + item.Number,
                        CreateDate = DateTime.Now,
                        MallBaseId = demodel.MallBaseId,
                        TenantId = demodel.TenantId
                    }, trans);
                }
            }
            //if (IntegralPresentTotal > 0)
            //{
            //    member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
            //    {
            //        Id = 0,
            //        CreateDate = DateTime.Now,
            //        Description = "订单购买赠送积分",
            //        Image = 0,
            //        Integral = IntegralPresentTotal,
            //        MallBaseId = demodel.MallBaseId,
            //        PlatformType = demodel.OrderSource,
            //        Remarks = "",
            //        TenantId = demodel.TenantId,
            //        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
            //        UserId = demodel.UserId,
            //        OrderId = OrderId
            //    }, trans);
            //}
        }

        /// <summary>
        /// 用户取消订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool CancelAppletGoodsOrderInfo(int orderId, int type, string remark, int userId, int tenantId, int mallBaseId)
        {
            var omodel = goods_OrderRepository.GetEntity(orderId);
            if (omodel == null)
            {
                return false;
            }
            if (type == 1)
            {
                if (omodel.OrderStatus != OrderStatusEnum.NonPayment)
                {
                    return false;
                }
            }
            else if (type == 2)
            {
                if (omodel.OrderStatus != OrderStatusEnum.WaitSendGoods)
                {
                    return false;
                }
                //物流
                var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
                if (erlist.Any())
                {
                    return false;//已有商品发货，无法退款
                }
            }
            var trans = goods_OrderRepository.DbTransaction;
            try
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
                if (type == 1)
                {
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Cancel);
                    keyValues.Add(nameof(RB_Goods_Order.CancelTime), DateTime.Now);
                }
                else
                {
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.WaitDeal);
                    keyValues.Add(nameof(RB_Goods_Order.IsApplyForCancel), 1);
                    keyValues.Add(nameof(RB_Goods_Order.HistoryOrderStatus), (int)omodel.OrderStatus);
                    keyValues.Add(nameof(RB_Goods_Order.CancelRemark), remark);
                }
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.OrderId),
                          FiledValue=orderId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.UserId),
                          FiledValue=userId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.TenantId),
                          FiledValue=tenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order.MallBaseId),
                          FiledValue=mallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = goods_OrderRepository.Update(keyValues, wheres, trans);
                if (flag)
                {
                    //回滚商品库存
                    if (type == 1)
                    {
                        int TotalIntegralNumber = 0;
                        var detailList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = omodel.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
                        if (detailList.Any())
                        {
                            string goodsIds = string.Join(",", detailList.Select(x => x.GoodsId ?? 0).Distinct());
                            var goodsList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                            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))
                                {
                                    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);
                                }
                                //更新商品表库存
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods.InventoryNum), (gmodel.InventoryNum??0)+(item.Number??0)}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                            FiledName=nameof(RB_Goods.Id),
                                            FiledValue=gmodel.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goodsRepository.Update(keyValues1, wheres1, trans);
                                goods_LogRepository.Insert(new RB_Goods_Log()
                                {
                                    Id = 0,
                                    Type = 2,
                                    SourceId = item.GoodsId,
                                    Content = $"取消订单{orderId}，还原商品库存:" + item.Number,
                                    CreateDate = DateTime.Now,
                                    MallBaseId = mallBaseId,
                                    TenantId = tenantId
                                });

                                if (item.IntegralNumber > 0)
                                {
                                    TotalIntegralNumber += (item.IntegralNumber ?? 0);
                                }
                            }
                        }
                        var umodel = member_UserRepository.GetEntity(omodel.UserId);
                        //积分抵扣回滚
                        if (TotalIntegralNumber > 0)
                        {
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User_Extend.Integral),umodel.Integral + TotalIntegralNumber}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_User_Extend.Id),
                                      FiledValue=umodel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            bool flag2 = member_UserRepository.Update(keyValues1, wheres1, trans);
                            if (flag2)
                            {
                                member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                                {
                                    Id = 0,
                                    CreateDate = DateTime.Now,
                                    Description = "订单取消返回积分抵扣，订单号：" + omodel.OrderNo,
                                    Image = 0,
                                    Integral = TotalIntegralNumber,
                                    MallBaseId = omodel.MallBaseId,
                                    PlatformType = omodel.OrderSource,
                                    Remarks = "",
                                    TenantId = omodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                    UserId = omodel.UserId,
                                    OrderId = omodel.OrderId
                                }, trans);
                            }
                        }
                        //优惠券回滚
                        if (!string.IsNullOrEmpty(omodel.CouponsIds))
                        {
                            var cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 1, Ids = omodel.CouponsIds, UserId = omodel.UserId, TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId });
                            foreach (var item in cList)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DiscountCoupon_Extend.UseState),0}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_DiscountCoupon_Extend.Id),
                                          FiledValue=item.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_CouponRepository.Update(keyValues1, wheres1, trans);
                            }
                        }
                        //余额支付回滚

                    }
                    Task.Run(() => goods_LogRepository.Insert(new RB_Goods_Log()
                    {
                        Id = 0,
                        Type = 1,
                        SourceId = orderId,
                        Content = type == 1 ? "客人取消订单" : "客人申请取消订单",
                        CreateDate = DateTime.Now,
                        MallBaseId = mallBaseId,
                        TenantId = tenantId
                    }));
                }
                goods_OrderRepository.DBSession.Commit();
                return flag;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "CancelAppletGoodsOrderInfo");
                goods_OrderRepository.DBSession.Rollback();
                return false;
            }

        }

        /// <summary>
        /// 申请售后
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetAppletMyOrderAfterSale(RB_Goods_OrderAfterSale_Extend demodel)
        {
            var dModel = goods_OrderDetailRepository.GetEntity(demodel.OrderDetialId);
            if (demodel.Type == 1 && (dModel.Final_Price ?? 0) < demodel.Refund)
            {
                return false;
            }
            demodel.Income = dModel.Final_Price;
            demodel.RefundActual ??= 0;
            demodel.Refund ??= 0;
            demodel.DeliveryId ??= 0;
            demodel.CreateDate = DateTime.Now;
            demodel.OrderId = dModel.OrderId;
            demodel.ReExpressId ??= 0;
            demodel.ReExpressNumber ??= "";
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.ReOrderNo = "RE" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;

            var oasList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = demodel.OrderDetialId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            if (oasList.Any())
            {
                return false;
            }
            int Id = goods_OrderAfterSaleRepository.Insert(demodel);
            if (Id > 0)
            {
                //流程
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "买家申请售后",
                    Type = 1,
                    ReOrderId = Id,
                    TenantId = demodel.TenantId,
                    CreateDate = DateTime.Now,
                    MallBaseId = demodel.MallBaseId
                });
                return true;
            }
            return false;
        }

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

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

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

        /// <summary>
        /// 售后买家发货
        /// </summary>
        /// <param name="reOrderId"></param>
        /// <param name="expressId"></param>
        /// <param name="expressNumber"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetAppletOrderSendGoods(int reOrderId, int expressId, string expressNumber, int tenantId, int mallBaseId)
        {
            var omodel = goods_OrderAfterSaleRepository.GetEntity(reOrderId);
            if (omodel == null)
            {
                return false;
            }
            if (omodel.ReOrderStatus != OrderAfterSaleStatusEnum.DeliveryToBuyer)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_OrderAfterSale.ReOrderStatus),OrderAfterSaleStatusEnum.ReceivedBySeller},
                { nameof(RB_Goods_OrderAfterSale.ReExpressId),expressId},
                { nameof(RB_Goods_OrderAfterSale.ReExpressNumber),expressNumber},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                      FiledValue=reOrderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            return goods_OrderAfterSaleRepository.Update(keyValues, wheres);
        }

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

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


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

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

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

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

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

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

                //收货  自动确认订单
                SetOrderOperation(omodel.RefMapperTo<RB_Goods_Order_Extend>(), 6, "", 0, "", tenantId, mallBaseId);
            }
            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_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                        item.IsBindExpress = erList.Where(x => x.OrderDetailId == item.Id).Any() ? 1 : 2;
                    }
                }
                string areaIds1 = string.Join(",", list.Select(x => x.Province ?? 0).Distinct());
                string areaIds2 = string.Join(",", list.Select(x => x.City ?? 0).Distinct());
                string areaIds3 = string.Join(",", list.Select(x => x.District ?? 0).Distinct());
                string areaIds = "0";
                if (!string.IsNullOrEmpty(areaIds1))
                {
                    areaIds += "," + areaIds1;
                }
                if (!string.IsNullOrEmpty(areaIds2))
                {
                    areaIds += "," + areaIds2;
                }
                if (!string.IsNullOrEmpty(areaIds3))
                {
                    areaIds += "," + areaIds3;
                }
                var arealist = destinationRepository.GetDictvalueListForIds(areaIds);
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                    item.DistrictAddress = (arealist.Where(x => x.ID == item.Province).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.City).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.District).FirstOrDefault()?.Name ?? "");
                }
            }
            return list;
        }

        /// <summary>
        /// 获取分销订单
        /// </summary>
        /// <param name="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);
                    }
                    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 ?? "暂无等级";
                        }
                    }
                }
                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_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);
                }

                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 ?? "暂无等级";
                    }
                }
            }

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

                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 ?? "暂无等级";
                    }
                }
            }

            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()) });
                    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.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.Type == 1)
                {
                    var leModel = logistics_ExpressRepository.GetEntity(oeModel.ExpressId);
                    ExpressList.Add(new
                    {
                        Name = uModel.Name ?? "",
                        ExpressName = leModel.Name ?? "",
                        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)
                {
                    OrderRefundFinanceModule(model, tenantId, mallBaseId);
                }
                goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                {
                    Id = 0,
                    Content = "卖家确认收货",
                    CreateDate = DateTime.Now,
                    MallBaseId = mallBaseId,
                    ReOrderId = reOrderId,
                    TenantId = tenantId,
                    Type = 2
                });
                return ApiResult.Success();
            }
            return ApiResult.Failed();
        }

        /// <summary>
        /// 生成退款单据
        /// </summary>
        /// <returns></returns>
        public bool OrderRefundFinanceModule(RB_Goods_OrderAfterSale dmodel, int TenantId, int MallBaseId)
        {
            var flag = false;
            try
            {
                decimal Money = dmodel.Refund ?? 0;
                decimal Rate = Convert.ToDecimal(Config.SettlementRate);
                decimal Fee = 0;
                if (Rate > 0)
                {
                    Fee = Math.Round(Money * Rate / 1000, 2, MidpointRounding.AwayFromZero);
                    Money -= Fee;
                }
                //查询用户
                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)+"，手续费:"+ Fee;
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    var detailList = new List<object>() {
                        new
                        {
                            CostTypeId = item.RefundCostTypeId,
                            Number = 1,
                            OriginalMoney = Money,
                            UnitPrice = Money,
                            Remark = "订单号：" + omodel.OrderNo + "售后单号：" + (dmodel.ReOrderNo ?? "暂无") + "   " + dstr
                        }
                    };

                    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 = 12,
                        ReFinanceId = dmodel.ReOrderId,
                        Remark = "名称:" + umodel.Name + "(" + umodel.Id + ")" + "   " + System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                        detailList
                    };
                    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()}
                        };
                        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(int reOrderId, decimal refund, string RefundOrderNo, int tenantId, int mallBaseId)
        {

            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

                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>
        /// 售后订单  发货
        /// </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>
        public string SetOrderSendGoods(RB_Goods_OrderExpress_Extend demodel)
        {
            var trans = goods_OrderExpressRepository.DbTransaction;
            try
            {
                if (demodel.Id > 0)
                {
                    var omodel = goods_OrderRepository.GetEntity(demodel.OrderId);
                    if (omodel == null)
                    {
                        return "订单不存在";
                    }
                    if (omodel.OrderStatus >= Common.Enum.Goods.OrderStatusEnum.Received)
                    {
                        return "已收货无法修改物流信息";
                    }
                    //修改物流信息
                    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, trans);
                    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
                        }, trans);
                    }
                    goods_OrderExpressRepository.DBSession.Commit();
                    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())
                    {
                        return "传递的订单明细Id有误，请核实后再试";
                    }
                    //验证商品是否已创建快递信息
                    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())
                        {
                            return "传递的订单明细Id:" + item + ",已绑定物流信息无法再次绑定";
                        }
                    }
                    int Id = goods_OrderExpressRepository.Insert(demodel, trans);
                    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
                            }, trans);
                        }
                        goods_LogRepository.Insert(new RB_Goods_Log()
                        {
                            Content = "新增快递信息",
                            CreateDate = demodel.CreateDate,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            SourceId = demodel.OrderId,
                            TenantId = demodel.TenantId,
                            Type = 1
                        }, trans);
                        //判断商品是否已全部绑定快递， 是的话需要更新商品状态为已发货
                        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, trans);
                            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
                                }, trans);
                            }

                            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);
                            }
                        }
                    }
                    goods_OrderExpressRepository.DBSession.Commit();
                    return Id > 0 ? "" : "保存失败";
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "");
                goods_OrderExpressRepository.DBSession.Rollback();
                return "保存失败";
            }

        }

        /// <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>
        /// <returns></returns>
        public bool SetOrderApplyForCancelAudit(RB_Goods_Order_Extend omodel, int type, string remark, string RefundOrderNo, int tenantId, int mallBaseId)
        {
            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.ApplyForCancelStatus), 1);
                    keyValues.Add(nameof(RB_Goods_Order.RefundOrderNo), RefundOrderNo);
                }
                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);
                    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)
                {
                    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.GetList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                            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))
                                {
                                    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);
                                }
                                //更新商品表库存
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods.InventoryNum), (gmodel.InventoryNum??0)+(item.Number??0)}
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_Goods.Id),
                                                FiledValue=gmodel.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                goodsRepository.Update(keyValues1, wheres1, trans);
                                goods_LogRepository.Insert(new RB_Goods_Log()
                                {
                                    Id = 0,
                                    Type = 2,
                                    SourceId = item.GoodsId,
                                    Content = $"同意客人申请取消订单{omodel.OrderId}，还原商品库存:" + item.Number,
                                    CreateDate = DateTime.Now,
                                    MallBaseId = mallBaseId,
                                    TenantId = tenantId
                                });

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

                        var umodel = member_UserRepository.GetEntity(omodel.UserId);
                        //积分抵扣回滚
                        if (TotalIntegralNumber > 0)
                        {
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User_Extend.Integral),umodel.Integral + TotalIntegralNumber}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_User_Extend.Id),
                                      FiledValue=umodel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            bool flag2 = member_UserRepository.Update(keyValues1, wheres1, trans);
                            if (flag2)
                            {
                                member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                                {
                                    Id = 0,
                                    CreateDate = DateTime.Now,
                                    Description = "订单取消返回积分抵扣，订单号：" + omodel.OrderNo,
                                    Image = 0,
                                    Integral = TotalIntegralNumber,
                                    MallBaseId = omodel.MallBaseId,
                                    PlatformType = omodel.OrderSource,
                                    Remarks = "",
                                    TenantId = omodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                    UserId = omodel.UserId,
                                    OrderId = omodel.OrderId
                                }, trans);
                            }
                        }
                        //优惠券回滚
                        if (!string.IsNullOrEmpty(omodel.CouponsIds))
                        {
                            var cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 1, Ids = omodel.CouponsIds, UserId = omodel.UserId, TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId });
                            foreach (var item in cList)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Member_DiscountCoupon_Extend.UseState),0}
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_DiscountCoupon_Extend.Id),
                                          FiledValue=item.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_CouponRepository.Update(keyValues1, wheres1, trans);
                            }
                        }
                        //余额支付回滚

                        string goodsName = detailList.FirstOrDefault().GoodsName;
                        if (detailList.Count > 1)
                        {
                            if (goodsName.Length > 6)
                            {
                                goodsName = goodsName.Substring(0, 6);
                            }
                            goodsName += "等" + detailList.Count + "件";
                        }
                        else
                        {
                            if (goodsName.Length > 10)
                            {
                                goodsName = goodsName.Substring(0, 10);
                            }
                        }
                        new MiniProgramMsgModule().SendOrderCancelMsg(tenantId, mallBaseId, umodel.OpenId, omodel.OrderNo, "订单已取消", (omodel.Income ?? 0).ToString(), goodsName);
                    }
                    //记录日志
                    string Content = $"客人申请取消订单，审核：{(type == 1 ? "同意" : "拒绝")}";
                    if (type == 2)
                    {
                        Content += "，拒绝理由：" + remark;
                    }
                    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) {
                    //同意 创建财务单据
                    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>
        /// <returns></returns>
        public bool SetOrderForcedToCancel(RB_Goods_Order_Extend omodel, string RefundOrderNo, int tenantId, int mallBaseId)
        {
            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.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.GetList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                        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))
                            {
                                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);
                            }
                            //更新商品表库存
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods.InventoryNum), (gmodel.InventoryNum??0)+(item.Number??0)}
                                };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                            FiledName=nameof(RB_Goods.Id),
                                            FiledValue=gmodel.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                            goodsRepository.Update(keyValues1, wheres1, trans);
                            goods_LogRepository.Insert(new RB_Goods_Log()
                            {
                                Id = 0,
                                Type = 2,
                                SourceId = item.GoodsId,
                                Content = $"后台强制取消订单{omodel.OrderId}，还原商品库存:" + item.Number,
                                CreateDate = DateTime.Now,
                                MallBaseId = mallBaseId,
                                TenantId = tenantId
                            });

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

                    var umodel = member_UserRepository.GetEntity(omodel.UserId);
                    //积分抵扣回滚
                    if (TotalIntegralNumber > 0)
                    {
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Member_User_Extend.Integral),umodel.Integral + TotalIntegralNumber}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Member_User_Extend.Id),
                                    FiledValue=umodel.Id,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag2 = member_UserRepository.Update(keyValues1, wheres1, trans);
                        if (flag2)
                        {
                            member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                            {
                                Id = 0,
                                CreateDate = DateTime.Now,
                                Description = "订单取消返回积分抵扣，订单号：" + omodel.OrderNo,
                                Image = 0,
                                Integral = TotalIntegralNumber,
                                MallBaseId = omodel.MallBaseId,
                                PlatformType = omodel.OrderSource,
                                Remarks = "",
                                TenantId = omodel.TenantId,
                                Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                UserId = omodel.UserId,
                                OrderId = omodel.OrderId
                            }, trans);
                        }
                    }
                    //优惠券回滚
                    if (!string.IsNullOrEmpty(omodel.CouponsIds))
                    {
                        var cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 1, Ids = omodel.CouponsIds, UserId = omodel.UserId, TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId });
                        foreach (var item in cList)
                        {
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_DiscountCoupon_Extend.UseState),0}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Member_DiscountCoupon_Extend.Id),
                                        FiledValue=item.Id,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            member_CouponRepository.Update(keyValues1, wheres1, trans);
                        }
                    }
                    //余额支付回滚

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

                    //记录日志
                    string Content = $"后台强制取消订单";
                    goods_LogRepository.Insert(new RB_Goods_Log()
                    {
                        Content = Content,
                        CreateDate = DateTime.Now,
                        Id = 0,
                        MallBaseId = mallBaseId,
                        SourceId = omodel.OrderId,
                        TenantId = tenantId,
                        Type = 1
                    });
                }
                goods_OrderRepository.DBSession.Commit();
                if (flag && tenantId == 1)
                {
                    //同意 创建财务单据
                    OrderRefundFinanceModule(omodel, true);
                }
                return flag;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "");
                goods_OrderRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 生成退款单据
        /// </summary>
        /// <param name="omodel"></param>
        /// <returns></returns>
        public bool OrderRefundFinanceModule(RB_Goods_Order_Extend omodel, bool IsForcedToCancel = false)
        {
            var flag = false;
            try
            {
                decimal Rate = Convert.ToDecimal(Config.SettlementRate);
                decimal Money = omodel.Income ?? 0;
                decimal Fee = 0;
                if (Rate > 0) {
                    Fee = Math.Round(Money * Rate / 1000, 2, MidpointRounding.AwayFromZero);
                    Money -= Fee;
                }
                //查询用户
                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) + "，手续费:" + Fee;
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    var detailList = new List<object>() {
                        new
                        {
                            CostTypeId = item.RefundCostTypeId,
                            Number = 1,
                            OriginalMoney = Money,
                            UnitPrice = Money,
                            Remark = "订单号：" + omodel.OrderNo  + "   " + dstr
                        }
                    };

                    item.IsPublic = 8;//默认原路退款
                    string Remark = "名称:" + umodel.Name + "(" + umodel.Id + ")" + "     " + System.DateTime.Now.ToString("yyyy年MM月dd日") + " 自动生成财务单据";
                    if (IsForcedToCancel) {
                        Remark = "后台强制取消该订单，用户名称:" + umodel.Name + "(" + umodel.Id + ")" + "     " + System.DateTime.Now.ToString("yyyy年MM月dd日") + " 自动生成财务单据";
                    }
                    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 = 14,
                        ReFinanceId = omodel.OrderId,
                        Remark = Remark,
                        detailList
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign
                    };

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

                LogHelper.Write(ex);
            }

            return flag;
        }

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

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

        /// <summary>
        /// 设置订单操作
        /// </summary>
        /// <param name="orderModel"></param>
        /// <param name="type">类型  1修改备注  2修改金额  3强制取消  4放入回收站  5确认收货  6确认完成  7回收恢复 8回收删除</param>
        /// <param name="remark"></param>
        /// <param name="income"></param>
        /// <param name="address"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetOrderOperation(RB_Goods_Order_Extend orderModel, int type, string remark, decimal income, string address, int tenantId, int mallBaseId)
        {
            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.Any())
                        {
                            foreach (var item in ocList)
                            {
                                //查询是否有申请退款
                                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 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
                            });
                        }
                    }
                }
                else if (type == 3)
                {
                    //强制取消 (作废  使用新方法)

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



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

        /// <summary>
        /// 根据订单好获取物流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 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())
            {
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsBindExpress = erList.Where(x => x.OrderDetailId == item.Id).Any() ? 1 : 2;
                }
            }
            model.DetailList = dlist;
            //地址
            model.DistrictAddress = (destinationRepository.GetEntity(model.Province)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.City)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.District)?.Name ?? "");
            //物流
            var erlist = goods_ExpressRelevanceRepository.GetList(new RB_Goods_ExpressRelevance_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            List<RB_Goods_OrderExpress_Extend> oeList = new List<RB_Goods_OrderExpress_Extend>();
            if (erlist.Any())
            {
                oeList = goods_OrderExpressRepository.GetList(new RB_Goods_OrderExpress_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderExpressIds = string.Join(",", erlist.Select(x => x.OrderExpressId)) });
                foreach (var item in oeList)
                {
                    item.ExpressName = logistics_ExpressRepository.GetEntity(item.ExpressId)?.Name ?? "";
                }
            }

            //获取返佣列表
            var ocList = goods_OrderCommissionRepository.GetListGroupByUser(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId }).OrderBy(x => x.Grade).ToList();
            if (ocList.Any())
            {
                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 ?? "";
                }
            }

            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.CouponMoney,
                model.FreightMoney,
                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,
                    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.UserName,
                    x.Mobile,
                    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
                })
            });
        }

        /// <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="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<int> CarouselIdList = JsonConvert.DeserializeObject<List<int>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = material_InfoRepository.GetEntity(CarouselIdList[0])?.Path ?? "";
                    }
                    //评论图片
                    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_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;
            if (demodel.OrderDetailId > 0)
            {
                var dmodel = goods_OrderDetailRepository.GetEntity(demodel.OrderDetailId);
                if (dmodel == null) { return false; }
                OrderId = dmodel.OrderId ?? 0;
                if (dmodel.IsComment == 1) { return false; }
                omodel = goods_OrderRepository.GetEntity(OrderId);
                if (omodel == null) { return false; }
                if (omodel.OrderStatus != OrderStatusEnum.Received) { return false; }
            }
            bool flag = goods_CommentRepository.Insert(demodel) > 0;
            if (flag)
            {
                if (demodel.OrderDetailId > 0)
                {
                    //更新订单商品为已评价
                    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);
                    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="goodsId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletGoodsCommentStatistics(int goodsId, int tenantId, int mallBaseId)
        {
            var list = EnumHelper.GetEnumList(typeof(GoodsCommentTypeEnum));
            var clist = goods_CommentRepository.GetAppletGoodsCommentStatistics(goodsId, tenantId, mallBaseId);
            List<object> RList = new List<object>();
            foreach (var item in list)
            {
                var cmodel = clist.Where(x => (int)x.CommentGrade == Convert.ToInt32(item.Value)).FirstOrDefault();
                RList.Add(new
                {
                    Id = Convert.ToInt32(item.Value),
                    Name = item.Key,
                    Count = cmodel?.CommentNum ?? 0
                });
            }
            return ApiResult.Success("", new
            {
                TotalNum = clist.Sum(x => x.CommentNum),
                List = RList
            });
        }

        #endregion

        #region 订单批量发货

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

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

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

        #region 查询物流

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

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

        #endregion

        #region 赞羊订单导入

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

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

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

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

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

                    #region 去除/t

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

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

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

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

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



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

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

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

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

        #region 快递公司
        #region 快递公司
        /// <summary>
        /// 快递公司列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<Model.Entity.BaseSetUp.RB_Logistics_Express> GetLogisticsExpressList(Model.Entity.BaseSetUp.RB_Logistics_Express query)
        {
            return logistics_ExpressRepository.GetLogisticsExpressList(query);
        }
        #endregion
        #endregion

        #region 供应商订单商品信息
        /// <summary>
        /// 获取订单商品分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="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> GetOrderDetailList(RB_Goods_OrderDetail_Extend dmodel)
        {
            return goods_OrderDetailRepository.GetOrderDetailList(dmodel);
        }
            #endregion
        }
}
