using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.User;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Product;
using Mall.Repository.User;
using Newtonsoft.Json;

namespace Mall.Module.Product
{
    /// <summary>
    /// 商品处理层
    /// </summary>
    public class ProductModule
    {
        /// <summary>
        /// 素材分组
        /// </summary>
        private readonly RB_Material_GroupRepository material_GroupRepository = new RB_Material_GroupRepository();
        /// <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_Product_CategoryStyleRepository product_CategoryStyleRepository = new RB_Product_CategoryStyleRepository();
        /// <summary>
        /// 商品规格
        /// </summary>
        private readonly RB_Product_SpecificationRepository product_SpecificationRepository = new RB_Product_SpecificationRepository();
        /// <summary>
        /// 快速购买
        /// </summary>
        private readonly RB_Product_QuickBuyRepository product_QuickBuyRepository = new RB_Product_QuickBuyRepository();
        /// <summary>
        /// 推荐设置
        /// </summary>
        private readonly RB_Product_RecommendRepository product_RecommendRepository = new RB_Product_RecommendRepository();
        /// <summary>
        /// 商品服务
        /// </summary>
        private readonly RB_Product_ServiceRepository product_ServiceRepository = new RB_Product_ServiceRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 商品区域
        /// </summary>
        private readonly RB_Goods_AreaRepository goods_AreaRepository = new RB_Goods_AreaRepository();
        /// <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_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();
        /// <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_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <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 Mall.Repository.User.RB_MiniProgramRepository programRepository = new Repository.User.RB_MiniProgramRepository();
        /// <summary>
        /// 商品收藏
        /// </summary>
        private readonly RB_Member_CollectionRepository member_CollectionRepository = new RB_Member_CollectionRepository();
        /// <summary>
        /// 收货地址
        /// </summary>
        private readonly RB_Member_ShippingAddressRepository member_ShippingAddressRepository = new RB_Member_ShippingAddressRepository();
        /// <summary>
        /// 订单商品
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 地区处理
        /// </summary>
        private readonly Rb_destinationRepository destinationRepository = new Rb_destinationRepository();

        /// <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_MiniProgram_GoodPosterRepository miniProgram_GoodPosterRepository = new RB_MiniProgram_GoodPosterRepository();
        /// <summary>
        /// 商品代理
        /// </summary>
        private readonly RB_Goods_ProxyRepository goods_ProxyRepository = new RB_Goods_ProxyRepository();




        #region 小程序接口

        /// <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="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
            }
            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_Extend> GetAppletGoodsPageListForZY(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                var SpecificationList = new List<RB_Goods_Specification_Extend>();
                var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (list.Where(x => x.IsCustomSpecification == 1).Any())
                {
                    string goodsIds = string.Join(",", list.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (SpecificationList.Any())
                    {
                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        foreach (var item in svlist)
                        {
                            item.ImagePath = item.Image;
                        }
                        foreach (var item in SpecificationList)
                        {
                            item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                        }
                    }
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                //会员价格
                var MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
                if (list.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Any())
                {
                    string goodsIds = string.Join(",", list.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Select(x => x.Id));
                    MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                string goodsIds2 = string.Join(",", list.Select(x => x.Id));
                List<RB_Goods_Order_Extend> orderlist = goods_OrderRepository.GetGoodsOrderNum(goodsIds: goodsIds2);
                foreach (var item in list)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = SpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                    }
                    if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                    {
                        item.MemberPriceList = MemberPriceList.Where(x => x.GoodsId == item.Id).ToList();
                    }

                    item.SalesNum += (orderlist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取商品推荐列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="RecommendStatus"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsRecommendList(int pageIndex, int pageSize, out int RecommendStatus, RB_Goods_Extend demodel)
        {
            var rmodel = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            RecommendStatus = 2;
            if (rmodel == null)
            {
                return new List<RB_Goods_Extend>();
            }
            pageSize = rmodel.DetailRecommendNum ?? 0;
            if (demodel.RecommendType == 1)
            {
                RecommendStatus = rmodel.DetailRecommendStatus ?? 2;
                if (rmodel.DetailRecommendStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
            }
            else if (demodel.RecommendType == 2)
            {
                RecommendStatus = rmodel.OrderCompleteStatus ?? 2;
                if (rmodel.OrderCompleteStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsOrderRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.OrderProductIds))
                    {
                        demodel.GoodsIds = rmodel.OrderProductIds;
                    }
                }
            }
            else if (demodel.RecommendType == 3)
            {
                RecommendStatus = rmodel.CommentRecommentStatus ?? 2;
                if (rmodel.CommentRecommentStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsCommentRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.CommentProductIds))
                    {
                        demodel.GoodsIds = rmodel.CommentProductIds;
                    }
                }
            }
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);

            List<RB_Goods_Extend> RList = list;
            if (list.Any())
            {
                if (demodel.RecommendType == 2 && rmodel.IsOrderRecommend == 1 && !string.IsNullOrEmpty(rmodel.OrderProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.OrderProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }

                }
                else if (demodel.RecommendType == 3 && rmodel.IsCommentRecommend == 1 && !string.IsNullOrEmpty(rmodel.CommentProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.CommentProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }
                }
                foreach (var item in RList)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
            }
            return RList;
        }

        /// <summary>
        /// 获取商品推荐列表(赞羊字段)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="RecommendStatus"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsRecommendListForZY(int pageIndex, int pageSize, out int RecommendStatus, RB_Goods_Extend demodel)
        {
            var rmodel = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            RecommendStatus = 2;
            if (rmodel == null)
            {
                return new List<RB_Goods_Extend>();
            }
            pageSize = rmodel.DetailRecommendNum ?? 0;
            if (demodel.RecommendType == 1)
            {
                RecommendStatus = rmodel.DetailRecommendStatus ?? 2;
                if (rmodel.DetailRecommendStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
            }
            else if (demodel.RecommendType == 2)
            {
                RecommendStatus = rmodel.OrderCompleteStatus ?? 2;
                if (rmodel.OrderCompleteStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsOrderRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.OrderProductIds))
                    {
                        demodel.GoodsIds = rmodel.OrderProductIds;
                    }
                }
            }
            else if (demodel.RecommendType == 3)
            {
                RecommendStatus = rmodel.CommentRecommentStatus ?? 2;
                if (rmodel.CommentRecommentStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsCommentRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.CommentProductIds))
                    {
                        demodel.GoodsIds = rmodel.CommentProductIds;
                    }
                }
            }
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);

            List<RB_Goods_Extend> RList = list;
            if (list.Any())
            {
                if (demodel.RecommendType == 2 && rmodel.IsOrderRecommend == 1 && !string.IsNullOrEmpty(rmodel.OrderProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.OrderProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }

                }
                else if (demodel.RecommendType == 3 && rmodel.IsCommentRecommend == 1 && !string.IsNullOrEmpty(rmodel.CommentProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.CommentProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }
                }


                var SpecificationList = new List<RB_Goods_Specification_Extend>();
                var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (RList.Where(x => x.IsCustomSpecification == 1).Any())
                {
                    string goodsIds = string.Join(",", RList.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (SpecificationList.Any())
                    {
                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        foreach (var item in svlist)
                        {
                            item.ImagePath = item.Image;
                        }
                        foreach (var item in SpecificationList)
                        {
                            item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                        }
                    }
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                //会员价格
                var MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
                if (RList.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Any())
                {
                    string goodsIds = string.Join(",", RList.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Select(x => x.Id));
                    MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                string goodsIds2 = string.Join(",", RList.Select(x => x.Id));
                List<RB_Goods_Order_Extend> orderlist = goods_OrderRepository.GetGoodsOrderNum(goodsIds: goodsIds2);

                foreach (var item in RList)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = SpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                    }
                    if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                    {
                        item.MemberPriceList = MemberPriceList.Where(x => x.GoodsId == item.Id).ToList();
                    }

                    item.SalesNum += (orderlist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0);
                }
            }
            return RList;
        }

        /// <summary>
        /// 获取小程序商品详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="UserId"></param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public RB_Goods_Extend GetAppletGoodsInfo(int goodsId, int UserId, int TenantId, int MallBaseId)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            //小程序名称
            model.MallName = programRepository.GetEntity(model.MallBaseId)?.MallName ?? "";

            #region 基本信息
            //查询分类
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            //最大售价
            decimal MaxSellMoney = model.SellingPrice ?? 0;
            model.SpecificationList = new List<RB_Goods_Specification_Extend>();
            model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (model.IsCustomSpecification == 1)
            {
                model.SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.SpecificationList.Any())
                {
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in svlist)
                    {
                        item.ImagePath = item.Image;
                    }
                    foreach (var item in model.SpecificationList)
                    {
                        item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                    }
                }
                model.SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                MaxSellMoney = model.SpecificationPriceList.Max(x => x.SellingPrice ?? 0);
            }
            //区域
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //返佣
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //会员价格
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //轮播
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }

            model.CustomShareImagePath = model.CustomShareImage;

            //服务列表
            model.ServiceList = new List<RB_ImageCommonModel>();
            if (model.IsDefaultService == 2)
            {
                if (!string.IsNullOrEmpty(model.GoodsService) && model.GoodsService != "[]")
                {
                    List<int> ServiceIds = JsonConvert.DeserializeObject<List<int>>(model.GoodsService);
                    var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { ServiceIds = string.Join(",", ServiceIds), TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in slist)
                    {
                        model.ServiceList.Add(new RB_ImageCommonModel()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
            }
            else if (model.IsDefaultService == 1)
            {
                var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in slist)
                {
                    model.ServiceList.Add(new RB_ImageCommonModel()
                    {
                        Id = item.Id,
                        Name = item.Name
                    });
                }
            }
            //表单
            if (model.FormsId > 0)
            {
                model.FormsName = "未建表";
            }
            else
            {
                model.FormsName = "默认表单";
            }
            #endregion

            #region 是否收藏
            model.Favorite = false;
            if (UserId > 0)
            {
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.UserId),
                      FiledValue=UserId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.GoodsId),
                      FiledValue=goodsId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.TenantId),
                      FiledValue=TenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.MallBaseId),
                      FiledValue=MallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                },
            };
                if (member_CollectionRepository.Exists(wheres))
                {
                    model.Favorite = true;
                }
            }
            #endregion

            #region 快递费用
            //运费
            Model.Entity.BaseSetUp.RB_Logistics_Rules rulesModel = new Model.Entity.BaseSetUp.RB_Logistics_Rules();
            if (model.FreightId > 0)
            {
                rulesModel = logistics_RulesRepository.GetEntity(model.FreightId);
                model.FreightName = rulesModel?.RulesName ?? "";
            }
            else
            {
                model.FreightName = "默认运费";
            }
            model.Express = 0;
            if (UserId > 0 && model.FreightId >= 0)
            {
                int FreightId = 0;
                if (model.FreightId == 0)
                {
                    //查询默认
                    FreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault()?.ID ?? 0;
                }
                if (FreightId > 0)
                {
                    var samodel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, IsDefault = 1 }).FirstOrDefault();
                    List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, RulesId = FreightId });
                    if (priceList.Any() && samodel != null)
                    {
                        string priceIds = string.Join(",", priceList.Select(x => x.ID));
                        var regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, PriceIds = priceIds });
                        List<int> disList = new List<int>();
                        disList.Add(samodel.Province ?? 0);
                        disList.Add(samodel.City ?? 0);
                        disList.Add(samodel.District ?? 0);
                        var regionModel = regionList.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                        if (regionModel != null)
                        {
                            var pmodel = priceList.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                            if (pmodel != null && rulesModel != null)
                            {
                                if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                {
                                    model.Express = pmodel.FirstPrice;
                                }
                                else
                                {
                                    //重量计费
                                    int TotalW = model.GoodsWeight ?? 0;
                                    if (TotalW <= pmodel.First)
                                    {
                                        model.Express = pmodel.FirstPrice;
                                    }
                                    else
                                    {
                                        if (pmodel.Second > 0)
                                        {
                                            if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                            }
                                            else
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                            }
                                        }
                                        else
                                        {
                                            model.Express = pmodel.FirstPrice;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最高返佣
            model.MaxShare = 0;
            if (UserId > 0)
            {
                //获取分销商信息
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                if (disModel != null)
                {
                    //判断是否开启和平返佣
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.Status),
                                FiledValue=0,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.Enabled),
                                FiledValue=1,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.TenantId),
                                FiledValue=TenantId,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.MallBaseId),
                                FiledValue=MallBaseId,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    if (distributor_HPCommissionRepository.Exists(wheres))
                    {
                        //获取和平分销返佣
                        if (disModel.HPGradeId > 0 && model.CostPrice > 0)
                        {
                            string categoryids = string.Join(",", model.CategoryList.Select(x => x.CategoryId));
                            var hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIdsT = categoryids, TenantId = TenantId, MallBaseId = 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 = TenantId, MallBaseId = MallBaseId });

                                var ratioModel = gList.Where(x => x.GradeId == disModel.HPGradeId).FirstOrDefault();
                                decimal MPrice = (model.CostPrice ?? 0) / (1 - ((ratioModel.CommissionRatio ?? 0) / 100));
                                model.MaxShare = MaxSellMoney - MPrice > 0 ? MaxSellMoney - MPrice : 0;
                                if (hpcModel.DecimalType == 1)
                                {
                                    model.MaxShare = Math.Ceiling(model.MaxShare);
                                }
                                else if (hpcModel.DecimalType == 2)
                                {
                                    model.MaxShare = Math.Ceiling(model.MaxShare * 100) / 100;
                                }
                            }
                        }
                    }
                    else
                    {
                        var BasicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                        if (model.SeparateDistribution == 1)
                        {
                            var dcList = model.DistributionCommissionList.Where(x => x.DistributorGrade == disModel.GradeId).ToList();
                            if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                            {
                                model.MaxShare = dcList.Max(x => (x.OneCommission ?? 0) + (x.TwoCommission ?? 0) + (x.ThreeCommission ?? 0));
                            }
                            else
                            {
                                model.MaxShare = dcList.Max(x => x.OneCommission ?? 0);
                            }
                            // 这里需注意，可能需要分销 是否提所有返佣控制
                            if (model.SeparateDistributionMoneyType == 1)
                            {
                                model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        else
                        {
                            if (disModel.GradeId == 0)
                            {
                                //拿分销基础配置
                                if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                {
                                    model.MaxShare = (BasicsModel?.OneCommission ?? 0) + (BasicsModel?.TwoCommission ?? 0) + (BasicsModel?.ThreeCommission ?? 0);
                                }
                                else
                                {
                                    model.MaxShare = BasicsModel?.OneCommission ?? 0;
                                }
                                if ((BasicsModel?.DistributorCommissionType ?? 2) == 1)
                                {
                                    model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            else if (disModel.GradeId > 0)
                            {
                                //获取分销商等级
                                var disgradeModel = distributor_GradeRepository.GetEntity(disModel.GradeId);
                                if (disgradeModel != null)
                                {
                                    if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                    {
                                        model.MaxShare = (disgradeModel?.OneCommission ?? 0) + (disgradeModel?.TwoCommission ?? 0) + (disgradeModel?.ThreeCommission ?? 0);
                                    }
                                    else
                                    {
                                        model.MaxShare = disgradeModel?.OneCommission ?? 0;
                                    }
                                    if ((disgradeModel?.DistributionCommissionType ?? 2) == 1)
                                    {
                                        model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion
            return model;
        }

        /// <summary>
        /// 获取商品分享
        /// </summary>
        /// <returns></returns>
        public object GetAppletGoodsShareInfo(int goodsId, int userId, string path, int mallBaseId)
        {
            string QRPath = GetWeiXinQRCode(path, 430, mallBaseId);
            var umodel = member_UserRepository.GetEntity(userId);
            var goodsModel = goodsRepository.GetEntity(goodsId);
            //商品海报配置信息
            var config = new object();
            //商品信息
            var info = new object();
            var goodsPoster = miniProgram_GoodPosterRepository.GetEntityExtRepository(new RB_MiniProgram_GoodPoster_Extend() { MallBaseId = mallBaseId });
            config = new
            {
                poster_style = goodsPoster?.PosterStyleList ?? new List<int>() { 1 },
                image_style = goodsPoster?.GoodsImgCountList ?? new List<int>() { 1 },
                color = new List<string>()
                {
                 "#fc4a3b",
                 "#ff7b22",
                 "#ffc73f",
                 "#3e9b6a",
                 "#4bb1ff",
                 "#8548ef",
                 "#000000",
                 "#a0a0a0",
                 "#FFFFFF"
                }
            };
            if (goodsModel == null)
            {
                info = new
                {
                    goods_name = "",
                    multi_map = new List<string>(),
                    is_negotiable = 0,
                    min_price = 0,
                    max_price = 0,
                    nickname = umodel?.Name ?? "",
                    avatar = umodel?.Photo ?? "",
                    qrcode_url = QRPath,
                    sign = ""
                };
            }
            else
            {
                //商品图片处理
                var imgList = new List<string>();
                if (!string.IsNullOrEmpty(goodsModel.CarouselImage) && goodsModel.CarouselImage != "[]")
                {
                    imgList = JsonConvert.DeserializeObject<List<string>>(goodsModel.CarouselImage);
                }
                if (imgList.Any())
                {
                    if (imgList.Count() < 8)
                    {
                        var imgList2 = new List<string>();
                        int Num = 8 / imgList.Count();
                        for (var i = 0; i < Num + 1; i++)
                        {
                            imgList2.AddRange(imgList);
                        }
                        imgList = imgList2.Take(8).ToList();
                    }
                }
                info = new
                {
                    goods_name = goodsModel.Name,
                    multi_map = imgList,
                    is_negotiable = 0,
                    min_price = goodsModel.SellingPrice,
                    max_price = goodsModel.SellingPrice,
                    nickname = umodel?.Name ?? "",
                    avatar = umodel?.Photo ?? "",
                    qrcode_url = QRPath,
                    sign = ""
                };
            }
            var obj = new
            {
                config,
                info
            };
            return obj;
        }

        #region 获取小程序码

        /// <summary>
        /// 生成小程序码
        /// </summary>
        /// <param name="path"></param>
        /// <param name="width"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string GetWeiXinQRCode(string path, int width, int mallBaseId)
        {
            var appletWeChatModel = programRepository.GetEntity(mallBaseId);
            string token = CacheManager.AppletWeChat.WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => CacheManager.AppletWeChat.WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (!string.IsNullOrEmpty(token))
            {
                //string GetImageUrl = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + token;//获取二维码
                string GetImageUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;//获取小程序码
                var postData = new
                {
                    path,
                    width
                };
                string pathName = Guid.NewGuid().ToString() + ".jpg";
                string basepath = AppContext.BaseDirectory;
                string path_server = basepath + "\\upfile\\temporary\\" + pathName;
                var Robj = HttpHelper.HttpPostForGetWXQRCodePath(GetImageUrl, JsonHelper.Serialize(postData), path_server);
                //var Robj1 = HttpHelper.HttpPost(GetImageUrl, JsonHelper.Serialize(postData), "");
                return "/upfile/temporary/" + pathName;
            }
            return "";
        }

        #endregion

        /// <summary>
        /// 获取小程序商品详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="UserId"></param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public object GetAppletGoodsInfo_V2(int goodsId, int UserId, int TenantId, int MallBaseId)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            else
            {
                model.CoverImage = "";
                if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
                {
                    List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                    //封面图
                    model.CoverImage = CarouselIdList[0];
                    //轮播图
                }
            }
            //小程序名称
            model.MallName = programRepository.GetEntity(model.MallBaseId)?.MallName ?? "";

            #region 基本信息
            //查询分类
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            //最大售价
            decimal MaxSellMoney = model.SellingPrice ?? 0;
            model.SpecificationList = new List<RB_Goods_Specification_Extend>();
            model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (model.IsCustomSpecification == 1)
            {
                model.SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.SpecificationList.Any())
                {
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in svlist)
                    {
                        item.ImagePath = item.Image;
                    }
                    foreach (var item in model.SpecificationList)
                    {
                        item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                    }
                }
                model.SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                MaxSellMoney = model.SpecificationPriceList.Max(x => x.SellingPrice ?? 0);
            }
            //区域
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //返佣
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //会员价格
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //轮播
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }

            model.CustomShareImagePath = model.CustomShareImage;

            //服务列表
            model.ServiceList = new List<RB_ImageCommonModel>();
            if (model.IsDefaultService == 2)
            {
                if (!string.IsNullOrEmpty(model.GoodsService) && model.GoodsService != "[]")
                {
                    List<int> ServiceIds = JsonConvert.DeserializeObject<List<int>>(model.GoodsService);
                    var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { ServiceIds = string.Join(",", ServiceIds), TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in slist)
                    {
                        model.ServiceList.Add(new RB_ImageCommonModel()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
            }
            else if (model.IsDefaultService == 1)
            {
                var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in slist)
                {
                    model.ServiceList.Add(new RB_ImageCommonModel()
                    {
                        Id = item.Id,
                        Name = item.Name
                    });
                }
            }
            //表单
            if (model.FormsId > 0)
            {
                model.FormsName = "未建表";
            }
            else
            {
                model.FormsName = "默认表单";
            }
            #endregion

            #region 是否收藏
            model.Favorite = false;
            if (UserId > 0)
            {
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.UserId),
                      FiledValue=UserId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.GoodsId),
                      FiledValue=goodsId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.TenantId),
                      FiledValue=TenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.MallBaseId),
                      FiledValue=MallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                },
            };
                if (member_CollectionRepository.Exists(wheres))
                {
                    model.Favorite = true;
                }
            }
            #endregion

            #region 快递费用
            //运费
            Model.Entity.BaseSetUp.RB_Logistics_Rules rulesModel = new Model.Entity.BaseSetUp.RB_Logistics_Rules();
            if (model.FreightId > 0)
            {
                rulesModel = logistics_RulesRepository.GetEntity(model.FreightId);
                model.FreightName = rulesModel?.RulesName ?? "";
            }
            else
            {
                model.FreightName = "默认运费";
            }
            model.Express = 0;
            if (UserId > 0 && model.FreightId >= 0)
            {
                int FreightId = model.FreightId ?? 0;
                if (model.FreightId == 0)
                {
                    //查询默认
                    FreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault()?.ID ?? 0;
                }
                if (FreightId > 0)
                {
                    var samodel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, IsDefault = 1 }).FirstOrDefault();
                    List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList1 = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, RulesId = FreightId });
                    if (priceList1.Any() && samodel != null)
                    {
                        string priceIds = string.Join(",", priceList1.Select(x => x.ID));
                        var regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, PriceIds = priceIds });
                        List<int> disList = new List<int>();
                        disList.Add(samodel.Province ?? 0);
                        disList.Add(samodel.City ?? 0);
                        disList.Add(samodel.District ?? 0);
                        var regionModel = regionList.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                        if (regionModel != null)
                        {
                            var pmodel = priceList1.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                            if (pmodel != null && rulesModel != null)
                            {
                                if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                {
                                    model.Express = pmodel.FirstPrice;
                                }
                                else
                                {
                                    //重量计费
                                    int TotalW = model.GoodsWeight ?? 0;
                                    if (TotalW <= pmodel.First)
                                    {
                                        model.Express = pmodel.FirstPrice;
                                    }
                                    else
                                    {
                                        if (pmodel.Second > 0)
                                        {
                                            if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                            }
                                            else
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                            }
                                        }
                                        else
                                        {
                                            model.Express = pmodel.FirstPrice;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最高返佣
            model.MaxShare = 0;
            if (UserId > 0)
            {
                //获取分销商信息
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                if (disModel != null)
                {
                    //判断是否开启和平返佣
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.Status),
                                FiledValue=0,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.Enabled),
                                FiledValue=1,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.TenantId),
                                FiledValue=TenantId,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                                FiledName=nameof(RB_Distributor_HPCommission.MallBaseId),
                                FiledValue=MallBaseId,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    if (distributor_HPCommissionRepository.Exists(wheres))
                    {
                        //获取和平分销返佣
                        if (disModel.HPGradeId > 0 && model.CostPrice > 0)
                        {
                            string categoryids = string.Join(",", model.CategoryList.Select(x => x.CategoryId));
                            var hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIdsT = categoryids, TenantId = TenantId, MallBaseId = 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 = TenantId, MallBaseId = MallBaseId });

                                var ratioModel = gList.Where(x => x.GradeId == disModel.HPGradeId).FirstOrDefault();
                                decimal MPrice = (model.CostPrice ?? 0) / (1 - ((ratioModel.CommissionRatio ?? 0) / 100));
                                model.MaxShare = MaxSellMoney - MPrice > 0 ? MaxSellMoney - MPrice : 0;
                                if (hpcModel.DecimalType == 1)
                                {
                                    model.MaxShare = Math.Ceiling(model.MaxShare);
                                }
                                else if (hpcModel.DecimalType == 2)
                                {
                                    model.MaxShare = Math.Ceiling(model.MaxShare * 100) / 100;
                                }
                            }
                        }
                    }
                    else
                    {
                        var BasicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                        if (model.SeparateDistribution == 1)
                        {
                            var dcList = model.DistributionCommissionList.Where(x => x.DistributorGrade == disModel.GradeId).ToList();
                            //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                            //{
                            //    model.MaxShare = dcList.Max(x => (x.OneCommission ?? 0) + (x.TwoCommission ?? 0) + (x.ThreeCommission ?? 0));
                            //}
                            //else
                            //{
                            model.MaxShare = dcList.Max(x => x.OneCommission ?? 0);
                            //}
                            // 这里需注意，可能需要分销 是否提所有返佣控制
                            if (model.SeparateDistributionMoneyType == 1)
                            {
                                model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        else
                        {
                            if (disModel.GradeId == 0)
                            {
                                //拿分销基础配置
                                //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                //{
                                //    model.MaxShare = (BasicsModel?.OneCommission ?? 0) + (BasicsModel?.TwoCommission ?? 0) + (BasicsModel?.ThreeCommission ?? 0);
                                //}
                                //else
                                //{
                                model.MaxShare = BasicsModel?.OneCommission ?? 0;
                                //}
                                if ((BasicsModel?.DistributorCommissionType ?? 2) == 1)
                                {
                                    model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            else if (disModel.GradeId > 0)
                            {
                                //获取分销商等级
                                var disgradeModel = distributor_GradeRepository.GetEntity(disModel.GradeId);
                                if (disgradeModel != null)
                                {
                                    //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                    //{
                                    //    model.MaxShare = (disgradeModel?.OneCommission ?? 0) + (disgradeModel?.TwoCommission ?? 0) + (disgradeModel?.ThreeCommission ?? 0);
                                    //}
                                    //else
                                    //{
                                    model.MaxShare = disgradeModel?.OneCommission ?? 0;
                                    //}
                                    if ((disgradeModel?.DistributionCommissionType ?? 2) == 1)
                                    {
                                        model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最外层组装参数
            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            List<RB_Member_Grade_Extend> memeberList = new List<RB_Member_Grade_Extend>();
            if (UserId > 0)
            {
                userModel = GetMemberUserInfo(UserId);
                if (userModel.MemberGrade > 0)
                {
                    memeberList = GetMemberGradeList(new RB_Member_Grade_Extend() { Enabled = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                }
            }

            #region 组装价格
            List<object> priceList = new List<object>();
            if (model.IsCustomSpecification == 1)
            {
                if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                {
                    foreach (var item in model.SpecificationPriceList)
                    {
                        var ssarr = item.SpecificationSort.Split(':');
                        int Sort = Convert.ToInt32(ssarr[0]);
                        string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                        List<object> attr_list = new List<object>();
                        for (int i = 0; i < ssarr.Length; i++)
                        {
                            var smodel = model.SpecificationList[i];
                            var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                            attr_list.Add(new
                            {
                                attr_group_name = smodel.Name,
                                attr_group_id = smodel.Sort,
                                attr_id = svmodel.Id,
                                attr_name = svmodel.Name
                            });
                        }
                        decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        List<object> member_price_list = new List<object>();
                        if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                        {
                            if (model.MemberPriceList.Any())
                            {
                                var mlist = model.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).ToList();
                                foreach (var qitem in mlist)
                                {
                                    member_price_list.Add(new
                                    {
                                        member_grade = qitem.MemberGrade,
                                        member_price = qitem.MemberPrice
                                    });
                                }
                                if (UserId > 0 && userModel.MemberGrade > 0)
                                {
                                    var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                    price_member = gmodel.MemberPrice ?? 0;
                                }
                                else
                                {
                                    price_member = mlist.Max(x => x.MemberPrice ?? 0);
                                }
                            }
                        }
                        else
                        {
                            //根据会员等级查找会员价格
                            foreach (var qitem in memeberList)
                            {
                                var mprice = Math.Round((item.SellingPrice ?? 0) * (qitem.Discount ?? 0) / 10, 2, MidpointRounding.AwayFromZero);
                                member_price_list.Add(new
                                {
                                    member_grade = qitem.Grade,
                                    member_price = mprice
                                });
                            }
                            if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                            {
                                var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                                price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                            else if (memeberList.Any())
                            {
                                price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        priceList.Add(new
                        {
                            id = item.Id,
                            goods_id = model.Id,
                            sign_id = item.SpecificationSort,
                            stock = item.InventoryNum,
                            price = item.SellingPrice,
                            no = item.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url,
                            is_delete = item.Status,
                            attr_list,
                            price_member,
                            member_price_list
                        });
                    }
                }
            }
            else
            {
                decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                List<object> member_price_list = new List<object>();
                if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                {
                    if (model.MemberPriceList.Any())
                    {
                        var mlist = model.MemberPriceList;
                        foreach (var qitem in mlist)
                        {
                            member_price_list.Add(new
                            {
                                member_grade = qitem.MemberGrade,
                                member_price = qitem.MemberPrice
                            });
                        }
                        if (UserId > 0 && userModel.MemberGrade > 0)
                        {
                            var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                            price_member = gmodel.MemberPrice ?? 0;
                        }
                        else
                        {
                            price_member = mlist.Max(x => x.MemberPrice ?? 0);
                        }
                    }
                }
                else
                {
                    //根据会员等级查找会员价格
                    foreach (var qitem in memeberList)
                    {
                        var mprice = Math.Round((model.SellingPrice ?? 0) * (qitem.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                        member_price_list.Add(new
                        {
                            member_grade = qitem.Grade,
                            member_price = mprice
                        });
                    }
                    if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                    {
                        var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                        price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                    else if (memeberList.Any())
                    {
                        price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                }


                priceList.Add(new
                {
                    id = 0,
                    goods_id = model.Id,
                    sign_id = "",
                    stock = model.InventoryNum,
                    price = model.SellingPrice ?? 0,
                    no = model.GoodsNumbers,
                    weight = model.GoodsWeight,
                    pic_url = "",
                    is_delete = 0,
                    attr_list = new List<object>(){ new
                    {
                        attr_group_name = "规格",
                        attr_group_id = 0,
                        attr_id = 0,
                        attr_name = model.DefaultSpecificationName
                    } },
                    price_member,
                    member_price_list
                });
            }
            #endregion

            #region 赠送积分
            int Integral = 0;
            if (model.IntegralPresent > 0)
            {
                Integral = model.IntegralPresent ?? 0;
                if (model.IntegralPresentType == 2)
                {
                    Integral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralPresent ?? 0) / 100));
                }
            }
            #endregion

            #region 会员价格
            decimal price_member_max = 0, price_member_min = 0, price_min = 0, price_max = 0;
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
            {
                price_member_min = model.MemberPriceList.Min(x => x.MemberPrice ?? 0);
                price_member_max = model.MemberPriceList.Max(x => x.MemberPrice ?? 0);
                if (userModel.MemberGrade > 0)
                {
                    price_min = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    price_max = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Max(x => x.MemberPrice ?? 0);
                }
            }
            else
            {

                if (model.IsCustomSpecification == 1)
                {
                    price_member_min = price_min = model.SpecificationPriceList.Min(x => x.SellingPrice ?? 0);
                    price_member_max = price_max = model.SpecificationPriceList.Max(x => x.SellingPrice ?? 0);
                }
                else
                {
                    price_member_min = price_member_max = price_min = price_max = model.SellingPrice ?? 0;
                }
                if (memeberList.Any())
                {
                    List<decimal> pricelist = new List<decimal>();
                    foreach (var item in memeberList)
                    {
                        pricelist.Add(price_member_min * (item.Discount ?? 10) / 10);
                        pricelist.Add(price_member_max * (item.Discount ?? 10) / 10);
                    }
                    price_member_min = pricelist.Min(x => x);
                    price_member_max = pricelist.Max(x => x);
                    if (userModel.MemberGrade > 0)
                    {
                        if (price_min > (model.SellingPrice ?? 0)) { price_min = model.SellingPrice ?? 0; }
                        if (price_max < (model.SellingPrice ?? 0)) { price_max = model.SellingPrice ?? 0; }
                        price_min = price_member_min * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                        price_max = price_member_max * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                    }
                }
            }
            price_member_max = Math.Round(price_member_max, 2, MidpointRounding.AwayFromZero);
            price_member_min = Math.Round(price_member_min, 2, MidpointRounding.AwayFromZero);
            //price_min = Math.Round(price_min, 2, MidpointRounding.AwayFromZero);
            //price_max = Math.Round(price_max, 2, MidpointRounding.AwayFromZero);//先使用会员的  
            price_min = price_member_min;
            price_max = price_member_max;
            #endregion

            #region 订单信息

            int payment_people = 0, payment_num = 0, payment_order = 0;//订单用户  商品数量   订单数量
            decimal payment_amount = 0;//订单总金额
            GetGoodsOrderPeopleInfo(out payment_amount, out payment_num, out payment_order, out payment_people, goodsId);
            #endregion

            #region 返回参数

            string shipping = "";
            if (model.FullNumPinkage > 0)
            {
                shipping += "单品满" + model.FullNumPinkage + "件包邮";
            }
            if (model.FullMoneyPinkage > 0)
            {
                if (model.FullNumPinkage > 0)
                {
                    shipping += "，单品满￥" + model.FullMoneyPinkage.Value.ToString("#0.00") + "包邮";
                }
                else
                {
                    shipping += "单品满￥" + model.FullMoneyPinkage.Value.ToString("#0.00") + "包邮";
                }
            }
            string limit = "";
            if (model.AreaList.Any())
            {
                limit = "仅限" + string.Join(",", model.AreaList.Select(x => x.AreaName)) + "购买";
            }
            int IsAllowShare = 1;
            if (model.CategoryList.Where(x => x.IsForeignShare == 2).Any())
            {
                IsAllowShare = 2;
            }

            return new
            {
                goods = new
                {
                    id = model.Id,
                    mall_id = model.MallBaseId,
                    mch_id = model.TenantId,//暂  商户id
                    //goods_warehouse_id = 0,//
                    status = model.GoodsStatus,
                    isAllowShare = IsAllowShare,//是否可以分享
                    price = model.SellingPrice,
                    use_attr = model.IsCustomSpecification,
                    attr_groups = model.SpecificationList.Select(x => new
                    {
                        attr_group_id = x.Sort,
                        attr_group_name = x.Name,
                        attr_list = x.SpecificationValueList.Select(z => new
                        {
                            attr_id = z.Sort,
                            attr_name = z.Name,
                            pic_url = z.ImagePath
                        })
                    }),
                    goods_stock = model.InventoryNum,
                    virtual_sales = (model.SalesNum ?? 0),
                    confine_count = model.LimitBuyGoodsNum,
                    pieces = model.FullNumPinkage,//满件包邮
                    forehead = model.FullMoneyPinkage,//满额包邮
                    freight_id = model.FreightId,
                    give_integral = model.IntegralPresent,
                    give_integral_type = model.IntegralPresentType,
                    forehead_integral = model.PointsDeduction,//暂  积分抵扣
                    forehead_integral_type = model.PointsDeductionType,//暂  积分抵扣类型
                    accumulative = model.IsMultipleDeduction,//多件抵扣
                    individual_share = userModel?.IsDistributor ?? 2,// 是否分销商
                    attr_setting_type = model.SeparateDistributionType,//分销类型
                    is_level = model.EnjoyMember,//是否销售会员价格
                    is_level_alone = model.SeparateSetMember,//是否单独设置会员价
                    share_type = model.SeparateDistributionMoneyType,//分销佣金类型
                    //sign = "",
                    app_share_pic = model.CustomShareImagePath,
                    app_share_title = model.CustomShareTitles,
                    is_default_services = model.IsDefaultService,
                    sort = model.Sort,
                    created_at = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    updated_at = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    //deleted_at = "",
                    is_delete = model.Status,
                    payment_people,//用户数量
                    payment_num,//商品数量
                    payment_amount,//销售总额
                    payment_order,//订单数量
                    confine_order_count = model.LimitBuyOrderNum,
                    is_area_limit = model.IsAreaBuy,
                    area_limit = new List<object>() { new { list = model.AreaList.Select(x => new {
                        area_id=x.AreaId,
                        area_name=x.AreaName,
                        area_type=x.AreaType
                    }) } },
                    form_id = model.FormsId,
                    sales = (model.SalesNum ?? 0) + payment_num,//已售出数量 + 订单商品数量//
                    name = model.Name,
                    original_price = model.OriginalPrice,
                    cover_pic = model.CoverImage,
                    unit = model.Unit,
                    detail = model.GoodsDetails,
                    video_url = model.VideoAddress,
                    level_show = (userModel?.MemberGrade ?? 0) > 0 ? 1 : 2,//是否显示会员价
                    is_sales = model.GoodsStatus == 1 && model.InventoryNum > 0 ? 1 : 2,//是否可购买
                    attr = priceList,
                    //goods_num = model.InventoryNum,
                    goods_no = model.GoodsNumbers,
                    goods_weight = model.GoodsWeight,
                    services = model.ServiceList.Select(x => new
                    {
                        id = x.Id,
                        name = x.Name
                    }),
                    price_min,
                    price_max,
                    pic_url = model.CarouselImageList.Select(x => new
                    {
                        id = x.Id,
                        pic_url = x.Path
                    }),
                    share = model.MaxShare,//分销佣金
                    favorite = model.Favorite,//是否收藏
                    goods_marketing = new
                    {
                        limit,
                        pickup = "",
                        shipping
                    },
                    goods_marketing_award = new
                    {
                        integral = new
                        {
                            title = Integral > 0 ? "购买可得" + Integral + "积分" : ""
                        }
                    },
                    //plugin_extra = new List<object>(),
                    express = model.Express,//快递费用   读取默认收货地址 如果没有为0  如果有 根据商品运费匹配 找出快递费用
                    price_member_max,
                    price_member_min,
                    extra_quick_share = new
                    {
                        share_pic = model.CarouselImageList.Select(x => new
                        {
                            id = x.Id,
                            pic_url = x.Path
                        }),
                        share_text = model.Name,
                        mall_name = model.MallName,
                        format_time = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
                    },
                    is_quick_shop = model.IsQuickBuy,
                    is_sell_well = model.IsSellWell,
                    is_negotiable = model.IsGoodsNegotiable,
                    cats = model.CategoryList.Select(x => new
                    {
                        x.CategoryId,
                        x.CategoryName
                    })//分类
                },
                delivery = ""
            };
            #endregion
            #endregion
        }

        /// <summary>
        /// 获取小程序商品视频分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsVideoPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string goodsIds = string.Join(",", list.Select(x => x.Id));
                var categoryList = 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 });

                List<RB_Goods_Order_Extend> orderlist = goods_OrderRepository.GetGoodsOrderNum(goodsIds: goodsIds);
                foreach (var item in list)
                {
                    item.CoverImage = "";
                    item.CarouselImageList = new List<RB_ImageCommonModel>();
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        item.CarouselImageList = CarouselIdList.Select(x => new RB_ImageCommonModel()
                        {
                            Id = 0,
                            Name = "",
                            Path = x
                        }).ToList();
                    }

                    #region 基本信息
                    //查询分类
                    item.CategoryList = categoryList.Where(x => x.GoodsId == item.Id).ToList();

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = speciList.Where(x => x.GoodsId == item.Id).ToList();
                        if (item.SpecificationList.Any())
                        {
                            var svlist = speciVList.Where(x => x.GoodsId == item.Id).ToList();
                            foreach (var qitem in svlist)
                            {
                                qitem.ImagePath = qitem.Image;
                            }
                            foreach (var qitem in item.SpecificationList)
                            {
                                qitem.SpecificationValueList = svlist.Where(x => x.SpecificationId == qitem.Id).ToList();
                            }
                        }
                        item.SpecificationPriceList = speciPList.Where(x => x.GoodsId == item.Id).ToList();
                    }
                    item.CustomShareImagePath = item.CustomShareImage;
                    #endregion

                    item.SalesNum += (orderlist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取商品详情 订单相关统计
        /// </summary>
        /// <param name="payment_amount"></param>
        /// <param name="payment_num"></param>
        /// <param name="payment_order"></param>
        /// <param name="payment_people"></param>
        /// <param name="goodsId"></param>
        public void GetGoodsOrderPeopleInfo(out decimal payment_amount, out int payment_num, out int payment_order, out int payment_people, int goodsId)
        {
            goods_OrderRepository.GetGoodsOrderPeopleInfo(out payment_amount, out payment_num, out payment_order, out payment_people, goodsId);
        }
        #endregion


        #region 素材管理
        /// <summary>
        /// 获取素材分组列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Material_Group_Extend> GetMaterialGroupList(RB_Material_Group_Extend dmodel)
        {
            var list = material_GroupRepository.GetList(dmodel);
            return list;
        }


        /// <summary>
        /// 获取素材分组分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Material_Info_Extend> GetMaterialInfoPageList(int pageIndex, int pageSize, out long count, RB_Material_Info_Extend dmodel)
        {
            var list = material_InfoRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            return list;
        }

        /// <summary>
        /// 新增分组
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMaterialGroupInfo(RB_Material_Group_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Material_Group.Name),demodel.Name},
                    { nameof(RB_Material_Group.Sort),demodel.Sort},
                    { nameof(RB_Material_Group.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                     FiledName=nameof(RB_Material_Group.Id),
                      FiledValue=demodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                    }
                };
                return material_GroupRepository.Update(keyValues, wheres);
            }
            else
            {
                return material_GroupRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 设置素材信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMaterialInfo(RB_Material_Info_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Material_Info.Name),demodel.Name},
                    { nameof(RB_Material_Info.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                     FiledName=nameof(RB_Material_Group.Id),
                      FiledValue=demodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                    }
                };
                return material_InfoRepository.Update(keyValues, wheres);
            }
            else
            {
                return material_InfoRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 设置分组回收
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialGroupRecycled(int groupId, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Material_Group.Recycled),2},
                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.Id),
                    FiledValue=groupId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.TenantId),
                    FiledValue=Convert.ToInt32(uid),
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            bool flag = material_GroupRepository.Update(keyValues, wheres);
            if (flag)
            {
                //分组下所有素材全回收
                material_InfoRepository.SetMaterialInfoRecycled(groupId, Convert.ToInt32(uid), mallBaseId);
            }
            return flag;
        }

        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelMaterialGroupInfo(int groupId, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.Recycled != 2)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Material_Group.Status),1},
                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.Id),
                    FiledValue=groupId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.TenantId),
                    FiledValue=Convert.ToInt32(uid),
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            bool flag = material_GroupRepository.Update(keyValues, wheres);
            if (flag)
            {
                //删除分组下所有的素材
                material_InfoRepository.DelMaterialInfo("", uid, mallBaseId, groupId);
            }
            return flag;
        }

        /// <summary>
        /// 设置分组还原
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialGroupRestore(int groupId, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.Recycled != 2)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Material_Group.Recycled),1},
                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.Id),
                    FiledValue=groupId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.TenantId),
                    FiledValue=Convert.ToInt32(uid),
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            return material_GroupRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 设置素材回收
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialInfoRecycled(string materialIds, string uid, int mallBaseId)
        {
            bool flag = material_InfoRepository.SetMaterialListRecycled(materialIds, uid, mallBaseId);
            return flag;
        }

        /// <summary>
        /// 删除素材
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelMaterialInfo(string materialIds, string uid, int mallBaseId)
        {
            bool flag = material_InfoRepository.DelMaterialInfo(materialIds, uid, mallBaseId);
            return flag;
        }

        /// <summary>
        /// 设置素材还原
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialInfoRestore(string materialIds, string uid, int mallBaseId)
        {
            var trans = material_InfoRepository.DbTransaction;
            try
            {
                var list = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = materialIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                if (list.Any())
                {
                    //查询出所有的分组
                    var glist = material_GroupRepository.GetList(new RB_Material_Group_Extend() { GroupIds = string.Join(",", list.Select(x => x.GroupId).Distinct()), TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    if (glist.Where(x => x.Recycled == 2).Any())
                    {
                        foreach (var item in glist.Where(x => x.Recycled == 2))
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Material_Group.Recycled),1},
                                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                    FiledName=nameof(RB_Material_Group.Id),
                                    FiledValue=item.Id,
                                    OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                    FiledName=nameof(RB_Material_Group.TenantId),
                                    FiledValue=Convert.ToInt32(uid),
                                    OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                    FiledName=nameof(RB_Material_Group.MallBaseId),
                                    FiledValue=mallBaseId,
                                    OperatorEnum=OperatorEnum.Equal
                                },
                            };
                            material_GroupRepository.Update(keyValues, wheres, trans);
                        }
                    }
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Material_Info.Recycled),1},
                            { nameof(RB_Material_Info.UpdateDate),DateTime.Now},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                FiledName=nameof(RB_Material_Info.Id),
                                FiledValue=item.Id,
                                OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                FiledName=nameof(RB_Material_Info.TenantId),
                                FiledValue=Convert.ToInt32(uid),
                                OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                FiledName=nameof(RB_Material_Info.MallBaseId),
                                FiledValue=mallBaseId,
                                OperatorEnum=OperatorEnum.Equal
                            },
                        };
                        material_InfoRepository.Update(keyValues, wheres, trans);
                    }
                }
                material_InfoRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetMaterialInfoRestore");
                material_InfoRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 设置分组转移
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="groupId"></param>
        /// <param name="Type"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialInfoTransfer(string materialIds, int groupId, int Type, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.Status == 1 || gmodel.Recycled == 2 || gmodel.Type != Type)
            {
                return false;
            }
            return material_InfoRepository.SetMaterialInfoTransfer(materialIds, groupId, uid, mallBaseId);
        }

        #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_Product_Category_Extend> GetProductCategoryPageList(int pageIndex, int pageSize, out long count, RB_Product_Category_Extend demodel)
        {
            var list = product_CategoryRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                List<int> ImgIds = new List<int>();
                ImgIds.AddRange(list.Select(x => x.Icon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.BigIcon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.AdvertisingImage ?? 0).Distinct());
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (ImgIds.Any())
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", ImgIds), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                    item.BigIconPath = mlist.Where(x => x.Id == item.BigIcon).FirstOrDefault()?.Path ?? "";
                    item.AdvertisingImagePath = mlist.Where(x => x.Id == item.AdvertisingImage).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductCategoryInfo(int categoryId, int tenantId, int mallBaseId)
        {
            var trans = product_CategoryRepository.DbTransaction;
            try
            {
                var list = GetProductCategoryForALLChlid(categoryId, tenantId, mallBaseId);
                foreach (var item in list)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Product_Category.Status),1},
                        { nameof(RB_Product_Category.UpdateDate),DateTime.Now},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Product_Category.Id),
                              FiledValue=categoryId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Product_Category.TenantId),
                              FiledValue=tenantId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Product_Category.MallBaseId),
                              FiledValue=mallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    bool flag = product_CategoryRepository.Update(keyValues, wheres, trans);
                }
                product_CategoryRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelProductCategoryInfo");
                product_CategoryRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 获取分类样式
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_Product_CategoryStyle_Extend GetProductCategoryStyleInfo(int tenantId, int mallBaseId)
        {
            return product_CategoryStyleRepository.GetList(new RB_Product_CategoryStyle_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
        }

        /// <summary>
        /// 保存分类样式
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductCategoryStyleInfo(RB_Product_CategoryStyle_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_CategoryStyle.Type),demodel.Type},
                    { nameof(RB_Product_CategoryStyle.Style),demodel.Style},
                    { nameof(RB_Product_CategoryStyle.CategoryNum),demodel.CategoryNum},
                    { nameof(RB_Product_CategoryStyle.RowNum),demodel.RowNum},
                    { nameof(RB_Product_CategoryStyle.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Product_Category.Id),
                            FiledValue=demodel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_CategoryStyleRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_CategoryStyleRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 保存排序
        /// </summary>
        /// <param name="delist"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetProductCategorySort(List<RB_Product_CategorySort> delist, int tenantId, int mallBaseId)
        {
            var trans = product_CategoryRepository.DbTransaction;
            try
            {
                string ids = string.Join(",", delist.Select(x => x.Id));
                var list = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { CategoryIds = ids, TenantId = tenantId, MallBaseId = mallBaseId });
                if (list.Any())
                {
                    foreach (var item in list)
                    {
                        var demodel = delist.Where(x => x.Id == item.Id).FirstOrDefault();
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Product_Category.Sort),demodel.Sort},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Product_Category.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = product_CategoryRepository.Update(keyValues, wheres, trans);
                    }
                }
                product_CategoryRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductCategorySort");
                product_CategoryRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 获取树形结构列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_CategoryTree> GetProductCategoryTreeList(RB_Product_Category_Extend demodel)
        {
            List<RB_Product_CategoryTree> treeList = new List<RB_Product_CategoryTree>();
            var list = product_CategoryRepository.GetList(demodel);
            if (list.Any())
            {
                List<int> ImgIds = new List<int>();
                ImgIds.AddRange(list.Select(x => x.Icon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.BigIcon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.AdvertisingImage ?? 0).Distinct());
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (ImgIds.Any())
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", ImgIds), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                    item.BigIconPath = mlist.Where(x => x.Id == item.BigIcon).FirstOrDefault()?.Path ?? "";
                    item.AdvertisingImagePath = mlist.Where(x => x.Id == item.AdvertisingImage).FirstOrDefault()?.Path ?? "";
                }
                list = list.OrderBy(x => x.Sort).ThenBy(x => x.Id).ToList();
                treeList = GetProductCategoryChildTree(list, 0);
            }

            return treeList;
        }

        /// <summary>
        /// 获取子集列表
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public List<RB_Product_CategoryTree> GetProductCategoryChildTree(List<RB_Product_Category_Extend> list, int parentId)
        {
            List<RB_Product_CategoryTree> RList = new List<RB_Product_CategoryTree>();
            var CList = list.Where(x => x.ParentId == parentId).ToList();
            foreach (var item in CList)
            {
                var cmodel = new RB_Product_CategoryTree
                {
                    Id = item.Id,
                    Name = item.Name,
                    Icon = item.Icon ?? 0,
                    IconPath = item.IconPath
                };
                cmodel.ChildList = GetProductCategoryChildTree(list, item.Id);
                RList.Add(cmodel);
            }
            return RList;
        }

        /// <summary>
        /// 保存商品分类
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductCategoryInfo(RB_Product_Category_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Category.AdvertisingAddress),demodel.AdvertisingAddress},
                    { nameof(RB_Product_Category.AdvertisingImage),demodel.AdvertisingImage},
                    { nameof(RB_Product_Category.BigIcon),demodel.BigIcon},
                    { nameof(RB_Product_Category.Enabled),demodel.Enabled},
                    { nameof(RB_Product_Category.Icon),demodel.Icon},
                    { nameof(RB_Product_Category.IsShow),demodel.IsShow},
                    { nameof(RB_Product_Category.Name),demodel.Name},
                    { nameof(RB_Product_Category.Sort),demodel.Sort},
                    { nameof(RB_Product_Category.IsForeignShare),demodel.IsForeignShare},
                    { nameof(RB_Product_Category.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Category.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_CategoryRepository.Update(keyValues, wheres);
            }
            else
            {
                int Id = product_CategoryRepository.Insert(demodel);
                if (Id > 0)
                {
                    int RootId = Id;
                    if (demodel.ParentId > 0)
                    {
                        var pmodel = product_CategoryRepository.GetEntity(demodel.ParentId);
                        RootId = pmodel?.RootId ?? 0;
                    }
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Product_Category.RootId),RootId},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Product_Category.Id),
                                FiledValue=Id,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    product_CategoryRepository.Update(keyValues, wheres);
                }
                return Id > 0;
            }
        }

        /// <summary>
        /// 获取商品分类
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public RB_Product_Category_Extend GetProductCategoryInfo(int categoryId)
        {
            var model = product_CategoryRepository.GetEntity(categoryId).RefMapperTo<RB_Product_Category_Extend>();
            List<int> ImgIds = new List<int>
            {
                model.Icon ?? 0,
                model.BigIcon ?? 0,
                model.AdvertisingImage ?? 0
            };
            List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
            if (ImgIds.Any())
            {
                mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", ImgIds) });
            }

            model.IconPath = mlist.Where(x => x.Id == model.Icon).FirstOrDefault()?.Path ?? "";
            model.BigIconPath = mlist.Where(x => x.Id == model.BigIcon).FirstOrDefault()?.Path ?? "";
            model.AdvertisingImagePath = mlist.Where(x => x.Id == model.AdvertisingImage).FirstOrDefault()?.Path ?? "";
            var p1Model = product_CategoryRepository.GetEntity(model?.ParentId);
            if (p1Model != null)
            {
                model.Parent1Name = p1Model.Name;
                var p2Model = product_CategoryRepository.GetEntity(p1Model?.ParentId);
                if (p2Model != null)
                {
                    model.Parent1Name = p2Model.Name;
                    model.Parent2Name = p1Model.Name;//黄媛媛要求  1表示1级  2表示2级
                }
            }
            return model;
        }

        /// <summary>
        /// 获取当前分类的所有子集分类
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="tid"></param>
        /// <param name="mid"></param>
        /// <returns></returns>
        public List<RB_Product_Category_Extend> GetProductCategoryForALLChlid(int categoryId, int tid, int mid)
        {
            var model = product_CategoryRepository.GetEntity(categoryId);
            var list = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { RootId = model.RootId, TenantId = tid, MallBaseId = mid });
            List<RB_Product_Category_Extend> RList = GetProductCategoryALLChild(list, model.Id);
            RList.AddRange(list.Where(x => x.Id == model.Id).ToList());
            return RList;
        }

        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Product_Category_Extend> GetCategoryListModule(RB_Product_Category_Extend dmodel)
        {
            return product_CategoryRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取所有子集
        /// </summary>
        /// <param name="list"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private List<RB_Product_Category_Extend> GetProductCategoryALLChild(List<RB_Product_Category_Extend> list, int id)
        {
            List<RB_Product_Category_Extend> RList = new List<RB_Product_Category_Extend>();
            var list2 = list.Where(x => x.ParentId == id).ToList();
            RList.AddRange(list2);
            foreach (var item in list2)
            {
                RList.AddRange(GetProductCategoryALLChild(list, item.Id));
            }
            return RList;
        }

        /// <summary>
        /// 分类转移
        /// </summary>
        /// <param name="cmodel"></param>
        /// <param name="parentId"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool SetProductCategoryTransfer(RB_Product_Category_Extend cmodel, int parentId, List<RB_Product_Category_Extend> list)
        {
            var trans = product_CategoryRepository.DbTransaction;
            try
            {
                int RootId = cmodel.Id;
                int Tier = 0;
                if (parentId > 0)
                {
                    var pmodel = product_CategoryRepository.GetEntity(parentId);
                    if (pmodel == null)
                    {
                        return false;
                    }
                    RootId = pmodel.RootId ?? 0;
                    Tier = (pmodel.Tier ?? 0) + 1;
                }
                else
                {
                    Tier = 1;
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Category.ParentId),parentId},
                    { nameof(RB_Product_Category.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper()
                    {
                         FiledName=nameof(RB_Product_Category.Id),
                         FiledValue=cmodel.Id,
                         OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = product_CategoryRepository.Update(keyValues, wheres, trans);
                if (flag)
                {
                    //更新所有子集rootid=
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Product_Category.RootId),RootId},
                            { nameof(RB_Product_Category.Tier),Tier+(item.Tier??0)-(cmodel.Tier??0) }
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Product_Category.Id),
                                    FiledValue=item.Id,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        product_CategoryRepository.Update(keyValues1, wheres1, trans);
                    }
                }
                product_CategoryRepository.DBSession.Commit();
                return flag;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductCategoryTransfer");
                product_CategoryRepository.DBSession.Rollback();
                return false;
            }
        }

        #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_Product_Specification_Extend> GetProducSpecificationPageList(int pageIndex, int pageSize, out long count, RB_Product_Specification_Extend demodel)
        {
            var list = product_SpecificationRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            foreach (var item in list)
            {
                item.SpecList = new List<string>();
                if (!string.IsNullOrEmpty(item.Content))
                {
                    item.SpecList = JsonConvert.DeserializeObject<List<string>>(item.Content);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取规格列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_Specification_Extend> GetProducSpecificationList(RB_Product_Specification_Extend demodel)
        {
            var list = product_SpecificationRepository.GetList(demodel);
            foreach (var item in list)
            {
                item.SpecList = new List<string>();
                if (!string.IsNullOrEmpty(item.Content))
                {
                    item.SpecList = JsonConvert.DeserializeObject<List<string>>(item.Content);
                }
            }
            return list;
        }

        /// <summary>
        /// 保存修改规格
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductSpecificationInfo(RB_Product_Specification_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Specification.Name),demodel.Name},
                    { nameof(RB_Product_Specification.Content),demodel.Content},
                    { nameof(RB_Product_Specification.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Specification.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_SpecificationRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_SpecificationRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除商品规格
        /// </summary>
        /// <param name="specificationId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductSpecificationInfo(int specificationId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Product_Specification.Status),1},
                { nameof(RB_Product_Specification.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Product_Specification.Id),
                        FiledValue=specificationId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_Specification.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_Specification.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return product_SpecificationRepository.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_Product_QuickBuy_Extend> GetProductQuickBuyPageList(int pageIndex, int pageSize, out long count, RB_Product_QuickBuy_Extend demodel)
        {
            var list = product_QuickBuyRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string imgids = string.Join(",", list.Where(x => x.Icon > 0).Select(x => x.Icon));
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (!string.IsNullOrEmpty(imgids))
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = imgids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取快速购买列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_QuickBuy_Extend> GetProductQuickBuyList(RB_Product_QuickBuy_Extend demodel)
        {
            var list = product_QuickBuyRepository.GetAllList(demodel);
            if (list.Any())
            {
                string imgids = string.Join(",", list.Where(x => x.Icon > 0).Select(x => x.Icon));
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (!string.IsNullOrEmpty(imgids))
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = imgids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 验证快速购买分类
        /// </summary>
        /// <param name="id"></param>
        /// <param name="categoryId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool ValidateQuickBuyCategory(int id, int? categoryId, int tenantId, int mallBaseId)
        {
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.CategoryId),
                        FiledValue=categoryId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.Status),
                        FiledValue=0,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            if (id > 0)
            {
                wheres.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Product_QuickBuy.Id),
                    FiledValue = id,
                    OperatorEnum = OperatorEnum.NotEqual
                });
            }
            return product_QuickBuyRepository.Exists(wheres);
        }

        /// <summary>
        /// 新增修改快速购买
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductQuickBuyInfo(RB_Product_QuickBuy_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_QuickBuy.CategoryId),demodel.CategoryId},
                    { nameof(RB_Product_QuickBuy.Sort),demodel.Sort},
                    { nameof(RB_Product_QuickBuy.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Product_QuickBuy.Id),
                            FiledValue=demodel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.TenantId),
                        FiledValue=demodel.TenantId,
                        OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.MallBaseId),
                        FiledValue=demodel.MallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                    },
                };
                return product_QuickBuyRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_QuickBuyRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除快速购买
        /// </summary>
        /// <param name="quickBuyId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductQuickBuyInfo(int quickBuyId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Product_QuickBuy.Status),1},
                { nameof(RB_Product_QuickBuy.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Product_QuickBuy.Id),
                    FiledValue=quickBuyId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_QuickBuy.TenantId),
                    FiledValue=tenantId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_QuickBuy.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            return product_QuickBuyRepository.Update(keyValues, wheres);
        }

        #endregion

        #region 推荐设置
        /// <summary>
        /// 获取推荐设置详情
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_Product_Recommend_Extend GetProductRecommendSetInfo(int tenantId, int mallBaseId)
        {
            var model = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return new RB_Product_Recommend_Extend();
            }
            model.OrderProductList = new List<RB_ProductRecommendModel>();
            if (model.IsOrderRecommend == 1 && !string.IsNullOrEmpty(model.OrderProductIds))
            {
                //查询商品
                var glist = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = model.OrderProductIds, TenantId = tenantId, MallBaseId = mallBaseId });
                foreach (var item in glist)
                {
                    //轮播图
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<int> CarouselIdList = JsonConvert.DeserializeObject<List<int>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = material_InfoRepository.GetEntity(CarouselIdList[0])?.Path ?? "";
                    }
                }
                foreach (var item in glist)
                {
                    model.OrderProductList.Add(new RB_ProductRecommendModel()
                    {
                        Id = item.Id,
                        Image = item.CoverImage,
                        Name = item.Name
                    });
                }
            }
            model.CommentProductList = new List<RB_ProductRecommendModel>();
            if (model.IsCommentRecommend == 1 && !string.IsNullOrEmpty(model.CommentProductIds))
            {
                var glist = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = model.CommentProductIds, TenantId = tenantId, MallBaseId = mallBaseId });
                foreach (var item in glist)
                {
                    //轮播图
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
                foreach (var item in glist)
                {
                    model.CommentProductList.Add(new RB_ProductRecommendModel()
                    {
                        Id = item.Id,
                        Image = item.CoverImage,
                        Name = item.Name
                    });
                }
            }
            return model;
        }

        /// <summary>
        /// 保存推荐设置
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductRecommendSetInfo(RB_Product_Recommend_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Recommend.CommentProductIds),demodel.CommentProductIds},
                    { nameof(RB_Product_Recommend.CommentRecommentStatus),demodel.CommentRecommentStatus},
                    { nameof(RB_Product_Recommend.DetailRecommendNum),demodel.DetailRecommendNum},
                    { nameof(RB_Product_Recommend.DetailRecommendStatus),demodel.DetailRecommendStatus},
                    { nameof(RB_Product_Recommend.IsCommentRecommend),demodel.IsCommentRecommend},
                    { nameof(RB_Product_Recommend.IsOrderRecommend),demodel.IsOrderRecommend},
                    { nameof(RB_Product_Recommend.OrderCompleteStatus),demodel.OrderCompleteStatus},
                    { nameof(RB_Product_Recommend.OrderProductIds),demodel.OrderProductIds},
                    { nameof(RB_Product_Recommend.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Recommend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_RecommendRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_RecommendRepository.Insert(demodel) > 0;
            }
        }

        #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_Product_Service_Extend> GetProductServicePageList(int pageIndex, int pageSize, out long count, RB_Product_Service_Extend demodel)
        {
            return product_ServiceRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取商品服务列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_Service_Extend> GetProductServiceList(RB_Product_Service_Extend demodel)
        {
            return product_ServiceRepository.GetList(demodel);
        }


        /// <summary>
        /// 新增修改商品服务
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductServiceInfo(RB_Product_Service_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Service.Name),demodel.Name},
                    { nameof(RB_Product_Service.Sort),demodel.Sort},
                    { nameof(RB_Product_Service.Remark),demodel.Remark},
                    { nameof(RB_Product_Service.IsDefault),demodel.IsDefault},
                    { nameof(RB_Product_Service.UpdateDate),demodel.UpdateDate}
                };
                if (demodel.UpdateType == 1)
                { //只更新默认状态
                    var model = product_ServiceRepository.GetEntity(demodel.Id);
                    if (model == null)
                    {
                        return false;
                    }
                    keyValues = new Dictionary<string, object>()
                    {
                        { nameof(RB_Product_Service.IsDefault),model.IsDefault==1?2:1},
                        { nameof(RB_Product_Service.UpdateDate),demodel.UpdateDate}
                    };
                }
                else if (demodel.UpdateType == 2)
                { //只更新排序
                    keyValues = new Dictionary<string, object>()
                    {
                        { nameof(RB_Product_Service.Sort),demodel.Sort},
                        { nameof(RB_Product_Service.UpdateDate),demodel.UpdateDate}
                    };
                }
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Service.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_ServiceRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_ServiceRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 获取服务详情
        /// </summary>
        /// <param name="serviceId"></param>
        /// <returns></returns>
        public RB_Product_Service_Extend GetProductServiceInfo(int serviceId)
        {
            return product_ServiceRepository.GetEntity(serviceId).RefMapperTo<RB_Product_Service_Extend>();
        }

        /// <summary>
        /// 删除商品服务
        /// </summary>
        /// <param name="serviceId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductServiceInfo(int serviceId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Product_Service.Status),1},
                { nameof(RB_Product_Service.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Product_Service.Id),
                    FiledValue=serviceId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_Service.TenantId),
                    FiledValue=tenantId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_Service.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            return product_ServiceRepository.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_Extend> GetProductGoodsPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var olist = goods_OrderRepository.GetGoodsOrderNum(ids);
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                    }

                    item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
                }
            }
            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_Extend> GetProductGoodsPageList_V2(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            if (!string.IsNullOrEmpty(demodel.CategoryIds) && !demodel.CategoryIds.Contains(','))
            {
                //获取该分类下所有子集分类
                var cmodel = product_CategoryRepository.GetEntity(demodel.CategoryIds);
                if (cmodel != null)
                {
                    List<int> AllClist = new List<int>();
                    AllClist.Add(cmodel.Id);
                    var clist = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, RootId = cmodel.RootId });
                    var OneList = clist.Where(x => x.ParentId == cmodel.Id).ToList();
                    foreach (var item in OneList)
                    {
                        AllClist.Add(item.Id);
                        var TwoList = clist.Where(x => x.ParentId == item.Id).ToList();
                        if (TwoList.Any())
                        {
                            AllClist.AddRange(TwoList.Select(x => x.Id).Distinct().ToList());
                        }
                    }
                    if (AllClist.Any())
                    {
                        demodel.CategoryIds = string.Join(",", AllClist);
                    }
                }
            }
            var list = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var olist = goods_OrderRepository.GetGoodsOrderNum(ids);
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                    }

                    item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
                }
            }
            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_Extend> GetProductGoodsProxyPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var olist = goods_OrderRepository.GetGoodsOrderNum(ids);
                //查询商品是否已代理
                var ProxyList = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsIds = ids, ProxyTenantId = demodel.TenantId, ProxyMallBaseId = demodel.MallBaseId });
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }

                    item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
                    item.IsProcurement = 2;
                    item.ProcurementGoodsId = 0;
                    if (ProxyList.Where(x => x.GoodsId == item.Id).Any())
                    {
                        item.IsProcurement = 1;
                        item.ProcurementGoodsId = ProxyList.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.GoodsId ?? 0;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取后台商品列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetProductGoodsList(RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetList(demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取后台商品列表(导出专用)
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetProductGoodsListForExcel(RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetList(demodel);
            if (list.Any())
            {
                var SpecificationList = new List<RB_Goods_Specification_Extend>();
                var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (list.Where(x => x.IsCustomSpecification == 1).Any())
                {
                    string goodsIds = string.Join(",", list.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (SpecificationList.Any())
                    {
                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        foreach (var item in svlist)
                        {
                            item.ImagePath = item.Image;
                        }
                        foreach (var item in SpecificationList)
                        {
                            item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                        }
                    }
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //区域
                var AreaList = new List<RB_Goods_Area_Extend>();
                if (list.Where(x => x.IsAreaBuy == 1).Any())
                {
                    string goodssid = string.Join(",", list.Where(x => x.IsAreaBuy == 1).Select(x => x.Id));
                    AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsIds = goodssid, 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];
                    }

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = SpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                    }
                    item.AreaList = new List<RB_Goods_Area_Extend>();
                    if (item.IsAreaBuy == 1)
                    {
                        item.AreaList = AreaList.Where(x => x.GoodsId == item.Id).ToList();
                    }

                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductGoodsInfo(RB_Goods_Extend demodel)
        {
            //bool IsSyncProxy = false;
            var goodsModel = new RB_Goods();
            if (demodel.Id > 0)
            {
                goodsModel = goodsRepository.GetEntity(demodel.Id);
                if (goodsModel == null)
                {
                    return false;
                }
                if (goodsModel.IsProcurement == 1)
                {
                    //是采购的商品
                    if (demodel.CostPrice != goodsModel.CostPrice)
                    {
                        return false;
                    }
                    //验证 规格
                    if (demodel.IsCustomSpecification != goodsModel.IsCustomSpecification)
                    {
                        return false;
                    }
                    if (goodsModel.IsCustomSpecification == 1)
                    {
                        var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        if (splist.Count() != demodel.SpecificationPriceList.Count() || splist.Count() != demodel.SpecificationPriceList.Where(x => splist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count())
                        {
                            return false;
                        }
                    }
                }
            }

            var trans = goodsRepository.DbTransaction;
            try
            {
                if (demodel.Id > 0)
                {
                    //修改
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Goods.Name),demodel.Name},
                        { nameof(RB_Goods.CarouselImage),demodel.CarouselImage},
                        { nameof(RB_Goods.VideoAddress),demodel.VideoAddress},
                        { nameof(RB_Goods.CustomShareTitles),demodel.CustomShareTitles},
                        { nameof(RB_Goods.CustomShareImage),demodel.CustomShareImage},
                        { nameof(RB_Goods.GoodsStatus),demodel.GoodsStatus},
                        { nameof(RB_Goods.InventoryNum),demodel.InventoryNum},
                        { nameof(RB_Goods.DefaultSpecificationName),demodel.DefaultSpecificationName},
                        { nameof(RB_Goods.IsCustomSpecification),demodel.IsCustomSpecification},
                        { nameof(RB_Goods.Sort),demodel.Sort},
                        { nameof(RB_Goods.SellingPrice),demodel.SellingPrice},
                        { nameof(RB_Goods.OriginalPrice),demodel.OriginalPrice},
                        { nameof(RB_Goods.Unit),demodel.Unit},
                        { nameof(RB_Goods.CostPrice),demodel.CostPrice},
                        { nameof(RB_Goods.IsGoodsNegotiable),demodel.IsGoodsNegotiable},
                        { nameof(RB_Goods.SalesNum),demodel.SalesNum},
                        { nameof(RB_Goods.GoodsNumbers),demodel.GoodsNumbers},
                        { nameof(RB_Goods.GoodsWeight),demodel.GoodsWeight},
                        { nameof(RB_Goods.IsDefaultService),demodel.IsDefaultService},
                        { nameof(RB_Goods.GoodsService),demodel.GoodsService},
                        { nameof(RB_Goods.FreightId),demodel.FreightId},
                        { nameof(RB_Goods.FormsId),demodel.FormsId},
                        { nameof(RB_Goods.LimitBuyGoodsNum),demodel.LimitBuyGoodsNum},
                        { nameof(RB_Goods.LimitBuyOrderNum),demodel.LimitBuyOrderNum},
                        { nameof(RB_Goods.FullNumPinkage),demodel.FullNumPinkage},
                        { nameof(RB_Goods.FullMoneyPinkage),demodel.FullMoneyPinkage},
                        { nameof(RB_Goods.IsAreaBuy),demodel.IsAreaBuy},
                        { nameof(RB_Goods.IntegralPresent),demodel.IntegralPresent},
                        { nameof(RB_Goods.IntegralPresentType),demodel.IntegralPresentType},
                        { nameof(RB_Goods.PointsDeduction),demodel.PointsDeduction},
                        { nameof(RB_Goods.PointsDeductionType),demodel.PointsDeductionType},
                        { nameof(RB_Goods.IsMultipleDeduction),demodel.IsMultipleDeduction},
                        { nameof(RB_Goods.GoodsDetails),demodel.GoodsDetails},
                        { nameof(RB_Goods.UpdateDate),demodel.UpdateDate},
                        { nameof(RB_Goods.SeparateDistribution),demodel.SeparateDistribution},
                        { nameof(RB_Goods.SeparateDistributionType),demodel.SeparateDistributionType},
                        { nameof(RB_Goods.SeparateDistributionMoneyType),demodel.SeparateDistributionMoneyType},
                        { nameof(RB_Goods.EnjoyMember),demodel.EnjoyMember},
                        { nameof(RB_Goods.SeparateSetMember),demodel.SeparateSetMember},
                        { nameof(RB_Goods.IsQuickBuy),demodel.IsQuickBuy},
                        { nameof(RB_Goods.SupplierId),demodel.SupplierId},
                        { nameof(RB_Goods.IsProxy),demodel.IsProxy},
                        { nameof(RB_Goods.ProxyType),demodel.ProxyType},
                        { nameof(RB_Goods.ProxyRises),demodel.ProxyRises},
                        { nameof(RB_Goods.ProxyMoney),demodel.ProxyMoney},
                    };
                    if (goodsModel.IsProcurement == 1)
                    {
                        //采购商品可修改
                        keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Goods.Name),demodel.Name},
                        { nameof(RB_Goods.CarouselImage),demodel.CarouselImage},
                        { nameof(RB_Goods.VideoAddress),demodel.VideoAddress},
                        { nameof(RB_Goods.CustomShareTitles),demodel.CustomShareTitles},
                        { nameof(RB_Goods.CustomShareImage),demodel.CustomShareImage},
                        { nameof(RB_Goods.Sort),demodel.Sort},
                        { nameof(RB_Goods.SellingPrice),demodel.SellingPrice},
                        { nameof(RB_Goods.OriginalPrice),demodel.OriginalPrice},
                        { nameof(RB_Goods.Unit),demodel.Unit},
                        { nameof(RB_Goods.SalesNum),demodel.SalesNum},
                        { nameof(RB_Goods.IsDefaultService),demodel.IsDefaultService},
                        { nameof(RB_Goods.GoodsService),demodel.GoodsService},
                        { nameof(RB_Goods.FreightId),demodel.FreightId},
                        { nameof(RB_Goods.FormsId),demodel.FormsId},
                        { nameof(RB_Goods.LimitBuyGoodsNum),demodel.LimitBuyGoodsNum},
                        { nameof(RB_Goods.LimitBuyOrderNum),demodel.LimitBuyOrderNum},
                        { nameof(RB_Goods.FullNumPinkage),demodel.FullNumPinkage},
                        { nameof(RB_Goods.FullMoneyPinkage),demodel.FullMoneyPinkage},
                        { nameof(RB_Goods.IsAreaBuy),demodel.IsAreaBuy},
                        { nameof(RB_Goods.IntegralPresent),demodel.IntegralPresent},
                        { nameof(RB_Goods.IntegralPresentType),demodel.IntegralPresentType},
                        { nameof(RB_Goods.PointsDeduction),demodel.PointsDeduction},
                        { nameof(RB_Goods.PointsDeductionType),demodel.PointsDeductionType},
                        { nameof(RB_Goods.IsMultipleDeduction),demodel.IsMultipleDeduction},
                        { nameof(RB_Goods.GoodsDetails),demodel.GoodsDetails},
                        { nameof(RB_Goods.UpdateDate),demodel.UpdateDate},
                        { nameof(RB_Goods.SeparateDistribution),demodel.SeparateDistribution},
                        { nameof(RB_Goods.SeparateDistributionType),demodel.SeparateDistributionType},
                        { nameof(RB_Goods.SeparateDistributionMoneyType),demodel.SeparateDistributionMoneyType},
                        { nameof(RB_Goods.EnjoyMember),demodel.EnjoyMember},
                        { nameof(RB_Goods.SeparateSetMember),demodel.SeparateSetMember},
                        { nameof(RB_Goods.IsQuickBuy),demodel.IsQuickBuy},
                        { nameof(RB_Goods.SupplierId),demodel.SupplierId}
                    };
                    }
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods.Id),
                              FiledValue=demodel.Id,
                               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 flag = goodsRepository.Update(keyValues, wheres, trans);
                    if (flag)
                    {
                        #region 修改分类
                        var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        var insertList = demodel.CategoryList.Where(x => !clist.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                        //var updateList = clist.Where(x => demodel.CategoryList.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                        var deleteList = clist.Where(x => !demodel.CategoryList.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                        foreach (var item in insertList)
                        {
                            goods_CategoryRepository.Insert(new RB_Goods_Category()
                            {
                                CategoryId = item.CategoryId,
                                CreateDate = demodel.CreateDate,
                                GoodsId = demodel.Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                        foreach (var item in deleteList)
                        {
                            goods_CategoryRepository.Delete(item.Id, trans);
                        }
                        #endregion
                        #region 修改规格
                        if (demodel.IsCustomSpecification == 1)
                        {
                            if (goodsModel.IsProcurement != 1)
                            {
                                var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                if (slist.Count() != demodel.SpecificationList.Count() || slist.Count() != demodel.SpecificationList.Where(x => x.Id > 0).Count())
                                {
                                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    //删除后新增
                                    goods_SpecificationRepository.DeleteBatch(slist, trans);
                                    goods_SpecificationValueRepository.DeleteBatch(svlist, trans);
                                    goods_SpecificationPriceRepository.DeleteBatch(splist, trans);
                                    foreach (var item in demodel.SpecificationList)
                                    {
                                        int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            EnabledImage = item.EnabledImage,
                                            GoodsId = demodel.Id,
                                            Id = 0,
                                            MallBaseId = demodel.MallBaseId,
                                            Name = item.Name,
                                            Sort = item.Sort,
                                            Status = 0,
                                            TenantId = demodel.TenantId
                                        }, trans);
                                        if (sid > 0)
                                        {
                                            foreach (var qitem in item.SpecificationValueList)
                                            {
                                                goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                                {
                                                    CreateDate = demodel.CreateDate,
                                                    GoodsId = demodel.Id,
                                                    Id = 0,
                                                    Image = qitem.Image,
                                                    MallBaseId = demodel.MallBaseId,
                                                    Name = qitem.Name,
                                                    Sort = qitem.Sort,
                                                    Status = 0,
                                                    TenantId = demodel.TenantId,
                                                    SpecificationId = sid
                                                }, trans);
                                            }
                                        }
                                    }
                                    foreach (var item in demodel.SpecificationPriceList)
                                    {
                                        goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            GoodsId = demodel.Id,
                                            Id = 0,
                                            GoodsNumbers = item.GoodsNumbers,
                                            GoodsWeight = item.GoodsWeight,
                                            InventoryNum = item.InventoryNum,
                                            MallBaseId = demodel.MallBaseId,
                                            SellingPrice = item.SellingPrice,
                                            SpecificationSort = item.SpecificationSort,
                                            Status = 0,
                                            TenantId = demodel.TenantId,
                                            UpdateDate = demodel.UpdateDate
                                        }, trans);
                                    }
                                }
                                else
                                {
                                    //更新
                                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    foreach (var item in slist)
                                    {
                                        var supmodel = demodel.SpecificationList.Where(x => x.Id == item.Id).FirstOrDefault();
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_Specification.EnabledImage),supmodel.EnabledImage},
                                        { nameof(RB_Goods_Specification.Name),supmodel.Name},
                                        { nameof(RB_Goods_Specification.Sort),supmodel.Sort}
                                    };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Goods_Specification.Id),
                                              FiledValue=item.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                        bool flag1 = goods_SpecificationRepository.Update(keyValues1, wheres1, trans);
                                        if (flag1)
                                        {
                                            var sv2list = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                                            if (sv2list.Count() != supmodel.SpecificationValueList.Count() || sv2list.Count() != supmodel.SpecificationValueList.Where(x => x.Id > 0).Count())
                                            {
                                                goods_SpecificationValueRepository.DeleteBatch(sv2list, trans);
                                                foreach (var qitem in supmodel.SpecificationValueList)
                                                {
                                                    goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                                    {
                                                        CreateDate = demodel.CreateDate,
                                                        GoodsId = demodel.Id,
                                                        Id = 0,
                                                        Image = qitem.Image,
                                                        MallBaseId = demodel.MallBaseId,
                                                        Name = qitem.Name,
                                                        Sort = qitem.Sort,
                                                        Status = 0,
                                                        TenantId = demodel.TenantId,
                                                        SpecificationId = item.Id
                                                    }, trans);
                                                }
                                            }
                                            else
                                            {
                                                foreach (var qitem in sv2list)
                                                {
                                                    var supModel1 = supmodel.SpecificationValueList.Where(x => x.Id == qitem.Id).FirstOrDefault();
                                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                    { nameof(RB_Goods_SpecificationValue.Image),supModel1.Image},
                                                    { nameof(RB_Goods_SpecificationValue.Name),supModel1.Name},
                                                    { nameof(RB_Goods_SpecificationValue.Sort),supModel1.Sort}
                                                };
                                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                         FiledName=nameof(RB_Goods_Specification.Id),
                                                          FiledValue=qitem.Id,
                                                           OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                    goods_SpecificationValueRepository.Update(keyValues2, wheres2, trans);
                                                }
                                            }
                                        }
                                    }
                                    //价格新增/更新
                                    if (splist.Count() != demodel.SpecificationPriceList.Count() || splist.Count() != demodel.SpecificationPriceList.Where(x => splist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count())
                                    {
                                        goods_SpecificationPriceRepository.DeleteBatch(splist, trans);
                                        foreach (var item in demodel.SpecificationPriceList)
                                        {
                                            goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                            {
                                                CreateDate = demodel.CreateDate,
                                                GoodsId = demodel.Id,
                                                Id = 0,
                                                GoodsNumbers = item.GoodsNumbers,
                                                GoodsWeight = item.GoodsWeight,
                                                InventoryNum = item.InventoryNum,
                                                MallBaseId = demodel.MallBaseId,
                                                SellingPrice = item.SellingPrice,
                                                SpecificationSort = item.SpecificationSort,
                                                Status = 0,
                                                TenantId = demodel.TenantId,
                                                UpdateDate = demodel.UpdateDate
                                            }, trans);
                                        }
                                    }
                                    else
                                    {
                                        foreach (var item in splist)
                                        {
                                            var pupmodel = demodel.SpecificationPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                                            if (item.SellingPrice != pupmodel.SellingPrice || item.InventoryNum != pupmodel.InventoryNum || item.GoodsNumbers != pupmodel.GoodsNumbers || item.GoodsWeight != pupmodel.GoodsWeight)
                                            {
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                { nameof(RB_Goods_SpecificationPrice.SellingPrice),pupmodel.SellingPrice},
                                                { nameof(RB_Goods_SpecificationPrice.InventoryNum),pupmodel.InventoryNum},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsWeight),pupmodel.GoodsWeight},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsNumbers),pupmodel.GoodsNumbers}
                                            };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                     FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                                      FiledValue=item.Id,
                                                       OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                                goods_SpecificationPriceRepository.Update(keyValues1, wheres1, trans);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //只更新规格价格
                                var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                //价格新增/更新
                                if (splist.Count() != demodel.SpecificationPriceList.Count() || splist.Count() != demodel.SpecificationPriceList.Where(x => splist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count())
                                {
                                    goods_SpecificationPriceRepository.DeleteBatch(splist, trans);
                                    foreach (var item in demodel.SpecificationPriceList)
                                    {
                                        goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            GoodsId = demodel.Id,
                                            Id = 0,
                                            GoodsNumbers = item.GoodsNumbers,
                                            GoodsWeight = item.GoodsWeight,
                                            InventoryNum = item.InventoryNum,
                                            MallBaseId = demodel.MallBaseId,
                                            SellingPrice = item.SellingPrice,
                                            SpecificationSort = item.SpecificationSort,
                                            Status = 0,
                                            TenantId = demodel.TenantId,
                                            UpdateDate = demodel.UpdateDate
                                        }, trans);
                                    }
                                }
                                else
                                {
                                    foreach (var item in splist)
                                    {
                                        var pupmodel = demodel.SpecificationPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                                        if (item.SellingPrice != pupmodel.SellingPrice || item.InventoryNum != pupmodel.InventoryNum || item.GoodsNumbers != pupmodel.GoodsNumbers || item.GoodsWeight != pupmodel.GoodsWeight)
                                        {
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                { nameof(RB_Goods_SpecificationPrice.SellingPrice),pupmodel.SellingPrice},
                                                { nameof(RB_Goods_SpecificationPrice.InventoryNum),pupmodel.InventoryNum},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsWeight),pupmodel.GoodsWeight},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsNumbers),pupmodel.GoodsNumbers}
                                            };
                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                     FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                                      FiledValue=item.Id,
                                                       OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                            goods_SpecificationPriceRepository.Update(keyValues1, wheres1, trans);
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                        #region 修改区域
                        var alist = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        var insertList1 = demodel.AreaList.Where(x => !alist.Select(y => y.AreaId).Contains(x.AreaId)).ToList();
                        var deleteList1 = alist.Where(x => !demodel.AreaList.Select(y => y.AreaId).Contains(x.AreaId)).ToList();
                        foreach (var item in insertList1)
                        {
                            goods_AreaRepository.Insert(new RB_Goods_Area()
                            {
                                AreaId = item.AreaId,
                                AreaType = item.AreaType,
                                CreateDate = demodel.CreateDate,
                                GoodsId = demodel.Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                        foreach (var item in deleteList1)
                        {
                            goods_AreaRepository.Delete(item.Id, trans);
                        }


                        #endregion
                        //修改卡卷
                        #region 修改分销佣金
                        if (demodel.SeparateDistribution == 1)
                        {
                            //价格新增/更新
                            var dclist = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                            if (dclist.Count() != demodel.DistributionCommissionList.Count()
                                || dclist.Count() != demodel.DistributionCommissionList.Where(x => dclist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count()
                                || dclist.Select(x => x.DistributorGrade).Distinct().Count() != demodel.DistributionCommissionList.Select(x => x.DistributorGrade).Distinct().Count()
                                || dclist.Select(x => x.DistributorGrade).Distinct().Count() != dclist.Select(x => x.DistributorGrade).Distinct().Where(x => demodel.DistributionCommissionList.Select(y => y.DistributorGrade).Distinct().Contains(x)).Count())
                            {
                                goods_DistributionCommissionRepository.DeleteBatch(dclist, trans);
                                foreach (var item in demodel.DistributionCommissionList)
                                {
                                    goods_DistributionCommissionRepository.Insert(new RB_Goods_DistributionCommission()
                                    {
                                        CreateDate = demodel.CreateDate,
                                        GoodsId = demodel.Id,
                                        Id = 0,
                                        DistributorGrade = item.DistributorGrade,
                                        OneCommission = item.OneCommission,
                                        ThreeCommission = item.ThreeCommission,
                                        TwoCommission = item.TwoCommission,
                                        MallBaseId = demodel.MallBaseId,
                                        SpecificationSort = item.SpecificationSort,
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UpdateDate = demodel.UpdateDate
                                    }, trans);
                                }
                            }
                            else
                            {

                                foreach (var item in dclist)
                                {
                                    var pupmodel = demodel.DistributionCommissionList.Where(x => x.SpecificationSort == item.SpecificationSort && x.DistributorGrade == item.DistributorGrade).FirstOrDefault();
                                    if (item.OneCommission != pupmodel.OneCommission || item.TwoCommission != pupmodel.TwoCommission || item.ThreeCommission != pupmodel.ThreeCommission)
                                    {
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_DistributionCommission.OneCommission),pupmodel.OneCommission},
                                            { nameof(RB_Goods_DistributionCommission.TwoCommission),pupmodel.TwoCommission},
                                            { nameof(RB_Goods_DistributionCommission.ThreeCommission),pupmodel.ThreeCommission}
                                        };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_Goods_DistributionCommission.Id),
                                                    FiledValue=item.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goods_DistributionCommissionRepository.Update(keyValues1, wheres1, trans);
                                    }
                                }
                            }
                        }
                        #endregion
                        #region 修改会员价格
                        if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
                        {
                            var mplist = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                            if (mplist.Count() != demodel.MemberPriceList.Count()
                                || mplist.Count() != demodel.MemberPriceList.Where(x => mplist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count()
                                || mplist.Select(x => x.MemberGrade).Distinct().Count() != demodel.MemberPriceList.Select(x => x.MemberGrade).Distinct().Count()
                                || mplist.Select(x => x.MemberGrade).Distinct().Count() != mplist.Select(x => x.MemberGrade).Distinct().Where(x => demodel.MemberPriceList.Select(y => y.MemberGrade).Distinct().Contains(x)).Count())
                            {
                                goods_MemberPriceRepository.DeleteBatch(mplist, trans);
                                foreach (var item in demodel.MemberPriceList)
                                {
                                    goods_MemberPriceRepository.Insert(new RB_Goods_MemberPrice()
                                    {
                                        CreateDate = demodel.CreateDate,
                                        GoodsId = demodel.Id,
                                        Id = 0,
                                        MemberGrade = item.MemberGrade,
                                        MemberPrice = item.MemberPrice,
                                        MallBaseId = demodel.MallBaseId,
                                        SpecificationSort = item.SpecificationSort,
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UpdateDate = demodel.UpdateDate
                                    }, trans);
                                }
                            }
                            else
                            {

                                foreach (var item in mplist)
                                {
                                    var pupmodel = demodel.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort && x.MemberGrade == item.MemberGrade).FirstOrDefault();
                                    if (item.MemberPrice != pupmodel.MemberPrice)
                                    {
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_MemberPrice.MemberPrice),pupmodel.MemberPrice}
                                        };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_Goods_MemberPrice.Id),
                                                    FiledValue=item.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goods_MemberPriceRepository.Update(keyValues1, wheres1, trans);
                                    }
                                }
                            }
                        }
                        #endregion

                        #region 商品代理
                        //由代理  变成  非代理
                        if (goodsModel.IsProxy == 1 && demodel.IsProxy == 2)
                        {
                            //设置所有采购商品  下架  状态代理下架
                            var plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = demodel.Id, MallBaseId = goodsModel.MallBaseId, TenantId = goodsModel.TenantId });
                            string goodsIds = string.Join(",", plist.Select(x => x.ProxyGoodsId ?? 0));
                            var glist = goodsRepository.GetSingleListForGoodsId(new RB_Goods_Extend() { GoodsIds = goodsIds });
                            foreach (var item in glist)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods.GoodsStatus),2},
                                    { nameof(RB_Goods.ProcurementStatus),2},
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.Id),
                                          FiledValue=item.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goodsRepository.Update(keyValues1, wheres1);
                            }
                        }
                        else if ((goodsModel.IsProxy == 2 || goodsModel.IsProxy == 1) && demodel.IsProxy == 1 && demodel.GoodsStatus == 1)
                        {
                            //启用代理  检测是否有已代理的  同步数据  并采购商品状态
                            var plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = demodel.Id, MallBaseId = goodsModel.MallBaseId, TenantId = goodsModel.TenantId });
                            string goodsIds = string.Join(",", plist.Select(x => x.ProxyGoodsId ?? 0));
                            var glist = goodsRepository.GetSingleListForGoodsId(new RB_Goods_Extend() { GoodsIds = goodsIds });
                            //同步数据
                            foreach (var item in glist)
                            {
                                Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods.GoodsStatus),demodel.GoodsStatus},
                                    { nameof(RB_Goods.InventoryNum),demodel.InventoryNum},
                                    { nameof(RB_Goods.DefaultSpecificationName),demodel.DefaultSpecificationName},
                                    { nameof(RB_Goods.IsCustomSpecification),demodel.IsCustomSpecification},
                                    { nameof(RB_Goods.CostPrice),demodel.CostPrice},
                                    { nameof(RB_Goods.IsGoodsNegotiable),demodel.IsGoodsNegotiable},
                                    { nameof(RB_Goods.GoodsNumbers),demodel.GoodsNumbers},
                                    { nameof(RB_Goods.GoodsWeight),demodel.GoodsWeight},
                                    { nameof(RB_Goods.ProcurementStatus),1},
                                    { nameof(RB_Goods.UpdateDate),demodel.UpdateDate}
                                };
                                List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.Id),
                                          FiledValue=item.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                bool flag2 = goodsRepository.Update(keyValues2, wheres2);
                                if (flag2)
                                {
                                    //检测规格更新
                                    if (demodel.IsCustomSpecification == 1)
                                    {

                                    }
                                    else
                                    {
                                        //删除规格
                                        var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = item.Id, TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = item.Id, TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                                        var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = item.Id, TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                                        //删除
                                        goods_SpecificationRepository.DeleteBatch(slist);
                                        goods_SpecificationValueRepository.DeleteBatch(svlist);
                                        goods_SpecificationPriceRepository.DeleteBatch(splist);
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    int Id = goodsRepository.Insert(demodel, trans);
                    bool flag = Id > 0;
                    if (flag)
                    {
                        //插入分类
                        foreach (var item in demodel.CategoryList)
                        {
                            goods_CategoryRepository.Insert(new RB_Goods_Category()
                            {
                                CategoryId = item.CategoryId,
                                CreateDate = demodel.CreateDate,
                                GoodsId = Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                        //插入规格
                        if (demodel.IsCustomSpecification == 1)
                        {
                            foreach (var item in demodel.SpecificationList)
                            {
                                int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                                {
                                    CreateDate = demodel.CreateDate,
                                    EnabledImage = item.EnabledImage,
                                    GoodsId = Id,
                                    Id = 0,
                                    MallBaseId = demodel.MallBaseId,
                                    Name = item.Name,
                                    Sort = item.Sort,
                                    Status = 0,
                                    TenantId = demodel.TenantId
                                }, trans);
                                if (sid > 0)
                                {
                                    foreach (var qitem in item.SpecificationValueList)
                                    {
                                        goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            GoodsId = Id,
                                            Id = 0,
                                            Image = qitem.Image,
                                            MallBaseId = demodel.MallBaseId,
                                            Name = qitem.Name,
                                            Sort = qitem.Sort,
                                            Status = 0,
                                            TenantId = demodel.TenantId,
                                            SpecificationId = sid
                                        }, trans);
                                    }
                                }
                            }
                            foreach (var item in demodel.SpecificationPriceList)
                            {
                                goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                {
                                    CreateDate = demodel.CreateDate,
                                    GoodsId = Id,
                                    Id = 0,
                                    GoodsNumbers = item.GoodsNumbers,
                                    GoodsWeight = item.GoodsWeight,
                                    InventoryNum = item.InventoryNum,
                                    MallBaseId = demodel.MallBaseId,
                                    SellingPrice = item.SellingPrice,
                                    SpecificationSort = item.SpecificationSort,
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    UpdateDate = demodel.UpdateDate
                                }, trans);
                            }
                        }
                        //插入区域
                        foreach (var item in demodel.AreaList)
                        {
                            goods_AreaRepository.Insert(new RB_Goods_Area()
                            {
                                AreaId = item.AreaId,
                                AreaType = item.AreaType,
                                CreateDate = demodel.CreateDate,
                                GoodsId = Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                        //插入卡卷
                        //插入分销佣金
                        if (demodel.SeparateDistribution == 1)
                        {
                            foreach (var item in demodel.DistributionCommissionList)
                            {
                                goods_DistributionCommissionRepository.Insert(new RB_Goods_DistributionCommission()
                                {
                                    CreateDate = demodel.CreateDate,
                                    GoodsId = Id,
                                    Id = 0,
                                    DistributorGrade = item.DistributorGrade,
                                    OneCommission = item.OneCommission,
                                    ThreeCommission = item.ThreeCommission,
                                    TwoCommission = item.TwoCommission,
                                    MallBaseId = demodel.MallBaseId,
                                    SpecificationSort = item.SpecificationSort,
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    UpdateDate = demodel.UpdateDate
                                }, trans);
                            }
                        }
                        //插入会员价格
                        if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
                        {
                            foreach (var item in demodel.MemberPriceList)
                            {
                                goods_MemberPriceRepository.Insert(new RB_Goods_MemberPrice()
                                {
                                    CreateDate = demodel.CreateDate,
                                    GoodsId = Id,
                                    Id = 0,
                                    MemberGrade = item.MemberGrade,
                                    MemberPrice = item.MemberPrice,
                                    MallBaseId = demodel.MallBaseId,
                                    SpecificationSort = item.SpecificationSort,
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    UpdateDate = demodel.UpdateDate
                                }, trans);
                            }
                        }
                    }
                }
                goodsRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductGoodsInfo");
                goodsRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public RB_Goods_Extend GetProductGoodsInfo(int goodsId, int TenantId, int MallBaseId)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            model.SpecificationList = new List<RB_Goods_Specification_Extend>();
            model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (model.IsCustomSpecification == 1)
            {
                model.SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.SpecificationList.Any())
                {
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in svlist)
                    {
                        item.ImagePath = item.Image;
                    }
                    foreach (var item in model.SpecificationList)
                    {
                        item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                    }
                }
                int SortNum = 1;
                model.SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in model.SpecificationPriceList)
                {
                    if (!string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        var ssarr = item.SpecificationSort.Split(':');
                        int Sort = Convert.ToInt32(ssarr[0]);
                        string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                        List<object> AttrList = new List<object>();
                        for (int i = 0; i < ssarr.Length; i++)
                        {
                            var smodel = model.SpecificationList[i];
                            var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                            AttrList.Add(new
                            {
                                SName = smodel.Name,
                                SId = smodel.Id,
                                SVId = svmodel.Sort,
                                SVName = svmodel.Name
                            });
                        }
                        item.AttrList = AttrList;
                    }
                    item.SortNum = SortNum;
                    SortNum++;
                }
                model.SpecificationPriceList = model.SpecificationPriceList.OrderByDescending(x => x.SortNum).ToList();
            }
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            model.DistributionCommissionTreeList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });

                if (model.DistributionCommissionList.Any())
                {
                    int SortNum = 1;
                    //获取分销商启用等级
                    var dgradeList = distributor_GradeRepository.GetList(new RB_Distributor_Grade_Extend() { Enabled = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                    dgradeList.Add(new RB_Distributor_Grade_Extend()
                    {
                        Grade = 0,
                        Name = "默认等级",
                        Id = 0
                    });
                    string zdgradeStr = string.Join(",", dgradeList.Select(x => x.Id).OrderBy(x => x));
                    string ndgradeStr = string.Join(",", model.DistributionCommissionList.Select(x => x.DistributorGrade).Distinct().OrderBy(x => x));
                    var KeyList = model.DistributionCommissionList.Select(x => x.SpecificationSort ?? "").Distinct().ToList();
                    if (zdgradeStr == ndgradeStr)
                    {
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            treemodel.GradeCommissionList = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            if (model.SeparateDistributionType == 2)
                            {
                                if (!string.IsNullOrEmpty(qitem))
                                {
                                    var ssarr = qitem.Split(':');
                                    int Sort = Convert.ToInt32(ssarr[0]);
                                    string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                    List<object> AttrList = new List<object>();
                                    for (int i = 0; i < ssarr.Length; i++)
                                    {
                                        var smodel = model.SpecificationList[i];
                                        var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                        AttrList.Add(new
                                        {
                                            SName = smodel.Name,
                                            SId = smodel.Id,
                                            SVId = svmodel.Sort,
                                            SVName = svmodel.Name
                                        });
                                    }
                                    treemodel.AttrList = AttrList;
                                }
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradeCommissionList = treemodel.GradeCommissionList.OrderBy(x => x.DistributorGrade).ToList();
                            model.DistributionCommissionTreeList.Add(treemodel);
                        }
                    }
                    else
                    {//分销商等级有变更
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            treemodel.GradeCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
                            var gradeCommList = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            dgradeList = dgradeList.OrderByDescending(x => x.Grade).ToList();
                            foreach (var grade in dgradeList)
                            {
                                var gradeMList = gradeCommList.Where(x => x.DistributorGrade == grade.Id && x.SpecificationSort == qitem);
                                if (gradeMList.Any())
                                {
                                    treemodel.GradeCommissionList.AddRange(gradeMList);
                                }
                                else
                                {
                                    //表示新的
                                    treemodel.GradeCommissionList.Add(new RB_Goods_DistributionCommission_Extend()
                                    {
                                        DistributorGrade = grade.Id,
                                        OneCommission = 0,
                                        TwoCommission = 0,
                                        ThreeCommission = 0
                                    });
                                }
                            }
                            if (model.SeparateDistributionType == 2)
                            {
                                if (!string.IsNullOrEmpty(qitem))
                                {
                                    var ssarr = qitem.Split(':');
                                    int Sort = Convert.ToInt32(ssarr[0]);
                                    string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                    List<object> AttrList = new List<object>();
                                    for (int i = 0; i < ssarr.Length; i++)
                                    {
                                        var smodel = model.SpecificationList[i];
                                        var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                        AttrList.Add(new
                                        {
                                            SName = smodel.Name,
                                            SId = smodel.Id,
                                            SVId = svmodel.Sort,
                                            SVName = svmodel.Name
                                        });
                                    }
                                    treemodel.AttrList = AttrList;
                                }
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradeCommissionList = treemodel.GradeCommissionList.OrderBy(x => x.DistributorGrade).ToList();
                            model.DistributionCommissionTreeList.Add(treemodel);
                        }
                    }
                    SortNum++;
                    if (model.DistributionCommissionTreeList.Any())
                    {
                        //倒序排一次
                        model.DistributionCommissionTreeList = model.DistributionCommissionTreeList.OrderByDescending(x => x.Sort).ToList();
                    }
                }
            }
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            model.MemberPriceTreeList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.MemberPriceList.Any())
                {
                    int SortNum = 1;
                    var mgradeList = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { Enabled = 1, TenantId = 1, MallBaseId = 1 });

                    string zdgradeStr = string.Join(",", mgradeList.Select(x => x.Id).OrderBy(x => x));
                    string ndgradeStr = string.Join(",", model.MemberPriceList.Select(x => x.MemberGrade).Distinct().OrderBy(x => x));
                    if (zdgradeStr == ndgradeStr)
                    {
                        var KeyList = model.MemberPriceList.Select(x => x.SpecificationSort ?? "").Distinct().ToList();
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            treemodel.GradePriceList = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            if (!string.IsNullOrEmpty(qitem))
                            {
                                var ssarr = qitem.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> AttrList = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = model.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    AttrList.Add(new
                                    {
                                        SName = smodel.Name,
                                        SId = smodel.Id,
                                        SVId = svmodel.Sort,
                                        SVName = svmodel.Name
                                    });
                                }
                                treemodel.AttrList = AttrList;
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradePriceList = treemodel.GradePriceList.OrderBy(x => x.MemberGrade).ToList();
                            model.MemberPriceTreeList.Add(treemodel);
                        }
                    }
                    else
                    {//会员等级有变更
                        var KeyList = model.MemberPriceList.Select(x => x.SpecificationSort ?? "").Distinct().ToList();
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            //treemodel.GradePriceList = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            treemodel.GradePriceList = new List<RB_Goods_MemberPrice_Extend>() { };
                            var gradePrice = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            mgradeList = mgradeList.OrderByDescending(x => x.Grade).ToList();
                            foreach (var grade in mgradeList)
                            {
                                var gradeMList = gradePrice.Where(x => x.MemberGrade == grade.Id && x.SpecificationSort == qitem);
                                if (gradeMList.Any())
                                {
                                    treemodel.GradePriceList.AddRange(gradeMList);
                                }
                                else
                                {
                                    //表示新的
                                    treemodel.GradePriceList.Add(new RB_Goods_MemberPrice_Extend()
                                    {
                                        MemberGrade = grade.Id,
                                        MemberPrice = 0,
                                    });
                                }
                            }
                            if (!string.IsNullOrEmpty(qitem))
                            {
                                var ssarr = qitem.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> AttrList = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = model.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    AttrList.Add(new
                                    {
                                        SName = smodel.Name,
                                        SId = smodel.Id,
                                        SVId = svmodel.Sort,
                                        SVName = svmodel.Name
                                    });
                                }
                                treemodel.AttrList = AttrList;
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradePriceList = treemodel.GradePriceList.OrderBy(x => x.MemberGrade).ToList();
                            model.MemberPriceTreeList.Add(treemodel);
                        }
                    }

                    SortNum++;
                    if (model.MemberPriceTreeList.Any())
                    {
                        //倒序排一次
                        model.MemberPriceTreeList = model.MemberPriceTreeList.OrderByDescending(x => x.Sort).ToList();
                    }
                }
            }
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }
            model.CustomShareImagePath = model.CustomShareImage;
            //服务列表
            model.ServiceList = new List<RB_ImageCommonModel>();
            if (model.IsDefaultService == 2)
            {
                if (!string.IsNullOrEmpty(model.GoodsService) && model.GoodsService != "[]")
                {
                    List<int> ServiceIds = JsonConvert.DeserializeObject<List<int>>(model.GoodsService);
                    var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { ServiceIds = string.Join(",", ServiceIds), TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in slist)
                    {
                        model.ServiceList.Add(new RB_ImageCommonModel()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
            }
            //运费
            if (model.FreightId > 0)
            {
                model.FreightName = logistics_RulesRepository.GetEntity(model.FreightId)?.RulesName ?? "";
            }
            else
            {
                model.FreightName = "默认运费";
            }
            //表单
            if (model.FormsId > 0)
            {
                model.FormsName = "未建表";
            }
            else
            {
                model.FormsName = "默认表单";
            }

            return model;
        }

        /// <summary>
        /// 快速修改
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="type"></param>
        /// <param name="sort"></param>
        /// <param name="goodsName"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetProductGoodsQuickUpdate(int goodsId, int type, int sort, string goodsName, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues;
            if (type == 1)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Sort),sort}
                };
            }
            else if (type == 2)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Name),goodsName}
                };
            }
            else if (type == 3)
            {
                var model = goodsRepository.GetEntity(goodsId);
                if (model == null)
                {
                    return false;
                }
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsQuickBuy),model.IsQuickBuy==1?2:1}
                };
            }
            
            else
            {
                return false;
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=goodsId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goodsRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 快速修改
        /// </summary>
        /// <param name="goodsIds"></param>
        /// <param name="type"></param>
        /// <param name="sort"></param>
        /// <param name="goodsName"></param>
        /// <param name="freightId"></param>
        /// <param name="limitBuyGoodsNum"></param>
        /// <param name="limitBuyOrderNum"></param>
        /// <param name="integralPresent"></param>
        /// <param name="integralPresentType"></param>
        /// <param name="pointsDeduction"></param>
        /// <param name="pointsDeductionType"></param>
        /// <param name="isMultipleDeduction"></param>
        /// <param name="isQuickBuy"></param>
        /// <param name="isGoodsNegotiable"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetProductGoodsQuickUpdate(string goodsIds, int type, int sort, string goodsName, int freightId, int limitBuyGoodsNum, int limitBuyOrderNum, int integralPresent, int integralPresentType, decimal pointsDeduction, int pointsDeductionType, int isMultipleDeduction, int isQuickBuy, int isGoodsNegotiable,int SupplierId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues;
            if (type == 1)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Sort),sort}
                };
            }//排序
            else if (type == 2)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Name),goodsName}
                };
            }//商品名称
            else if (type == 3)
            {
                var model = goodsRepository.GetEntity(Convert.ToInt32(goodsIds));
                if (model == null)
                {
                    return false;
                }
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsQuickBuy),model.IsQuickBuy==1?2:1}
                };
            }//单个快速购买
            else if (type == 4)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.GoodsStatus),1}
                };
            }//上架
            else if (type == 5)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.GoodsStatus),2}
                };
            }//下架
            else if (type == 6)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Status),1}
                };
            }//删除
            else if (type == 7)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.FreightId),freightId}
                };
            }//运费
            else if (type == 8)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.LimitBuyGoodsNum),limitBuyGoodsNum},
                    { nameof(RB_Goods.LimitBuyOrderNum),limitBuyOrderNum},
                };
            }//限购
            else if (type == 9)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IntegralPresent),integralPresent},
                    { nameof(RB_Goods.IntegralPresentType),integralPresentType},
                    { nameof(RB_Goods.PointsDeduction),pointsDeduction},
                    { nameof(RB_Goods.PointsDeductionType),pointsDeductionType},
                    { nameof(RB_Goods.IsMultipleDeduction),isMultipleDeduction},
                };
            }//积分
            else if (type == 10)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsQuickBuy),isQuickBuy}
                };
            }//批量快速购买
            else if (type == 11)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsGoodsNegotiable),isGoodsNegotiable}
                };
            }//面议
            else if (type == 12)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.SupplierId),SupplierId}
                };
            }//面议
            else
            {
                return false;
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=goodsIds,
                        OperatorEnum=OperatorEnum.IN
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goodsRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProcudtGoodsInfo(int goodsId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods.Status),1},
                { nameof(RB_Goods.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=goodsId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goodsRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_Grade_Extend> GetMemberGradeList(RB_Member_Grade_Extend dmodel)
        {
            var list = member_GradeRepository.GetList(dmodel);
            return list;
        }

        /// <summary>
        /// 获取分销等级列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Grade_Extend> GetDistributorGradeList(RB_Distributor_Grade_Extend demodel)
        {
            var list = distributor_GradeRepository.GetList(demodel);
            return list;
        }



        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetGoodsList(RB_Goods_Extend dmodel)
        {
            return goodsRepository.GetList(dmodel);
        }
        #endregion

        #region 商品代理

        /// <summary>
        /// 新增代理商品
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="categoryList"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult SetProductGoodsProxy(int goodsId, List<int> categoryList, int tenantId, int mallBaseId)
        {
            var plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId });
            if (plist.Any())
            {
                return ApiResult.Failed("该商品已存在采购");
            }
            var goodsModel = goodsRepository.GetEntity(goodsId);
            if (goodsModel == null)
            {
                return ApiResult.Failed("采购商品不存在");
            }
            if (goodsModel.GoodsStatus != 1)
            {
                return ApiResult.Failed("该商品未上架，无法采购");
            }
            if (goodsModel.IsProxy != 1)
            {
                return ApiResult.Failed("采购商品不可代理");
            }
            if (goodsModel.IsProcurement == 1)
            {
                return ApiResult.Failed("采购商品不可代理");
            }
            if (goodsModel.TenantId == tenantId)
            {
                return ApiResult.Failed("不可采购同商户商品");
            }
            if ((goodsModel.ProxyMoney ?? 0) <= 0)
            {
                return ApiResult.Failed("采购商品有误");
            }

            var trans = goodsRepository.DbTransaction;
            try
            {
                //复制商品信息
                int Id = goodsRepository.Insert(new RB_Goods()
                {
                    Name = goodsModel.Name,
                    CarouselImage = goodsModel.CarouselImage,
                    VideoAddress = goodsModel.VideoAddress,
                    CustomShareTitles = goodsModel.CustomShareTitles,
                    CustomShareImage = goodsModel.CustomShareImage,
                    GoodsStatus = goodsModel.GoodsStatus,
                    InventoryNum = goodsModel.InventoryNum,
                    DefaultSpecificationName = goodsModel.DefaultSpecificationName,
                    IsCustomSpecification = goodsModel.IsCustomSpecification,
                    Sort = goodsModel.Sort,
                    SellingPrice = goodsModel.SellingPrice,
                    OriginalPrice = goodsModel.OriginalPrice,
                    Unit = goodsModel.Unit,
                    CostPrice = goodsModel.ProxyMoney,
                    IsGoodsNegotiable = goodsModel.IsGoodsNegotiable,
                    SalesNum = goodsModel.SalesNum,
                    GoodsNumbers = goodsModel.GoodsNumbers,
                    GoodsWeight = goodsModel.GoodsWeight,
                    IsDefaultService = 1,
                    GoodsService = "[]",
                    FreightId = 0,
                    FormsId = 0,
                    LimitBuyGoodsNum = goodsModel.LimitBuyGoodsNum,
                    LimitBuyOrderNum = goodsModel.LimitBuyOrderNum,
                    FullNumPinkage = goodsModel.FullNumPinkage,
                    FullMoneyPinkage = goodsModel.FullMoneyPinkage,
                    IsAreaBuy = 2,
                    IntegralPresent = goodsModel.IntegralPresent,
                    IntegralPresentType = goodsModel.IntegralPresentType,
                    PointsDeduction = goodsModel.PointsDeduction,
                    PointsDeductionType = goodsModel.PointsDeductionType,
                    IsMultipleDeduction = goodsModel.IsMultipleDeduction,
                    GoodsDetails = goodsModel.GoodsDetails,
                    Status = 0,
                    TenantId = tenantId,
                    MallBaseId = mallBaseId,
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    SeparateDistribution = 2,
                    SeparateDistributionType = 1,
                    SeparateDistributionMoneyType = 1,
                    EnjoyMember = 2,
                    SeparateSetMember = 2,
                    IsQuickBuy = 2,
                    IsSellWell = 2,
                    GoodsType = goodsModel.GoodsType,
                    SupplierId = 0,
                    IsProxy = 2,
                    ProxyType = 1,
                    ProxyRises = 0,
                    ProxyMoney = 0,
                    IsProcurement = 1,
                    ProcurementStatus = 1
                }, trans);
                if (Id > 0)
                {
                    goods_ProxyRepository.Insert(new RB_Goods_Proxy()
                    {
                        CreateDate = DateTime.Now,
                        GoodsId = goodsId,
                        Id = 0,
                        MallBaseId = goodsModel.MallBaseId,
                        TenantId = goodsModel.TenantId,
                        ProxyGoodsId = Id,
                        ProxyMallBaseId = mallBaseId,
                        ProxyTenantId = tenantId,
                        Remark = "新增采购",
                        Status = 0
                    }, trans);
                    //商品分类
                    foreach (var item in categoryList)
                    {
                        goods_CategoryRepository.Insert(new RB_Goods_Category()
                        {
                            CategoryId = item,
                            CreateDate = DateTime.Now,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = mallBaseId,
                            Status = 0,
                            TenantId = tenantId
                        }, trans);
                    }
                    //复制规格
                    var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId });
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId });
                    foreach (var item in slist)
                    {
                        goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                        {
                            EnabledImage = item.EnabledImage,
                            CreateDate = DateTime.Now,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = mallBaseId,
                            Name = item.Name,
                            Sort = item.Sort,
                            Status = 0,
                            TenantId = tenantId
                        }, trans);
                    }
                    foreach (var item in svlist)
                    {
                        goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                        {
                            TenantId = tenantId,
                            Status = 0,
                            Sort = item.Sort,
                            CreateDate = DateTime.Now,
                            GoodsId = Id,
                            Id = 0,
                            Image = item.Image,
                            MallBaseId = mallBaseId,
                            Name = item.Name,
                            SpecificationId = item.SpecificationId
                        }, trans);
                    }
                }
                goodsRepository.DBSession.Commit();
                if (Id > 0)
                    return ApiResult.Success();
                else
                    return ApiResult.Failed();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductGoodsProxy");
                goodsRepository.DBSession.Rollback("SetProductGoodsProxy");
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 取消商品代理
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="type"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool CancelGoodsProxy(int goodsId, int type, int tenantId, int mallBaseId)
        {
            var plist = new List<RB_Goods_Proxy_Extend>();
            if (type == 1)
            {
                plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId });
            }
            else
            {
                plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { ProxyGoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId });
            }
            if (!plist.Any())
            {
                return false;
            }
            var pModel = plist.FirstOrDefault();
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_Proxy.Status),1},
                { nameof(RB_Goods_Proxy.Remark),DateTime.Now.ToString("yyyy-MM-dd")+ " 取消代理"}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Proxy.Id),
                      FiledValue=pModel.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_ProxyRepository.Update(keyValues, wheres);
            if (flag)
            {
                //删除商品
                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Status),1},
                    { nameof(RB_Goods.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods.Id),
                          FiledValue=pModel.ProxyGoodsId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                goodsRepository.Update(keyValues1, wheres1);
            }
            return flag;
        }

        /// <summary>
        /// 设置采购商品上下架
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="type">类型  1上架   2下架</param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetGoodsProxyStatus(int goodsId, int type, int tenantId, int mallBaseId)
        {
            var goodsModel = goodsRepository.GetEntity(goodsId);
            if (goodsModel == null)
            {
                return false;
            }
            if (goodsModel.IsProcurement != 1)
            {
                return false;
            }
            if (goodsModel.ProcurementStatus != 1)
            {
                return false;
            }
            int GoodsStatus = 1;
            if (type == 1)
            {
                if (goodsModel.GoodsStatus != 2)
                {
                    return false;
                }
            }
            else
            {
                if (goodsModel.GoodsStatus != 1)
                {
                    return false;
                }
                GoodsStatus = 2;
            }

            var pModel = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { ProxyGoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId }).FirstOrDefault();
            if (pModel == null) { return false; }
            var gModel = goodsRepository.GetEntity(pModel.GoodsId);
            if (gModel == null) { return false; }
            if (gModel.GoodsStatus == 1 && gModel.IsProxy == 1)
            {
                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                    { nameof(RB_Goods.GoodsStatus),GoodsStatus},
                    { nameof(RB_Goods.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Goods.Id),
                            FiledValue=goodsModel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                return goodsRepository.Update(keyValues1, wheres1);
            }
            return false;
        }

        #endregion

        #region 商品导入

        /// <summary>
        /// 赞羊商品导入
        /// </summary>
        /// <param name="path_server"></param>
        /// <param name="goodsStatus"></param>
        /// <param name="categoryIdList"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string SetGoodsBatchImport(string path_server, int goodsStatus, List<int> categoryIdList, int tenantId, int mallBaseId)
        {
            if (!System.IO.File.Exists(path_server))
            {
                return "导入文件已删除，请刷新后重新导入再试";
            }
            int FileType = path_server.Contains(".csv") ? 1 : 2;//1 赞羊导入   2 和平导入
            //处理文件内容读取
            List<RB_Goods_Extend> list = DataHelper.GoodsBetchDataHelper.ImportClaimData(path_server);
            list = list.Where(x => !string.IsNullOrWhiteSpace(x.Name)).ToList();
            if (list.Any())
            {
                List<string> AreaName = new List<string>();
                foreach (var item in list)
                {
                    #region 导入验证
                    if (string.IsNullOrEmpty(item.Name))
                    {
                        return "有商品名称为空，无法导入";
                    }
                    if ((item.OriginalPrice ?? 0) < 0)
                    {
                        return "商品原价为空：" + item.Name;
                    }
                    if ((item.SellingPrice ?? 0) < 0)
                    {
                        return "商品售价为空：" + item.Name;
                    }
                    if (string.IsNullOrEmpty(item.CoverImage))
                    {
                        return "封面图为空：" + item.Name;
                    }
                    if (string.IsNullOrEmpty(item.CarouselImage))
                    {
                        return "轮播图为空：" + item.Name;
                    }
                    if (item.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationImport))
                        {
                            return "规格组为空：" + item.Name;
                        }
                        if (string.IsNullOrEmpty(item.SpecificationPriceImport))
                        {
                            return "规格详情为空：" + item.Name;
                        }
                    }
                    if (item.IsAreaBuy == 1)
                    {
                        if (string.IsNullOrEmpty(item.AreaImport))
                        {
                            return "区域购买为空：" + item.Name;
                        }
                    }

                    if (FileType == 1)
                    {
                        try
                        {
                            //转化轮播图
                            List<GoodsCarouselImport> CarouseList = JsonConvert.DeserializeObject<List<GoodsCarouselImport>>(item.CarouselImage);
                            item.CarouselImage = JsonConvert.SerializeObject(CarouseList.Select(x => x.pic_url));//转化为系统格式
                        }
                        catch (Exception)
                        {
                            return "轮播图格式有误";
                        }
                        item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                        item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                        item.AreaList = new List<RB_Goods_Area_Extend>();
                        try
                        {
                            List<GoodsSpecificationImport> SpecificationList = JsonConvert.DeserializeObject<List<GoodsSpecificationImport>>(item.SpecificationImport);
                            List<GoodsSpecificationPriceImport> SpecificationPriceList = JsonConvert.DeserializeObject<List<GoodsSpecificationPriceImport>>(item.SpecificationPriceImport);
                            //转化规格组
                            if (item.IsCustomSpecification == 1)
                            {
                                //规格组转化
                                int Num = 1;
                                foreach (var qitem in SpecificationList)
                                {
                                    List<RB_Goods_SpecificationValue_Extend> SpecificationValueList = new List<RB_Goods_SpecificationValue_Extend>();
                                    int EnabledImage = 2;
                                    foreach (var qqitem in qitem.attr_list)
                                    {
                                        if (!string.IsNullOrEmpty(qqitem.pic_url))
                                        {
                                            EnabledImage = 1;
                                        }
                                        SpecificationValueList.Add(new RB_Goods_SpecificationValue_Extend()
                                        {
                                            Sort = qqitem.attr_id,
                                            Name = FromUnicodeString(qqitem.attr_name),
                                            Image = qqitem.pic_url
                                        });
                                    }
                                    if (Num > 1) { EnabledImage = 2; }
                                    item.SpecificationList.Add(new RB_Goods_Specification_Extend()
                                    {
                                        Sort = qitem.attr_group_id,
                                        Name = FromUnicodeString(qitem.attr_group_name),
                                        EnabledImage = EnabledImage,
                                        SpecificationValueList = SpecificationValueList
                                    });
                                    Num++;
                                }
                                //规格详情转化
                                foreach (var qitem in SpecificationPriceList)
                                {
                                    item.SpecificationPriceList.Add(new RB_Goods_SpecificationPrice_Extend()
                                    {
                                        SpecificationSort = qitem.sign_id,
                                        GoodsNumbers = FromUnicodeString(qitem.no),
                                        GoodsWeight = qitem.weight,
                                        InventoryNum = qitem.stock,
                                        SellingPrice = qitem.price
                                    });
                                }
                            }
                            else
                            {
                                item.DefaultSpecificationName = SpecificationList.FirstOrDefault()?.attr_list?.FirstOrDefault()?.attr_name ?? "";
                                item.GoodsNumbers = SpecificationPriceList.FirstOrDefault()?.no ?? "";
                                item.GoodsWeight = SpecificationPriceList.FirstOrDefault()?.weight ?? 0;
                            }
                            item.GoodsId = SpecificationPriceList.FirstOrDefault()?.goods_id ?? 0;
                        }
                        catch (Exception)
                        {
                            return "规格组/规格详情有误";
                        }
                        try
                        {
                            //转化区域
                            if (item.IsAreaBuy == 1)
                            {
                                List<GoodsAreaListImport> GoodsAreaList = JsonConvert.DeserializeObject<List<GoodsAreaListImport>>(item.AreaImport);
                                foreach (var qitem in GoodsAreaList)
                                {
                                    foreach (var qqitem in qitem.list)
                                    {
                                        item.AreaList.Add(new RB_Goods_Area_Extend()
                                        {
                                            AreaName = qqitem.name//拿到name  查询根据系统区域表再次查询所有的区域拿到id
                                        });
                                        AreaName.Add("'" + (qqitem.name ?? "") + "'");
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            return "区域格式有误";
                        }

                        try
                        {
                            if (item.GoodsId <= 0)
                            {
                                return "商品id不存在：" + item.Name;
                            }
                            var goodsModel = goodsRepository.GetEntity(item.GoodsId);
                            if (goodsModel != null)
                            {
                                return "商品id已存在：" + item.Name + " ,id:" + item.GoodsId;
                            }
                        }
                        catch (Exception)
                        {
                            return "商品id获取出错了";
                        }
                    }
                    else
                    {
                        try
                        {
                            //转化轮播图
                            List<string> CarouseList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        }
                        catch (Exception)
                        {
                            return "轮播图格式有误";
                        }
                        item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                        item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                        item.AreaList = new List<RB_Goods_Area_Extend>();
                        try
                        {
                            item.SpecificationList = JsonConvert.DeserializeObject<List<RB_Goods_Specification_Extend>>(item.SpecificationImport);
                            item.SpecificationPriceList = JsonConvert.DeserializeObject<List<RB_Goods_SpecificationPrice_Extend>>(item.SpecificationPriceImport);
                            //转化规格组
                            if (item.IsCustomSpecification != 1)
                            {
                                item.DefaultSpecificationName = item.SpecificationList.FirstOrDefault()?.SpecificationValueList?.FirstOrDefault()?.Name ?? "";
                                item.GoodsNumbers = item.SpecificationPriceList.FirstOrDefault()?.GoodsNumbers ?? "";
                                item.GoodsWeight = item.SpecificationPriceList.FirstOrDefault()?.GoodsWeight ?? 0;
                            }

                            //item.Id = item.SpecificationPriceList.FirstOrDefault()?.GoodsId ?? 0;
                        }
                        catch (Exception)
                        {
                            return "规格组/规格详情有误";
                        }
                        try
                        {
                            //转化区域
                            if (item.IsAreaBuy == 1)
                            {
                                item.AreaList = JsonConvert.DeserializeObject<List<RB_Goods_Area_Extend>>(item.AreaImport);
                            }
                        }
                        catch (Exception)
                        {
                            return "区域格式有误";
                        }
                    }
                    #endregion

                    #region 规格验证

                    if (item.IsCustomSpecification == 1)
                    {

                        if (item.SpecificationList.Count() != item.SpecificationList.Select(x => x.Sort).Distinct().Count())
                        {
                            return "商品规格组排序有误：" + item.Name;
                        }
                        int TotalNum = 1;
                        foreach (var qitem in item.SpecificationList)
                        {
                            if (qitem.SpecificationValueList.Count() != qitem.SpecificationValueList.Select(x => x.Sort).Distinct().Count())
                            {
                                return "商品规格组排序有误：" + item.Name;
                            }
                            TotalNum *= qitem.SpecificationValueList.Count();
                            if (qitem.EnabledImage != 1)
                            {
                                foreach (var qqitem in qitem.SpecificationValueList)
                                {
                                    qqitem.Image = "";
                                }
                            }
                        }
                        //验证总keys数量
                        if (item.SpecificationPriceList.Count() != TotalNum)
                        {
                            return "商品规格明细数量有误：" + item.Name;
                        }
                        //初始化所有keys
                        List<string> KeyList = new List<string>();
                        for (var i = 1; i <= TotalNum; i++)
                        {
                            KeyList.Add("");
                        }
                        int MGBJNum = 1;
                        //组装所有keys
                        foreach (var qitem in item.SpecificationList)
                        {
                            int LBBJNum = TotalNum / qitem.SpecificationValueList.Count() / MGBJNum;
                            int KeyIndex = 0;
                            for (var i = 1; i <= LBBJNum; i++)
                            {
                                foreach (var qqitem in qitem.SpecificationValueList)
                                {
                                    for (var j = 1; j <= MGBJNum; j++)
                                    {
                                        KeyList[KeyIndex] = KeyList[KeyIndex] + ":" + qqitem.Sort;
                                        KeyIndex++;
                                    }
                                }
                            }
                        }
                        //验证所有keys
                        foreach (var qitem in KeyList)
                        {
                            string keys = qitem[1..];
                            var pricemodel = item.SpecificationPriceList.Where(x => x.SpecificationSort == keys).FirstOrDefault();
                            if (pricemodel == null)
                            {
                                return "商品规格价格Key有误：" + item.Name;
                            }
                            pricemodel.InventoryNum ??= 0;
                            pricemodel.SellingPrice ??= 0;
                            pricemodel.GoodsNumbers ??= "";
                            pricemodel.GoodsWeight ??= 0;
                            item.InventoryNum += (pricemodel.InventoryNum ?? 0);
                        }
                        //主表价格  如果有自定义规格，直接取最小值
                        item.SellingPrice = item.SpecificationPriceList.Min(x => x.SellingPrice ?? 0);
                    }

                    #endregion

                    #region 商品分类
                    item.CategoryList = new List<RB_Goods_Category_Extend>();
                    foreach (var qitem in categoryIdList)
                    {
                        item.CategoryList.Add(new RB_Goods_Category_Extend()
                        {
                            CategoryId = qitem
                        });
                    }
                    #endregion

                    #region 赋默认值

                    item.GoodsStatus = goodsStatus;
                    item.DefaultSpecificationName ??= "";
                    item.GoodsNumbers ??= "";
                    item.GoodsWeight ??= 0;
                    item.IsDefaultService ??= 1;
                    item.GoodsService = "[]";
                    item.FreightId ??= 0;
                    item.FormsId ??= 0;
                    item.SeparateDistribution ??= 2;
                    item.SeparateDistributionType ??= 1;
                    item.SeparateDistributionMoneyType ??= 1;
                    item.EnjoyMember ??= 2;
                    item.SeparateSetMember ??= 2;
                    item.GoodsType ??= Common.Enum.Goods.OrderTypeEnum.Mall;

                    item.IsProxy ??= 2;
                    item.ProxyType ??= 0;
                    item.ProxyRises ??= 0;
                    item.ProxyMoney ??= 0;
                    item.IsProcurement = 2;

                    item.Status = 0;
                    item.TenantId = tenantId;
                    item.MallBaseId = mallBaseId;
                    item.CreateDate = DateTime.Now;
                    item.UpdateDate = DateTime.Now;

                    #endregion

                    #region 修正默认
                    item.Name = item.Name.Replace("\t", "");
                    item.IsSellWell = item.IsSellWell == 1 ? 1 : 2;
                    item.IsQuickBuy = item.IsQuickBuy == 1 ? 1 : 2;
                    item.IsGoodsNegotiable = item.IsGoodsNegotiable == 1 ? 1 : 2;
                    item.IsAreaBuy = item.IsAreaBuy == 1 ? 1 : 2;
                    item.IsMultipleDeduction = item.IsMultipleDeduction == 1 ? 1 : 2;
                    item.IsCustomSpecification = item.IsCustomSpecification == 1 ? 1 : 2;
                    #endregion
                }
                //根据区域名称  查找所有区域id
                List<Model.Extend.BaseSetUp.RB_Destination_Extend> destList = new List<Model.Extend.BaseSetUp.RB_Destination_Extend>();
                if (FileType == 1)
                {
                    destList = destinationRepository.GetListExt(new Model.Extend.BaseSetUp.RB_Destination_Extend() { NameStr = string.Join(",", AreaName.Distinct()) });
                }
                var trans = goodsRepository.DbTransaction;
                DateTime dt = DateTime.Now;
                try
                {
                    foreach (var item in list)
                    {
                        if (item.IsAreaBuy == 1 && FileType == 1)
                        {
                            foreach (var qitem in item.AreaList)
                            {
                                qitem.AreaId = destList.Where(x => x.Name == qitem.AreaName).FirstOrDefault()?.ID;
                                qitem.AreaType = (int)(destList.Where(x => x.Name == qitem.AreaName).FirstOrDefault()?.CodeLevel ?? Common.Enum.AreaRegionEnum.CountryEnum);
                            }
                        }
                        bool flag = SetGoodsImportInfo(item, trans);
                        if (flag == false)
                        {
                            goodsRepository.DBSession.Rollback();
                            return "请联系管理员，商品导入失败：" + item.Name;
                        }
                    }
                    goodsRepository.DBSession.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetGoodsBatchImport");
                    goodsRepository.DBSession.Rollback();
                    System.IO.File.Delete(path_server);
                    return "出错啦，请联系管理员";
                }
            }
            System.IO.File.Delete(path_server);
            return "";
        }

        /// <summary>
        /// 新增商品导入
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGoodsImportInfo(RB_Goods_Extend demodel, System.Data.IDbTransaction trans)
        {
            try
            {
                int Id = goodsRepository.Insert(demodel, trans);
                bool flag = Id > 0;
                if (flag)
                {
                    if (demodel.GoodsId > 0)
                    {
                        goodsRepository.SetGoodsNewId(demodel.GoodsId ?? 0, Id, trans);
                        Id = demodel.GoodsId ?? 0;
                    }
                    //插入分类
                    foreach (var item in demodel.CategoryList)
                    {
                        goods_CategoryRepository.Insert(new RB_Goods_Category()
                        {
                            CategoryId = item.CategoryId,
                            CreateDate = demodel.CreateDate,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        }, trans);
                    }
                    //插入规格
                    if (demodel.IsCustomSpecification == 1)
                    {
                        foreach (var item in demodel.SpecificationList)
                        {
                            int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                            {
                                CreateDate = demodel.CreateDate,
                                EnabledImage = item.EnabledImage,
                                GoodsId = Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Name = item.Name,
                                Sort = item.Sort,
                                Status = 0,
                                TenantId = demodel.TenantId
                            }, trans);
                            if (sid > 0)
                            {
                                foreach (var qitem in item.SpecificationValueList)
                                {
                                    goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                    {
                                        CreateDate = demodel.CreateDate,
                                        GoodsId = Id,
                                        Id = 0,
                                        Image = qitem.Image,
                                        MallBaseId = demodel.MallBaseId,
                                        Name = qitem.Name,
                                        Sort = qitem.Sort,
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        SpecificationId = sid
                                    }, trans);
                                }
                            }
                        }
                        foreach (var item in demodel.SpecificationPriceList)
                        {
                            goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                            {
                                CreateDate = demodel.CreateDate,
                                GoodsId = Id,
                                Id = 0,
                                GoodsNumbers = item.GoodsNumbers,
                                GoodsWeight = item.GoodsWeight,
                                InventoryNum = item.InventoryNum,
                                MallBaseId = demodel.MallBaseId,
                                SellingPrice = item.SellingPrice,
                                SpecificationSort = item.SpecificationSort,
                                Status = 0,
                                TenantId = demodel.TenantId,
                                UpdateDate = demodel.UpdateDate
                            }, trans);
                        }
                    }
                    //插入区域
                    foreach (var item in demodel.AreaList)
                    {
                        goods_AreaRepository.Insert(new RB_Goods_Area()
                        {
                            AreaId = item.AreaId,
                            AreaType = item.AreaType,
                            CreateDate = demodel.CreateDate,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        }, trans);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetGoodsImportInfo");
                return false;
            }
        }

        /// <summary>
        /// unicode 解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string FromUnicodeString(string str)
        {
            //最直接的方法Regex.Unescape(str);
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str) && str.Contains("\\u"))
            {
                string[] strlist = str.Replace("\\", "").Split('u');
                try
                {
                    for (int i = 1; i < strlist.Length; i++)
                    {
                        int charCode = Convert.ToInt32(strlist[i], 16);
                        strResult.Append((char)charCode);
                    }
                }
                catch (FormatException)
                {
                    return Regex.Unescape(str);
                }
                return strResult.ToString();
            }
            return str;
        }

        #endregion



        #region 分销商
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Info_Extend> GetDistributorInfoList(RB_Distributor_Info_Extend dmodel)
        {
            return distributor_InfoRepository.GetList(dmodel);
        }
        #endregion


     
    }
}
