using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.AOP.CustomerAttribute;
using Mall.Common.API;
using Mall.Common.Enum.Goods;
using Mall.Common.Plugin;
using Mall.Model.Entity.BaseSetUp;
using Mall.Model.Entity.GuideCar;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.Reserve;
using Mall.Model.Entity.User;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.GuideCar;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Repository.BaseSetUp;
using Mall.Repository.GuideCar;
using Mall.Repository.MarketingCenter;
using Mall.Repository.Product;
using Mall.Repository.Reserve;
using Mall.Repository.User;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 线下服务商品管理
    /// </summary>
    public class OfflineGoodsModule
    {

        /// <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_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 商品可预定日期
        /// </summary>
        private readonly RB_Goods_TargetDateRepository goods_TargetDateRepository = new RB_Goods_TargetDateRepository();
        /// <summary>
        /// 商品日志
        /// </summary>
        private readonly RB_Goods_LogRepository goods_LogRepository = new RB_Goods_LogRepository();
        /// <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_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 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_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 商品评论
        /// </summary>
        private readonly RB_Goods_CommentRepository goods_CommentRepository = new RB_Goods_CommentRepository();
        /// <summary>
        /// 地区处理
        /// </summary>
        private readonly Rb_destinationRepository destinationRepository = new Rb_destinationRepository();
        /// <summary>
        /// 商品分销
        /// </summary>
        private readonly RB_MiniProgram_GoodPosterRepository miniProgram_GoodPosterRepository = new RB_MiniProgram_GoodPosterRepository();
        /// <summary>
        /// 粉象返佣
        /// </summary>
        private readonly RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();
        /// <summary>
        /// 粉象VIP返佣比例
        /// </summary>
        private readonly RB_Distributor_FXCommissionRepository distributor_FXCommissionRepository = new RB_Distributor_FXCommissionRepository();
        /// <summary>
        /// 微店基础
        /// </summary>
        private RB_SmallShops_CustomRepository smallShops_CustomRepository = new RB_SmallShops_CustomRepository();
        /// <summary>
        /// 微店
        /// </summary>
        private RB_SmallShops_InfoRepository smallShops_InfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 微店商品价格
        /// </summary>
        private RB_SmallShops_PriceRepository smallShops_PriceRepository = new RB_SmallShops_PriceRepository();
        /// <summary>
        /// 司导站点
        /// </summary>
        private RB_GuideCar_SiteRepository SiteRepository = new RB_GuideCar_SiteRepository();
        /// <summary>
        /// 司导站点地区
        /// </summary>
        private RB_GuideCar_SiteRegionRepository SiteRegionRepository = new RB_GuideCar_SiteRegionRepository();
        /// <summary>
        /// 司导基础配置
        /// </summary>
        private RB_GuideCar_BaseRepository guideCar_BaseRepository = new RB_GuideCar_BaseRepository();
        /// <summary>
        /// 司导基础配置
        /// </summary>
        private RB_GuideCar_GuideRepository GuideRepository = new RB_GuideCar_GuideRepository();
        /// <summary>
        /// 车辆
        /// </summary>
        private RB_GuideCar_CarRepository GuideCarRepository = new RB_GuideCar_CarRepository();
        /// <summary>
        /// 车辆颜色
        /// </summary>
        private RB_GuideCar_CarColorRepository CarColorRepository = new RB_GuideCar_CarColorRepository();
        /// <summary>
        /// 积分规则
        /// </summary>
        private readonly RB_Integral_SettingsRepository integral_SettingsRepository = new RB_Integral_SettingsRepository();
        /// <summary>
        /// 小程序基础
        /// </summary>
        private readonly RB_MallBaseRepository mallBaseRepository = new RB_MallBaseRepository();
        /// <summary>
        /// 小程序
        /// </summary>
        private readonly RB_MiniProgramRepository miniProgramRepository = new RB_MiniProgramRepository();
        /// <summary>
        /// 运费
        /// </summary>
        private readonly RB_Logistics_RulesRepository logistics_RulesRepository = new RB_Logistics_RulesRepository();
        private readonly RB_Logistics_RulesRegionRepository logistics_RulesRegionRepository = new RB_Logistics_RulesRegionRepository();
        /// <summary>
        /// 优惠卷
        /// </summary>
        private readonly RB_Member_CouponRepository member_CouponRepository = new RB_Member_CouponRepository();
        private readonly RB_DiscountCouponRepository discountCouponRepository = new RB_DiscountCouponRepository();
        private readonly RB_DiscountCoupon_ProductRepository discountCoupon_ProductRepository = new RB_DiscountCoupon_ProductRepository();


        /// <summary>
        /// 车辆搜索模块
        /// </summary>
        private RB_GuideCar_CarSearchSearchRepository carSearchSearchRepository = new RB_GuideCar_CarSearchSearchRepository();

        /// <summary>
        /// 车辆搜索模块
        /// </summary>
        private RB_GuideCar_CarBrandRepository carBrandRepository = new RB_GuideCar_CarBrandRepository();

        /// <summary>
        /// 用户积分
        /// </summary>
        private readonly RB_Member_IntegralRepository member_IntegralRepository = new RB_Member_IntegralRepository();

        /// <summary>
        /// 门店仓储层对象
        /// </summary>
        private readonly RB_StoresRepository storesRepository = new RB_StoresRepository();
        /// <summary>
        /// 服务人员仓储层对象
        /// </summary>
        private readonly RB_Reserve_ServicePersonalRepository reserveServicePersonalRepository = new RB_Reserve_ServicePersonalRepository();

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

        #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> GetOfflineProductGoodsPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetPageListForCommission(pageIndex, pageSize, out count, demodel, 3);
            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 storesIds = string.Join(",", list.Where(qitem => !string.IsNullOrWhiteSpace(qitem.StoresIds)).Select(qitem => qitem.StoresIds));
                List<RB_Stores_Extend> storeList = new List<RB_Stores_Extend>();
                if (!string.IsNullOrWhiteSpace(storesIds))
                {
                    storeList = storesRepository.GetStoresListRepository(new RB_Stores_Extend() { QIds = storesIds });
                }

                foreach (var item in list)
                {
                    item.StoreNameList = new List<string>();
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    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];
                        //轮播图
                        foreach (var qitem in CarouselIdList)
                        {
                            item.CarouselImageList.Add(new RB_ImageCommonModel()
                            {
                                Id = 0,
                                Name = "",
                                Path = qitem
                            });
                        }
                    }
                    item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
                    if (!string.IsNullOrEmpty(item.StoresIds))
                    {
                        List<int> storesResultList = Common.ConvertHelper.ConvertToListInt(item.StoresIds);

                        if (storesResultList != null && storesResultList.Count > 0)
                        {
                            foreach (var sItem in storesResultList)
                            {
                                string storeName = storeList?.Where(qitem => qitem.Id == sItem)?.FirstOrDefault()?.Name ?? "";
                                if (!string.IsNullOrEmpty(storeName))
                                {
                                    item.StoreNameList.Add(storeName);
                                }

                            }
                        }

                    }
                }
            }
            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> GetProductGoodsPageListToExcel(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetPageListForCommission(pageIndex, pageSize, out count, demodel, 3);
            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 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 });
                }
                #region 查询司导信息
                string siteIds = string.Join(",", list.Select(x => x.SiteId));
                var sitelist = SiteRepository.GetGuideCarSiteList(new RB_GuideCar_Site_Extend() { SiteIds = siteIds });
                string guideIds = string.Join(",", list.Select(x => x.GuideId));
                var guidelist = GuideRepository.GetGuideCarGuideList(new RB_GuideCar_Guide_Extend() { GuideIds = guideIds });
                string carids = string.Join(",", list.Select(x => x.CarId));
                var carlist = GuideCarRepository.GetGuideCarCarList(new RB_GuideCar_Car_Extend() { GuideCarIds = carids });
                string colorIds = string.Join(",", list.Select(x => x.CarColorId));
                var carcolorlist = CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend() { CarColorIds = colorIds });
                #endregion
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    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];
                        //轮播图
                        foreach (var qitem in CarouselIdList)
                        {
                            item.CarouselImageList.Add(new RB_ImageCommonModel()
                            {
                                Id = 0,
                                Name = "",
                                Path = qitem
                            });
                        }
                    }

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

            #region 可预定日期
            model.TargetDateList = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = goodsId });
            #endregion
            if (!string.IsNullOrEmpty(model.LineDescription) && model.LineDescription != "[]")
            {
                model.LineDescriptionList = JsonConvert.DeserializeObject<List<string>>(model.LineDescription);
            }
            return model;
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetProductGoodsInfo(RB_Goods_Extend demodel)
        {
            bool flag = false;
            demodel.GoodsClassify = 3;
            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},
                        { nameof(RB_Goods.Commission),demodel.Commission},
                        { nameof(RB_Goods.PresentFXGrade),demodel.PresentFXGrade},
                        { nameof(RB_Goods.PresentFXMonth),demodel.PresentFXMonth},
                        { nameof(RB_Goods.Advertising),demodel.Advertising},
                        { nameof(RB_Goods.SubName),demodel.SubName},
                        { nameof(RB_Goods.MarketingLogo),demodel.MarketingLogo},
                        { nameof(RB_Goods.IsLiveGoods),demodel.IsLiveGoods},
                        { nameof(RB_Goods.ShelvesDate),demodel.ShelvesDate },
                        { nameof(RB_Goods.DownDate),demodel.DownDate },
                        { nameof(RB_Goods.SendArea),demodel.SendArea },
                        { nameof(RB_Goods.SiteId),demodel.SiteId },
                        { nameof(RB_Goods.GuideId),demodel.GuideId },
                        { nameof(RB_Goods.CarId),demodel.CarId },
                        { nameof(RB_Goods.CarColorId),demodel.CarColorId },
                        { nameof(RB_Goods.CarNumber),demodel.CarNumber },
                        { nameof(RB_Goods.CarBuyYear),demodel.CarBuyYear },
                        { nameof(RB_Goods.CarType),demodel.CarType },
                        { nameof(RB_Goods.UseDay),demodel.UseDay },
                        { nameof(RB_Goods.LineName),demodel.LineName },
                        { nameof(RB_Goods.LineDescription),demodel.LineDescription },
                        { nameof(RB_Goods.IsSpell),demodel.IsSpell },
                        { nameof(RB_Goods.RideNum),demodel.RideNum },
                        { nameof(RB_Goods.AdvanceDay),demodel.AdvanceDay },
                        { nameof(RB_Goods.VideoType),demodel.VideoType },
                        { nameof(RB_Goods.IntegralComment),demodel.IntegralComment },
                        { nameof(RB_Goods.IntegralCommentType),demodel.IntegralCommentType },
                        { nameof(RB_Goods.GoodsType),demodel.GoodsType },
                        { nameof(RB_Goods.GoodsPageType),demodel.GoodsPageType },
                        { nameof(RB_Goods.DepositMoney),demodel.DepositMoney },
                        { nameof(RB_Goods.IsChooseServicePerson),demodel.IsChooseServicePerson },
                        { nameof(RB_Goods.StoresIds),demodel.StoresIds },
                        { nameof(RB_Goods.Remark),demodel.Remark },
                        { nameof(RB_Goods.ServiceTime),demodel.ServiceTime },
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>()
                    {
                        new WhereHelper(nameof(RB_Goods.Id),demodel.Id) ,
                        new WhereHelper(nameof(RB_Goods.TenantId),demodel.TenantId) ,
                        new WhereHelper(nameof(RB_Goods.MallBaseId),demodel.MallBaseId)
                    };
                    flag = goodsRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        #region 修改可预定日期
                        var tdlist = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = demodel.Id });
                        var tdinsertList = demodel.TargetDateList.Where(x => !tdlist.Select(y => y.Date).Contains(x.Date)).ToList();
                        var tddeleteList = tdlist.Where(x => !demodel.TargetDateList.Select(y => y.Date).Contains(x.Date)).ToList();
                        foreach (var item in tdinsertList)
                        {
                            goods_TargetDateRepository.Insert(new RB_Goods_TargetDate()
                            {
                                Id = 0,
                                GoodsId = demodel.Id,
                                Date = item.Date,
                                IsReserve = 1,
                                ReserveNum = 0
                            });
                        }
                        foreach (var item in tddeleteList)
                        {
                            goods_TargetDateRepository.Delete(item);
                        }
                        #endregion

                        #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 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
                            });
                        }
                        foreach (var item in deleteList)
                        {
                            goods_CategoryRepository.Delete(item.Id);
                        }
                        #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
                            });
                        }
                        foreach (var item in deleteList1)
                        {
                            goods_AreaRepository.Delete(item.Id);
                        }
                        #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);
                                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
                                    });
                                }
                            }
                            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}
                                        };
                                        goods_DistributionCommissionRepository.Update(keyValues1, new WhereHelper(nameof(RB_Goods_DistributionCommission.Id), item.Id));
                                    }
                                }
                            }
                        }
                        #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);
                                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
                                    });
                                }
                            }
                            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}
                                        };
                                        goods_MemberPriceRepository.Update(keyValues1, new WhereHelper(nameof(RB_Goods_MemberPrice.Id), item.Id));
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    int Id = goodsRepository.Insert(demodel);
                    flag = Id > 0;
                    if (flag)
                    {
                        //插入可预定日期
                        if (demodel.TargetDateList != null && demodel.TargetDateList.Count > 0)
                        {
                            foreach (var item in demodel.TargetDateList)
                            {
                                goods_TargetDateRepository.Insert(new RB_Goods_TargetDate()
                                {
                                    Id = 0,
                                    GoodsId = Id,
                                    Date = item.Date,
                                    IsReserve = 1,
                                    ReserveNum = 0
                                });
                            }
                        }
                        //插入分类
                        if (demodel.CategoryList != null && demodel.CategoryList.Count > 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
                                });
                            }
                        }
                        //插入区域
                        if (demodel.AreaList != null && demodel.AreaList.Count > 0)
                        {
                            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
                                });
                            }
                        }
                        //插入分销佣金
                        if (demodel.SeparateDistribution == 1)
                        {
                            if (demodel.DistributionCommissionList != null && demodel.DistributionCommissionList.Count > 0)
                            {
                                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
                                    });
                                }
                            }
                        }
                        //插入会员价格
                        if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
                        {
                            if (demodel.MemberPriceList != null && demodel.MemberPriceList.Count > 0)
                            {
                                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
                                    });
                                }
                            }
                        }
                    }
                }
                flag = true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductGoodsInfoSD:" + Common.Plugin.JsonHelper.Serialize(demodel));
            }
            return flag;
        }

        /// <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(nameof(RB_Goods.Id),goodsId) ,
                new WhereHelper(nameof(RB_Goods.TenantId),tenantId) ,
                new WhereHelper(nameof(RB_Goods.MallBaseId),mallBaseId)
            };
            return goodsRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 设置商品上下架
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetGoodsStatusInfo(int goodsId, int tenantId, int mallBaseId)
        {
            var goodsModel = goodsRepository.GetEntity(goodsId);
            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                { nameof(RB_Goods.GoodsStatus),(goodsModel?.GoodsStatus??0)==1?2:1},
                { nameof(RB_Goods.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Goods.Id),goodsId),
                new WhereHelper(nameof(RB_Goods.TenantId),tenantId),
                new WhereHelper(nameof(RB_Goods.MallBaseId),mallBaseId)
            };
            return goodsRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 设置商品上下架
        /// </summary>
        /// <param name="goodsIds"></param>
        /// <param name="Type"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetGoodsBatchStatusInfo(string goodsIds, int Type, int tenantId, int mallBaseId)
        {
            var list = goodsRepository.GetSingleListForCommission(new RB_Goods_Extend() { GoodsIds = goodsIds }, 1);
            foreach (var goodsModel in list)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Goods.GoodsStatus),Type},
                    { nameof(RB_Goods.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Goods.Id),goodsModel.Id),
                    new WhereHelper(nameof(RB_Goods.TenantId),tenantId),
                    new WhereHelper(nameof(RB_Goods.MallBaseId),mallBaseId),
                };
                goodsRepository.Update(keyValues, wheres);
            }
            return true;
        }

        #endregion

        #region 添加订单评论返积分

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

        }
        #endregion





        /// <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="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetProductGoodsList(RB_Goods_Extend demodel, int SmallShopsId = 0)
        {
            var list = goodsRepository.GetList(demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                RB_SmallShops_Info_Extend smallModel = new RB_SmallShops_Info_Extend();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsIds = ids });
                }
                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> GetServicePersonalGoodsList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel, int GoodsClassify)
        {
            var list = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                RB_SmallShops_Info_Extend smallModel = new RB_SmallShops_Info_Extend();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                List<RB_Goods_SpecificationPrice_Extend> spriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                //商品Id
                string ids = string.Join(",", list.Select(x => x.Id));
                //if (SmallShopsId > 0)
                //{
                //    smallModel = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(SmallShopsId);
                //    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsIds = ids });
                //    spriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = ids });
                //}
                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="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderDetail_Extend> GetReserveOrderList(RB_Goods_Order_Extend dmodel)
        {
            return goods_OrderDetailRepository.GetReserveOrderList(dmodel);
        }

        #region 评论

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


        /// <summary>
        /// 管理新增评论
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetReserveGoodsCommentInfo(List<RB_Goods_Comment_Extend> list)
        {
            RB_Goods_OrderDetail dmodel = new RB_Goods_OrderDetail();
            if (list.FirstOrDefault().OrderDetailId > 0)
            {
                dmodel = goods_OrderDetailRepository.GetEntity(list.FirstOrDefault().OrderDetailId);
                if (dmodel == null) { return false; }
                if (dmodel.IsComment == 1) { return false; }
            }
            bool flag = goods_CommentRepository.InsertBatch(list);
            if (flag)
            {
                if (list.FirstOrDefault().OrderDetailId > 0)
                {
                    //更新订单商品为已评价
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Goods_OrderDetail.IsComment),1}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_OrderDetail.Id),
                              FiledValue=list.FirstOrDefault().OrderDetailId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    goods_OrderDetailRepository.Update(keyValues, wheres);
                    //更新订单对应对应的商品和服务人员评分
                    //先查找已评论的商品信息 
                    if (dmodel.GoodsId.HasValue && dmodel.GoodsId.Value > 0)
                    {
                        var carScoreList = goods_CommentRepository.GetAppletReserveGoodsCommentscore(dmodel.GoodsId.Value, 0, dmodel.TenantId, dmodel.MallBaseId);
                        decimal carScore = 0;
                        if (carScoreList != null && carScoreList.Any() && carScoreList.FirstOrDefault().CommentNum>0)
                        {
                            carScore = carScoreList.FirstOrDefault().TotalScore / carScoreList.FirstOrDefault().CommentNum;
                        }
                        else
                        {
                            carScore = Convert.ToDecimal(list.Where(x => x.GoodsId == dmodel.GoodsId).FirstOrDefault().CommentScore);
                        }
                        if (carScore > 0)//更新车辆的评分
                        {
                            //更新订单商品为已评价
                            Dictionary<string, object> keyValuesCar = new Dictionary<string, object>() {
                                { nameof(RB_Goods.CourseScore),Math.Round(carScore,1, MidpointRounding.AwayFromZero)}
                            };
                            List<WhereHelper> wheresCar = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Goods.Id),
                                      FiledValue=dmodel.GoodsId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goodsRepository.Update(keyValuesCar, wheresCar);
                        }
                    }
                    if (dmodel.ServicepersonalId.HasValue && dmodel.ServicepersonalId.Value > 0)
                    {
                        decimal guidScore = 0;
                        var guideScoreList = goods_CommentRepository.GetAppletReserveGoodsCommentscore(0, dmodel.ServicepersonalId.Value, dmodel.TenantId, dmodel.MallBaseId);
                        if (guideScoreList != null && guideScoreList.Any()&& guideScoreList.FirstOrDefault().CommentNum>0)
                        {
                            guidScore = guideScoreList.FirstOrDefault().TotalScore / guideScoreList.FirstOrDefault().CommentNum;
                        }
                        else
                        {
                            guidScore = Convert.ToDecimal(list.Where(x => x.ServicePersonalId == dmodel.ServicepersonalId).FirstOrDefault().CommentScore);
                        }

                        if (guidScore > 0)//更新车辆的评分
                        {
                            //更新订单商品为已评价
                            Dictionary<string, object> keyValuesCar = new Dictionary<string, object>() {
                                { nameof(RB_Reserve_ServicePersonal.Score),Math.Round(guidScore,1, MidpointRounding.AwayFromZero)}
                            };
                            List<WhereHelper> wheresCar = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Reserve_ServicePersonal.ID),
                                      FiledValue=dmodel.ServicepersonalId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            reserveServicePersonalRepository.Update(keyValuesCar, wheresCar);
                        }
                    }
                }
            }
            return flag;
        }


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

        #endregion

    }
}