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.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.User;
using Newtonsoft.Json;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 司导专区处理层
    /// </summary>
    public class GuideCarModule
    {

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


        #region 基础配置
        /// <summary>
        /// 获取基础配置
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_GuideCar_Base_Extend GetGuideCarInfo(int tenantId, int mallBaseId)
        {
            var model = guideCar_BaseRepository.GetList(new RB_GuideCar_Base_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                model = new RB_GuideCar_Base_Extend()
                {
                    AdvanceDay = 1,
                    MallBaseId = mallBaseId,
                    CancelHour = 1,
                    CostPrice = 0,
                    Id = 0,
                    InsuranceDescription = "",
                    InsuranceName = "",
                    IsConfirm = 1,
                    PagePath = "",
                    SalePrice = 0,
                    TenantId = tenantId,
                };
            }
            if (model.OrderStateJson == null || model.OrderStateJson == "" || model.OrderStateJson == "[]")
            {
                var list = EnumHelper.GetEnumList(typeof(Common.Enum.Goods.OrderStatusEnum));
                model.OrderStateList = list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new GrudeCarStateModel
                {
                    Name = x.Key,
                    Id = Convert.ToInt32(x.Value)
                }).ToList();
            }
            else
            {
                model.OrderStateList = JsonConvert.DeserializeObject<List<GrudeCarStateModel>>(model.OrderStateJson);
            }
            return model;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGuideCarInfo(RB_GuideCar_Base_Extend demodel)
        {
            var model = guideCar_BaseRepository.GetList(new RB_GuideCar_Base_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return guideCar_BaseRepository.Insert(demodel) > 0;
            }
            else
            {
                model.UpdateBy = demodel.UpdateBy;
                model.AdvanceDay = demodel.AdvanceDay;
                model.CancelHour = demodel.CancelHour;
                model.CostPrice = demodel.CostPrice;
                model.InsuranceDescription = demodel.InsuranceDescription;
                model.InsuranceName = demodel.InsuranceName;
                model.IsConfirm = demodel.IsConfirm;
                model.OrderStateJson = demodel.OrderStateJson;
                model.PagePath = demodel.PagePath;
                model.SalePrice = demodel.SalePrice;
                model.UpdateDate = demodel.UpdateDate;
                return guideCar_BaseRepository.Update(model);
            }
        }

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

        #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.GetPageListForCommission(pageIndex, pageSize, out count, demodel, 1);
            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 = "";
                    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;
                }
            }
            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, 1);
            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 = 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;

            #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="goodsIs"></param>
        /// <param name="tdlist"></param>
        /// <returns></returns>
        public string ValidateGoodsTargetDate(int goodsId, List<RB_Goods_TargetDate_Extend> tdlist)
        {
            var oldtdlist = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = goodsId });
            var tddeleteList = oldtdlist.Where(x => !tdlist.Select(y => y.Date).Contains(x.Date)).ToList();
            string msg = "";
            foreach (var item in tddeleteList)
            {
                //看是否有不可预约的 / 有预定人数的
                if (item.IsReserve == 2 || item.ReserveNum > 0)
                {
                    msg += item.Date.Value.ToString("yyyy-MM-dd") + ",";
                }
            }
            if (msg != "")
            {
                msg = msg[..1];
                msg += " 已有订单预定，无法修改当前日期";
            }
            return msg;
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductGoodsInfo(RB_Goods_Extend demodel)
        {
            var goodsModel = new RB_Goods();
            if (demodel.Id > 0)
            {
                goodsModel = goodsRepository.GetEntity(demodel.Id);
                if (goodsModel == null)
                {
                    return false;
                }
            }
            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 },
                    };
                    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);
                    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}
                                        };
                                        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);
                                    }
                                }
                            }
                        }
                        #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}
                                        };
                                        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);
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    int Id = goodsRepository.Insert(demodel);
                    bool flag = Id > 0;
                    if (flag)
                    {
                        //插入可预定日期
                        foreach (var item in demodel.TargetDateList)
                        {
                            goods_TargetDateRepository.Insert(new RB_Goods_TargetDate()
                            {
                                Id = 0,
                                GoodsId = Id,
                                Date = item.Date,
                                IsReserve = 1,
                                ReserveNum = 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
                            });
                        }
                        //插入区域
                        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)
                        {
                            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)
                        {
                            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
                                });
                            }
                        }
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductGoodsInfoSD:" + Common.Plugin.JsonHelper.Serialize(demodel));
                return false;
            }
        }

        /// <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="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(){
                        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="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(){
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=goodsModel.Id,
                        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
                }
            };
                goodsRepository.Update(keyValues, wheres);
            }
            return true;
        }

        #endregion

        #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="goodsId"></param>
        /// <param name="UserId"></param>
        /// <param name="SmallShopsId"></param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public object GetAppletGoodsInfo_V2(int goodsId, int UserId, int SmallShopsId, 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 ?? "";

            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            if (UserId > 0)
            {
                userModel = member_UserRepository.GetEntity<RB_Member_User_Extend>(UserId);
                if (SmallShopsId == 0)
                {
                    SmallShopsId = userModel.SmallShopId;
                }
            }

            #region 基本信息
            //查询分类
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });

            #region 微店价格
            RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
            List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
            if (SmallShopsId > 0)
            {
                smallModel = smallShops_InfoRepository.GetEntity(SmallShopsId);
                smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsId = goodsId });
                if (((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any()))
                {
                    var sspModel = smallPList.Where(x => x.SpecificationKey == "").FirstOrDefault();
                    if (sspModel != null)
                    {
                        //单商品设置的
                        if (sspModel.PriceType == 1)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                        }
                        else if (sspModel.PriceType == 2)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + (sspModel.UpPrice ?? 0);
                        }
                    }
                    else
                    {
                        if ((smallModel.UpPrice ?? 0) > 0)
                        {
                            if (smallModel.PriceType == 1)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                            }
                            else if (smallModel.PriceType == 2)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + (smallModel.UpPrice ?? 0);
                            }
                        }
                    }
                }
            }
            #endregion

            //最大售价
            decimal MaxSellMoney = model.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 });
            }

            #region 微店处理会员价格
            if (model.MemberPriceList.Any() && SmallShopsId > 0)
            {
                if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any())
                {
                    foreach (var item in model.MemberPriceList)
                    {
                        var sspModel = smallPList.Where(x => x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                        if (sspModel != null)
                        {
                            //单商品设置的
                            if (sspModel.PriceType == 1)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            }
                            else if (sspModel.PriceType == 2)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            }
                        }
                        else
                        {
                            if ((smallModel.UpPrice ?? 0) > 0)
                            {
                                if (smallModel.PriceType == 1)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                }
                                else if (smallModel.PriceType == 2)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            //轮播
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrWhiteSpace(model.VideoAddress))
            {
                model.CarouselImageList.Add(new RB_ImageCommonModel()
                {
                    Id = 0,
                    Name = "",
                    Type = 1,
                    Path = model.VideoAddress
                });
            }
            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;
            #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.MaxShare = 0;
            decimal MyBuyCommission = 0;//自购返利
            var BasicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            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)
                {
                    if ((BasicsModel?.IsEnableFXGrade ?? 2) == 1)
                    {
                        if ((model.PresentFXGrade ?? 0) == 0)
                        {
                            var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                            if (FXList.Any() && FXList.Where(x => x.IsGuest == 1).Any())
                            {
                                var FXModel = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault();
                                var PModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                                if (FXModel != null && PModel != null)
                                {
                                    decimal CRate = 0;
                                    if (FXModel.Id == PModel.Id)
                                    {
                                        CRate = FXModel.SiblingRatio ?? 0;
                                    }
                                    else
                                    {
                                        CRate = (FXModel.CommissionRatio ?? 0) - (PModel.CommissionRatio ?? 0);
                                    }

                                    if (model.IsCustomSpecification == 1)
                                    {
                                        var dcModel = model.SpecificationPriceList.OrderByDescending(x => x.Commission).FirstOrDefault();
                                        if (dcModel.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (model.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //是否展示分享vip佣金
                            var fxcommissionList = distributor_FXCommissionRepository.GetFXCommissionList(new RB_Distributor_FXCommission_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, FXGradeId = disModel.FXGradeId ?? 0 });
                            if (fxcommissionList.Any())
                            {
                                model.MaxShare = fxcommissionList.Max(x => x.CommissionPrice ?? 0);
                            }
                        }
                    }
                    else
                    {
                        if (model.SeparateDistribution == 1)
                        {
                            var dcList = model.DistributionCommissionList.Where(x => x.DistributorGrade == disModel.GradeId).ToList();
                            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)
                            {
                                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)
                                {
                                    model.MaxShare = disgradeModel?.OneCommission ?? 0;
                                    if ((disgradeModel?.DistributionCommissionType ?? 2) == 1)
                                    {
                                        model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

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

            #region 组装价格
            List<object> priceList = new List<object>();

            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 = "",
                price = model.SellingPrice ?? 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 == 1)
                {
                    Integral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralPresent ?? 0) / 100));
                }
            }

            int CommentIntegral = 0;
            if (model.IntegralComment > 0)
            {
                CommentIntegral = model.IntegralComment ?? 0;
                if (model.IntegralCommentType == 1)
                {
                    CommentIntegral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralComment ?? 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.Where(x => x.SellingPrice > 0).Min(x => x.SellingPrice ?? 0);
                    price_member_max = price_max = model.SpecificationPriceList.Where(x => x.SellingPrice > 0).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 司导商品
            string SiteName = SiteRepository.GetGuideCarSiteList(new RB_GuideCar_Site_Extend() { ID = model.SiteId ?? 0 }).FirstOrDefault()?.SiteName ?? "";
            var guideModel = GuideRepository.GetGuideCarGuideList(new RB_GuideCar_Guide_Extend() { ID = model.GuideId ?? 0 }).FirstOrDefault();
            model.GuideName = guideModel?.Name ?? "";
            model.GuidePhoto = guideModel?.GuidePhoto ?? "";
            model.GuideScore = guideModel?.Score ?? 5;
            model.Introduction = guideModel?.Introduction ?? "";
            model.GuideWorkYears = guideModel?.WorkYears ?? 1;
            var carModel = GuideCarRepository.GetGuideCarCarList(new RB_GuideCar_Car_Extend() { ID = model.CarId ?? 0 }).FirstOrDefault();
            string CarName = carModel?.Name ?? "";
            model.CarColorName = CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend() { ID = model.CarColorId ?? 0 }).FirstOrDefault()?.ColorName ?? "";
            model.CarScore = carModel?.Score ?? 5;
            model.CarModel = carModel?.CarType ?? "";
            model.LineDescriptionList = new List<string>();
            if (!string.IsNullOrEmpty(model.LineDescription) && model.LineDescription != "[]")
            {
                model.LineDescriptionList = JsonConvert.DeserializeObject<List<string>>(model.LineDescription);
            }
            #endregion

            #region 返回参数

            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;
            }
            var tempLogo = new MarketingLogoItem();
            if (!string.IsNullOrEmpty(model?.MarketingLogo))
            {
                try
                {
                    tempLogo = Common.Plugin.JsonHelper.DeserializeObject<MarketingLogoItem>(model?.MarketingLogo);
                }
                catch
                {
                    tempLogo = new MarketingLogoItem();
                }
            }
            return new
            {
                goods = new
                {
                    id = model.Id,
                    mall_id = model.MallBaseId,
                    mch_id = model.TenantId,//暂  商户id
                    status = model.GoodsStatus,
                    isAllowShare = IsAllowShare,//是否可以分享
                    advertising = model.Advertising,//广告词
                    price = model.SellingPrice,
                    member_price = price_member_max,
                    site_name = SiteName,
                    site_id = model.SiteId,
                    guide_name = model.GuideName,
                    guide_id = model.GuideId,
                    guide_photo = model.GuidePhoto,
                    guide_introduction = model.Introduction,
                    guide_workyears = model.GuideWorkYears,
                    guide_score = model.GuideScore,
                    car_name = CarName,
                    car_id = model.CarId,
                    car_score = model.CarScore,
                    carcolor_name = model.CarColorName,
                    car_model = model.CarModel,
                    carcolor_id = model.CarColorId,
                    car_number = model.CarNumber,
                    car_buyyear = model.CarBuyYear,
                    car_type = model.CarType,
                    car_type_name = model.CarType.GetEnumName(),
                    use_day = model.UseDay,
                    line_name = model.LineName,
                    line_descriptionlist = model.LineDescriptionList,
                    is_spell = model.IsSpell,
                    ride_num = model.RideNum,                 
                    advance_day = model.AdvanceDay,
                    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,//分销佣金类型
                    app_share_pic = model.CustomShareImagePath,
                    app_share_title = model.CustomShareTitles,
                    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") : "",
                    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
                    }) } },
                    name = model.Name,
                    original_price = model.OriginalPrice,
                    cover_pic = model.CoverImage,
                    detail = model.GoodsDetails,
                    video_url = model.VideoAddress,
                    level_show = (userModel?.MemberGrade ?? 0) > 0 ? 1 : 2,//是否显示会员价
                    is_sales = model.GoodsStatus,//是否可购买   ______根据日期判断     。。。。。。。。。。。。。。。。。。。。。。。。。。
                    //attr = priceList,
                    pic_url = model.CarouselImageList.Select(x => new
                    {
                        id = x.Id,
                        pic_url = x.Path,
                        type = x.Type
                    }),
                    share = model.MaxShare,//分销佣金
                    myBuyCommission = MyBuyCommission,//粉象模式  自购返利
                    favorite = model.Favorite,//是否收藏
                    goods_marketing = new
                    {
                        limit
                    },
                    goods_marketing_award = new
                    {
                        integral = new
                        {
                            title = Integral > 0 ? "购买可得" + Integral + "积分" : ""
                        },
                        commentIntegral = new
                        {
                            title = CommentIntegral > 0 ? "购买并评论可得" + Integral + "积分" : ""
                        }
                    },
                    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") : ""
                    },
                    marketingLogo = tempLogo,
                    cats = model.CategoryList.Select(x => new
                    {
                        x.CategoryId,
                        x.CategoryName
                    })//分类
                },
                delivery = ""
            };
            #endregion
            #endregion
        }

        /// <summary>
        /// 获取小程序司导商品结算页面详情
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult GetAppletSDGoodsSettlementInfo(RB_Goods_Order_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            if (demodel.SmallShopsId == 0)
            {
                demodel.SmallShopsId = umodel.SmallShopId;
            }
            //积分
            Model.Entity.MarketingCenter.RB_Integral_Settings integralModel = new Model.Entity.MarketingCenter.RB_Integral_Settings();
            if (umodel.Integral > 0)
            {
                integralModel = integral_SettingsRepository.GetIntegralSettingsList(new Model.Entity.MarketingCenter.RB_Integral_Settings() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            }
            //快递默认
            demodel.DeliveryMethod ??= OrderDeliveryMethodEnum.VerificationShop;
            #region 区域
            var disList = new List<int>
            {
                demodel.District ?? 0,
                demodel.City ?? 0,
                demodel.Province ?? 0
            };
            #endregion

            List<object> DList = new List<object>();
            decimal TotalGoodsMoney = 0, TotalGoodsOriginalMoney = 0, TotalGoodsSellMoney = 0;//总商品价格  总原价  总售价
            decimal member_discount = 0;//总会员优惠
            decimal Total_integral_price = 0;//总积分金额
            int Total_use_integral = 0;//总积分
            decimal CouponsMoney = 0;//优惠总金额
            decimal InsuranceMoney = 0;//保险金额
            bool IsPointsDeduction = false;//是否有商品可使用积分抵扣
            bool address_enable = true;//地址Ok
            bool date_enable = true;//日期ok
            string date_remark = "";//日期无法下单备注
            int seat_number = 0;//座位数量
            List<object> goods_list = new List<object>();
            var guidebaseModel = guideCar_BaseRepository.GetList(new RB_GuideCar_Base_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (demodel.DetailList.Any())
            {
                string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId));
                var gList = goodsRepository.GetListForCommission(new RB_Goods_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }, 1);
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var mpriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                //区域
                var AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsIds = GoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                #region 查询司导信息
                string siteIds = string.Join(",", gList.Select(x => x.SiteId));
                var sitelist = SiteRepository.GetGuideCarSiteList(new RB_GuideCar_Site_Extend() { SiteIds = siteIds });
                string guideIds = string.Join(",", gList.Select(x => x.GuideId));
                var guidelist = GuideRepository.GetGuideCarGuideList(new RB_GuideCar_Guide_Extend() { GuideIds = guideIds });
                string carids = string.Join(",", gList.Select(x => x.CarId));
                var carlist = GuideCarRepository.GetGuideCarCarList(new RB_GuideCar_Car_Extend() { GuideCarIds = carids });
                string colorIds = string.Join(",", gList.Select(x => x.CarColorId));
                var carcolorlist = CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend() { CarColorIds = colorIds });
                #endregion
                #region 查询外部设置区域限购
                List<int> RAreaList = new List<int>();
                var RulesAreaModel = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { RulesType = Common.Enum.MallBase.RulesTypeEnum.AreaBuy, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                if (RulesAreaModel != null && RulesAreaModel.IsOpenMinPrice == 1)
                {
                    var RegionAreaList = logistics_RulesRegionRepository.GetListForSingle(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { RulesPriceId = RulesAreaModel.ID, RulesType = Common.Enum.MallBase.RulesTypeEnum.AreaBuy, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (RegionAreaList.Any())
                    {
                        //允许以下区域购买
                        RAreaList = RegionAreaList.Select(x => x.RegionId).Distinct().ToList();
                    }
                }

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

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

                #region 微店价格
                RB_SmallShops_Info_Extend smallModel = new RB_SmallShops_Info_Extend();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (demodel.SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(demodel.SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = demodel.SmallShopsId, GoodsIds = GoodsIds });
                }
                #endregion
                //初始化值
                foreach (var item in demodel.DetailList)
                {
                    seat_number = item.Number ?? 0;
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1 || gmodel.GoodsClassify != 1)
                    {
                        continue;
                    }
                    if (gmodel.CarType != GuideCarGoodsTypeEnum.Line)
                    {
                        item.Number = 1;//s设置成一个人表示一口价  保险费算人头数
                    }
                    var categoryList = clist.Where(x => x.GoodsId == item.GoodsId).ToList();

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

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

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

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

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

                    item.NorGoodsMoney = item.Final_Price ?? 0;//计算运费用

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

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

                        item.Final_Price -= integral_price;
                    }
                    #endregion

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

                    }
                    #endregion

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

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

                //赋值
                foreach (var item in demodel.DetailList)
                {
                    var gmodel = gList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (gmodel == null || gmodel.GoodsStatus != 1 || gmodel.GoodsClassify != 1)
                    {
                        continue;
                    }

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

                    var areaGoods = AreaList.Where(x => x.GoodsId == item.GoodsId).ToList();
                    bool address_disabled = false;

                    if (gmodel.IsAreaBuy == 1 && areaGoods.Any())
                    {
                        if (!areaGoods.Where(x => disList.Contains(x.AreaId ?? 0)).Any())
                        {
                            address_disabled = true;
                            address_enable = false;
                        }
                    }
                    else
                    {
                        //验证基础设置区域购买
                        if (RAreaList.Any())
                        {
                            if (!RAreaList.Where(x => disList.Contains(x)).Any())
                            {
                                address_disabled = true;
                                address_enable = false;
                            }
                        }
                    }

                    #region 司导信息
                    var targetList = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = gmodel.Id, IsReserve = 1, DateTime = demodel.TripSTime.Value.ToString("yyyy-MM-dd") });
                    if (gmodel.AdvanceDay > 0)
                    {
                        DateTime Mindate = Convert.ToDateTime(DateTime.Now.AddDays(gmodel.AdvanceDay ?? 0).ToString("yyyy-MM-dd"));
                        targetList = targetList.Where(x => x.Date >= Mindate).ToList();
                    }
                    if (!targetList.Any())
                    {
                        date_enable = false;
                        date_remark = "出发日期不在可预定日期内，请重新选择出发日期";
                    }
                    var targetModel = targetList.FirstOrDefault();
                    if (targetModel == null || targetModel.ReserveNum + seat_number > (gmodel.RideNum ?? 0))
                    {
                        date_enable = false;
                        date_remark = "剩余座位数不足，请重新选择出发日期";
                    }

                    #region 线路验证
                    if (gmodel.CarType == GuideCarGoodsTypeEnum.Line) {
                        var tdlist = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = item.GoodsId ?? 0, StartTime = demodel.TripSTime.Value.ToString("yyyy-MM-dd"), EndTime = demodel.TripETime.Value.ToString("yyyy-MM-dd") });
                        var firstModel = tdlist.OrderBy(x => x.Date).FirstOrDefault();
                        var endModel = tdlist.OrderByDescending(x => x.Date).FirstOrDefault();
                        if (endModel != null && endModel.IsReserve == 2) {
                            date_enable = false;
                            date_remark = "日期范围不在可预定的范围内，请提前日期选择";
                        }
                        if (endModel != null && endModel.IsReserve == 1 && endModel.ReserveNum > 0){
                            date_enable = false;
                            date_remark = "日期范围不在可预定的范围内，请提前日期选择";
                        }
                    }
                    #endregion

                    string SiteName = sitelist.Where(x => x.ID == gmodel.SiteId).FirstOrDefault()?.SiteName ?? "";
                    var guideModel = guidelist.Where(x => x.ID == gmodel.GuideId).FirstOrDefault();
                    string GuideName = guideModel?.Name ?? "";
                    string GuidePhoto = guideModel?.GuidePhoto ?? "";
                    decimal GuideScore = guideModel?.Score ?? 5;
                    string Introduction = guideModel?.Introduction ?? "";
                    decimal GuideWorkYears = guideModel?.WorkYears ?? 1;
                    var carModel = carlist.Where(x => x.ID == gmodel.CarId).FirstOrDefault();
                    string CarName = carModel?.Name ?? "";
                    string CarColorName = carcolorlist.Where(x => x.ID == gmodel.CarColorId).FirstOrDefault()?.ColorName ?? "";
                    decimal CarScore = carModel?.Score ?? 5;
                    string CarModel = carModel?.CarType ?? "";
                    string CarClass = carModel?.CarClass.GetEnumName() ?? "";

                    //保险
                    decimal qInsuranceMoney = (guidebaseModel?.SalePrice ?? 0);
                    decimal qInsuranceCostMoney = (guidebaseModel?.CostPrice ?? 0);
                    InsuranceMoney += qInsuranceMoney * seat_number;
                    #endregion
                    goods_list.Add(new
                    {
                        id = gmodel.Id,
                        name = gmodel.Name,
                        categoryIdList = item.CategoryIdList,
                        num = seat_number,
                        surplus_num = (gmodel.RideNum ?? 0) - (targetModel?.ReserveNum ?? 0),
                        forehead_integral = gmodel.PointsDeduction,
                        forehead_integral_type = gmodel.PointsDeductionType,
                        accumulative = gmodel.IsMultipleDeduction,//累计多件抵扣
                        address_disabled,
                        date_enable,
                        unit_price = item.Unit_Price,
                        total_original_price = (item.Original_Price ?? 0) * (item.Number ?? 0),
                        total_price = (item.Unit_Price ?? 0) * (item.Number ?? 0),//优惠券（有平摊情况） 积分抵扣 （默认从第一个商品抵扣）
                        goods_attr = new
                        {
                            id = 0,
                            goods_id = gmodel.Id,
                            sign_id = item.SpecificationSort,
                            price = item.Unit_Price ?? 0,
                            original_price = item.Original_Price ?? 0,
                            pic_url = gmodel.CoverImage,
                            individual_share = umodel?.IsDistributor ?? 2,// 是否分销商
                            share_type = gmodel.SeparateDistributionMoneyType,//分销佣金类型,
                            member_price = item.MemberPrice,
                            integral_price = demodel.Use_Integral == 1 ? item.IntegralMoney : 0,//积分抵扣金额
                            use_integral = demodel.Use_Integral == 1 ? item.IntegralNumber : 0,
                            couponMoney,
                            insurance_money = qInsuranceMoney,
                            insurance_costmoney = qInsuranceCostMoney,
                            name = gmodel.Name,
                            cover_pic = gmodel.CoverImage,
                            detail = gmodel.GoodsDetails,
                            pic_list = gmodel.CarouselImageList.Select(x => new
                            {
                                id = x.Id,
                                pic_url = x.Path
                            }),
                            number = seat_number,
                            goods_share_level = DistributionCommissionList.Where(x => x.GoodsId == gmodel.Id).Select(x => new
                            {
                                share_commission_first = x.OneCommission,
                                share_commission_second = x.TwoCommission,
                                share_commission_third = x.ThreeCommission,
                                level = x.DistributorGrade
                            }),
                            attr_setting_type = gmodel.SeparateDistributionType,
                            site_name = SiteName,
                            site_id = gmodel.SiteId,
                            guide_name = GuideName,
                            guide_id = gmodel.GuideId,
                            guide_score = GuideScore,
                            guide_photo = GuidePhoto,
                            guide_introduction = Introduction,
                            guide_workyears = GuideWorkYears,
                            car_name = CarName,
                            car_id = gmodel.CarId,
                            car_score = CarScore,
                            carcolor_name = CarColorName,
                            car_model = CarModel,
                            car_class = CarClass,
                            carcolor_id = gmodel.CarColorId,
                            car_number = gmodel.CarNumber,
                            car_buyyear = gmodel.CarBuyYear,
                            car_type = gmodel.CarType,
                            car_type_name = gmodel.CarType.GetEnumName(),
                            use_day = gmodel.UseDay,
                            line_name = gmodel.LineName,
                            is_spell = gmodel.IsSpell,
                            ride_num = gmodel.RideNum,
                            advance_day = gmodel.AdvanceDay,
                        },
                        discounts = item.Discounts,
                        member_discount = ((item.Unit_Price ?? 0) * (item.Number ?? 0)) - (item.MemberPrice * (item.Number ?? 0)),
                        cover_pic = gmodel.CoverImage,
                        is_level_alone = gmodel.SeparateSetMember,//是否单独设置会员价                        
                        is_level = gmodel.EnjoyMember,//是否销售会员价格
                        sign = "",
                        marketingLogo = gmodel.MarketingLogo
                    });
                }
            }

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

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

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

            #endregion

            mch_list.Add(new
            {
                mch = new
                {
                    id = minModel?.MallBaseId ?? 0,
                    name = minModel?.MallName ?? ""
                },
                goods_list,
                remark = "",
                total_goods_price = TotalGoodsSellMoney,
                total_goods_original_price = TotalGoodsOriginalMoney,
                member_discount,
                coupon = new
                {
                    enabled = true,
                    use = demodel.User_Coupon_Id > 0 ? true : false,
                    coupon_discount = CouponsMoney,
                    user_coupon_id = demodel.User_Coupon_Id ?? 0
                },
                integral = IntegralObj,
                insurance_money = (guidebaseModel?.SalePrice ?? 0),
                total_price = TotalGoodsMoney + InsuranceMoney,
            });

            //订阅
            List<string> template_message_list = new List<string>();
            if (minModel != null)
            {
                if (!string.IsNullOrWhiteSpace(minModel.OrderSuccessTpl))
                {
                    template_message_list.Add(minModel.OrderSuccessTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderCancelTpl))
                {
                    template_message_list.Add(minModel.OrderCancelTpl);
                }
                if (!string.IsNullOrWhiteSpace(minModel.OrderDeliverGoodsTpl))
                {
                    template_message_list.Add(minModel.OrderDeliverGoodsTpl);
                }
            }
            var Robj = new
            {
                mch_list,
                promptNoSuperiorFY = PromptNoSuperiorFY,
                total_price = TotalGoodsMoney + InsuranceMoney,
                date_enable,
                date_remark,
                insurance_description = guidebaseModel?.InsuranceDescription,
                address = new
                {
                    demodel.District,
                    demodel.City,
                    demodel.Province,
                    demodel.ShoppingAddress
                },
                address_enable,
                template_message_list
            };
            #endregion
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 获取商品可预定日期列表
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public object GetAppletSDGoodsTargetDateList(int goodsId, string month)
        {
            var model = goodsRepository.GetEntity(goodsId);
            var targetList = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = goodsId, Month = month });
            if (model.AdvanceDay > 0)
            {
                DateTime Mindate = Convert.ToDateTime(DateTime.Now.AddDays(model.AdvanceDay ?? 0).ToString("yyyy-MM-dd"));
                targetList = targetList.Where(x => x.Date >= Mindate).ToList();
            }

            return targetList.Select(x => new
            {
                x.Id,
                x.GoodsId,
                Date = x.Date.Value.ToString("yyyy-MM-dd"),
                x.IsReserve,
                x.ReserveNum,
                SurplusNum = (model.RideNum ?? 0) - x.ReserveNum
            });
        }



        public List<RB_Goods_Extend> GetAppletGuidCarPageListForCar(int pageIndex, int pageSize, out long rowCount, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetAppletPageListForCar(pageIndex, pageSize, out rowCount, demodel);
            if (list.Any())
            {

                //会员价格
                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);
                #region 微店价格
                RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (demodel.SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity(demodel.SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = demodel.SmallShopsId, GoodsIds = goodsIds2 });
                }
                #endregion
                foreach (var item in list)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();

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

                    if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                    {
                        item.MemberPriceList = MemberPriceList.Where(x => x.GoodsId == item.Id).ToList();
                        #region 微店处理会员价格
                        if (item.MemberPriceList.Any() && demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                foreach (var mqitem in item.MemberPriceList)
                                {
                                    var sspModel = smallPList.Where(x => x.SpecificationKey == mqitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                    }

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

                }
            }
            return list;
        }


        #endregion

        #region 站点配置
        /// <summary>
        /// 站点配置列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_GuideCar_Site_Extend> GetGuideCarSiteList(int pageIndex, int pageSize, out long rowCount, RB_GuideCar_Site_Extend query)
        {
            List<RB_GuideCar_Site_Extend> list = SiteRepository.GetPageListRepository(pageIndex, pageSize, out rowCount, query);
            if (list != null && list.Any())
            {
                List<RB_GuideCar_SiteRegion_Extend> listLogisticsRulesRegion = SiteRegionRepository.GetListRepository(new RB_GuideCar_SiteRegion_Extend { TenantId = query.TenantId, SiteType = 1, MallBaseId = query.MallBaseId, SiteIds = string.Join(",", list.Select(x => x.ID)) });
                foreach (var item in list)
                {
                    item.RegionList = new List<RB_GuideCar_SiteRegion_Extend>();
                    item.RegionList = listLogisticsRulesRegion.Where(x => x.SiteId == item.ID).ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 站点配置
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_GuideCar_Site_Extend GetGuideCarSiteModel(RB_GuideCar_Site_Extend query)
        {
            RB_GuideCar_Site_Extend model = SiteRepository.GetGuideCarSiteList(query).FirstOrDefault();
            if (model != null)
            {
                List<RB_GuideCar_SiteRegion_Extend> listLogisticsRulesRegion = SiteRegionRepository.GetListRepository(new RB_GuideCar_SiteRegion_Extend { TenantId = query.TenantId, SiteType = query.SiteType, MallBaseId = query.MallBaseId, SiteId = model.ID });
                model.RegionList = new List<RB_GuideCar_SiteRegion_Extend>();
                model.RegionList = listLogisticsRulesRegion;
            }

            return model;
        }



        /// <summary>
        /// 站点配置
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_GuideCar_Site_Extend> GetGuideCarSiteList(RB_GuideCar_Site_Extend query)
        {
            return SiteRepository.GetGuideCarSiteList(query);
        }

        /// <summary>
        /// 新增/修改站点配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateGuideCarSite(RB_GuideCar_Site_Extend model)
        {
            bool flag = false;
            var trans = SiteRepository.DbTransaction;
            try
            {
                int rulesId = 0;
                if (model.ID == 0)
                {
                    rulesId = SiteRepository.Insert(model, trans);
                    flag = rulesId > 0;
                }
                else
                {
                    rulesId = model.ID;
                    flag = SiteRepository.Update(model, trans);

                    List<RB_GuideCar_SiteRegion_Extend> listLogisticsRulesRegion = SiteRegionRepository.GetListRepository(new RB_GuideCar_SiteRegion_Extend { TenantId = model.TenantId, SiteType = model.SiteType, MallBaseId = model.MallBaseId, SiteId = model.ID });

                    //删除之前的区域
                    foreach (var itemRegion in listLogisticsRulesRegion.Where(x => x.SiteId == model.ID))
                    {
                        IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//删除价格下面对应的地区
                                 {
                                    { nameof(RB_GuideCar_SiteRegion.Status),1},
                                    { nameof(RB_GuideCar_SiteRegion.UpdateDate),System.DateTime.Now},
                                  };
                        IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_GuideCar_SiteRegion.ID),FiledValue=itemRegion.ID,OperatorEnum=OperatorEnum.Equal}
                                };
                        SiteRegionRepository.Update(filedsRegion, whereHelpersRegion, trans);
                    }
                }
                if (model.RegionList != null && model.RegionList.Any())
                {
                    model.RegionList.ForEach(x => x.TenantId = model.TenantId);
                    model.RegionList.ForEach(x => x.CreateDate = System.DateTime.Now);
                    model.RegionList.ForEach(x => x.ID = 0);
                    model.RegionList.ForEach(x => x.SiteId = rulesId);
                    model.RegionList.ForEach(x => x.SiteType = model.SiteType);
                    model.RegionList.ForEach(x => x.MallBaseId = model.MallBaseId);
                    SiteRegionRepository.InsertBatch(model.RegionList, trans);
                }

                SiteRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateGuideCarSite");
                SiteRepository.DBSession.Rollback("AddOrUpdateGuideCarSite");
                return false;
            }
            return flag;
        }

        /// <summary>
        /// 删除站点配置
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelGuideCarSiteInfo(int id, int uid, int mallBaseId)
        {
            var trans = SiteRepository.DbTransaction;
            bool flag;
            try
            {
                Dictionary<string, object> cols = new Dictionary<string, object>()
                {
                    { nameof(RB_GuideCar_Site.Status),1},
                    { nameof(RB_GuideCar_Site.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_Site.ID),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_Site.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_Site.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
            };
                flag = SiteRepository.Update(cols, wheres1, trans);

                IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//删除价格下面对应的地区
                                 {
                                    { nameof(RB_GuideCar_SiteRegion.Status),1},
                                    { nameof(RB_GuideCar_SiteRegion.UpdateDate),System.DateTime.Now},
                                  };
                IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_GuideCar_SiteRegion.SiteId),FiledValue=id,OperatorEnum=OperatorEnum.Equal},
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_SiteRegion.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_SiteRegion.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }  };
                flag = SiteRegionRepository.Update(filedsRegion, whereHelpersRegion, trans);
                SiteRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelGuideCarSiteInfo");
                SiteRepository.DBSession.Rollback("DelGuideCarSiteInfo");
                return false;
            }
            return flag;
        }


        /// <summary>
        /// 批量启用/禁用站点
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool EnableGuideCarSiteInfo(List<string> ids, int IsEnable, int uid, int mallBaseId)
        {
            var trans = SiteRepository.DbTransaction;
            bool flag = false;
            try
            {
                foreach (var item in ids)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        Dictionary<string, object> cols = new Dictionary<string, object>()
                        {
                            { nameof(RB_GuideCar_Site.IsEnable),IsEnable},
                            { nameof(RB_GuideCar_Site.UpdateDate),DateTime.Now},
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_Site.ID),
                                    FiledValue=Convert.ToInt32(item),
                                    OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_Site.TenantId),
                                    FiledValue=Convert.ToInt32(uid),
                                    OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_Site.MallBaseId),
                                    FiledValue=Convert.ToInt32(mallBaseId),
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        flag = SiteRepository.Update(cols, wheres1, trans);
                    }
                }
                SiteRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "EnableGuideCarSiteInfo");
                SiteRepository.DBSession.Rollback("EnableGuideCarSiteInfo");
                return false;
            }
            return flag;
        }


        /// <summary>
        /// 获取站点地区列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_GuideCar_SiteRegion_Extend> GetListRepository(RB_GuideCar_SiteRegion_Extend query)
        {
            return SiteRegionRepository.GetListRepository(query);
        }

        #endregion

        #region 导游信息
        /// <summary>
        ///导游配置列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_GuideCar_Guide_Extend> GetGuidePageListRepository(int pageIndex, int pageSize, out long rowCount, RB_GuideCar_Guide_Extend query)
        {
            List<RB_GuideCar_Guide_Extend> list = GuideRepository.GetPageListRepository(pageIndex, pageSize, out rowCount, query);

            return list;
        }

        /// <summary>
        /// 导游配置
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_GuideCar_Guide_Extend GetGuideCarGuideModel(RB_GuideCar_Guide_Extend query)
        {
            RB_GuideCar_Guide_Extend model = GuideRepository.GetGuideCarGuideList(query).FirstOrDefault();

            return model;
        }


        /// <summary>
        ///导游列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public RB_GuideCar_Guide_Extend GetGuideCarGuideOrderInfo(RB_GuideCar_Guide_Extend query)
        {
            RB_GuideCar_Guide_Extend model = GuideRepository.GetGuideCarGuideModel(query).FirstOrDefault();

            return model;
        }


        /// <summary>
        /// 导游配置
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_GuideCar_Guide_Extend> GetGuideCarGuideList(RB_GuideCar_Guide_Extend query)
        {
            return GuideRepository.GetGuideCarGuideList(query);
        }
        /// <summary>
        /// 新增/修改导游配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateGuideCarGuide(RB_GuideCar_Guide_Extend model)
        {
            bool flag = false;
            try
            {

                if (model.ID == 0)
                {
                    flag = GuideRepository.Insert(model) > 0;
                }
                else
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_GuideCar_Guide_Extend.GuidePhoto),model.GuidePhoto},
                        { nameof(RB_GuideCar_Guide_Extend.Name),model.Name},
                        { nameof(RB_GuideCar_Guide_Extend.SiteId),model.SiteId},
                        { nameof(RB_GuideCar_Guide_Extend.Telephone),model.Telephone},
                        { nameof(RB_GuideCar_Guide_Extend.Introduction),model.Introduction},
                        { nameof(RB_GuideCar_Guide_Extend.EmergencyPhone),model.EmergencyPhone},
                        { nameof(RB_GuideCar_Guide_Extend.WorkYears),model.WorkYears}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_GuideCar_Guide_Extend.ID),
                              FiledValue=model.ID,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    flag = GuideRepository.Update(keyValues, wheres);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateGuideCarGuide");
                return false;
            }
            return flag;
        }



        /// <summary>
        /// 批量启用/禁用导游
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool EnableGuideCarGuideInfo(List<string> ids, int IsEnable, int uid, int mallBaseId)
        {
            var trans = GuideRepository.DbTransaction;
            bool flag = false;
            try
            {
                foreach (var item in ids)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        Dictionary<string, object> cols = new Dictionary<string, object>()
                        {
                            { nameof(RB_GuideCar_Guide.IsEnable),IsEnable},
                            { nameof(RB_GuideCar_Guide.UpdateDate),DateTime.Now},
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_Site.ID),
                                    FiledValue=Convert.ToInt32(item),
                                    OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_Site.TenantId),
                                    FiledValue=Convert.ToInt32(uid),
                                    OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_Site.MallBaseId),
                                    FiledValue=Convert.ToInt32(mallBaseId),
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        flag = GuideRepository.Update(cols, wheres1, trans);
                    }
                }
                GuideRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "EnableGuideCarGuideInfo");
                GuideRepository.DBSession.Rollback("EnableGuideCarGuideInfo");
                return false;
            }
            return flag;
        }
        #endregion

        #region 车辆信息
        /// <summary>
        /// 车辆列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_GuideCar_Car_Extend> GetGuideCarPageList(int pageIndex, int pageSize, out long rowCount, RB_GuideCar_Car_Extend query)
        {
            List<RB_GuideCar_Car_Extend> list = GuideCarRepository.GetPageListRepository(pageIndex, pageSize, out rowCount, query);
            if (list != null && list.Any())
            {
                List<RB_GuideCar_CarColor_Extend> listCarColor = CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend { TenantId = query.TenantId, MallBaseId = query.MallBaseId, CardIds = string.Join(",", list.Select(x => x.ID)) });
                if (listCarColor != null && listCarColor.Any())
                {
                    listCarColor.Where(x => !string.IsNullOrWhiteSpace(x.CarPic)).ToList().ForEach(x => x.PicList = JsonConvert.DeserializeObject<List<string>>(x.CarPic));
                }
                foreach (var item in list)
                {
                    item.ColorList = new List<RB_GuideCar_CarColor_Extend>();
                    item.ColorList = listCarColor.Where(x => x.CarId == item.ID).ToList();

                }
            }
            return list;
        }

        /// <summary>
        /// 车辆
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_GuideCar_Car_Extend GetGuideCarModel(RB_GuideCar_Car_Extend query)
        {
            RB_GuideCar_Car_Extend model = GuideCarRepository.GetGuideCarCarList(query).FirstOrDefault();
            if (model != null)
            {
                List<RB_GuideCar_CarColor_Extend> listCarColor = CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend { TenantId = query.TenantId, MallBaseId = query.MallBaseId, CarId = model.ID });
                if (listCarColor != null && listCarColor.Any())
                {
                    listCarColor.Where(x => !string.IsNullOrWhiteSpace(x.CarPic)).ToList().ForEach(x => x.PicList = JsonConvert.DeserializeObject<List<string>>(x.CarPic));
                }
                model.ColorList = new List<RB_GuideCar_CarColor_Extend>();
                model.ColorList = listCarColor;
            }

            return model;
        }



        /// <summary>
        /// 车辆
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_GuideCar_Car_Extend> GetGuideCarList(RB_GuideCar_Car_Extend query)
        {
            var list = GuideCarRepository.GetGuideCarCarList(query);
            if (list != null && list.Any())
            {
                List<RB_GuideCar_CarColor_Extend> listCarColor = CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend { TenantId = query.TenantId, MallBaseId = query.MallBaseId, CardIds = string.Join(",", list.Select(x => x.ID)) });
                if (listCarColor != null && listCarColor.Any())
                {
                    listCarColor.Where(x => !string.IsNullOrWhiteSpace(x.CarPic)).ToList().ForEach(x => x.PicList = JsonConvert.DeserializeObject<List<string>>(x.CarPic));
                }
                foreach (var item in list)
                {
                    item.ColorList = new List<RB_GuideCar_CarColor_Extend>();
                    item.ColorList = listCarColor.Where(x => x.CarId == item.ID).ToList();

                }
            }
            return list;
        }

        /// <summary>
        /// 新增/修改车辆
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateGuideCar(RB_GuideCar_Car_Extend model)
        {
            bool flag = false;
            var trans = GuideCarRepository.DbTransaction;
            try
            {
                int rulesId = 0;
                if (model.ID == 0)
                {
                    rulesId = GuideCarRepository.Insert(model, trans);
                    flag = rulesId > 0;
                }
                else
                {
                    rulesId = model.ID;
                    flag = GuideCarRepository.Update(model, trans);

                    List<RB_GuideCar_CarColor_Extend> listLogisticsRulesRegion = CarColorRepository.GetCarColorList(new RB_GuideCar_CarColor_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CarId = model.ID });

                    //List<string> ColorListdExcept = new List<string>();

                    //if (model.ColorList != null && model.ColorList.Any())
                    //{
                    //    if (listLogisticsRulesRegion != null && listLogisticsRulesRegion.Any())
                    //    {
                    //        //颜色差集
                    //        ColorListdExcept = model.ColorList.Select(x => x.ID.ToString()).Except(listLogisticsRulesRegion.Select(x => x.ID.ToString())).ToList();
                    //    }
                    //    foreach (var item in listLogisticsRulesRegion.Where(x => ColorListdExcept.Contains(x.ID.ToString())))
                    //    {
                    //        IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//删除价格下面对应的地区
                    //             {
                    //                { nameof(RB_GuideCar_CarColor_Extend.Status),1},
                    //                { nameof(RB_GuideCar_CarColor_Extend.UpdateDate),System.DateTime.Now},
                    //              };
                    //        IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                    //            {
                    //                new WhereHelper (){ FiledName=nameof(RB_GuideCar_CarColor_Extend.ID),FiledValue=item.ID,OperatorEnum=OperatorEnum.Equal}
                    //            };
                    //        CarColorRepository.Update(filedsRegion, whereHelpersRegion, trans);
                    //    }
                    //}
                    //else
                    //{ //全部删除
                    foreach (var itemRegion in listLogisticsRulesRegion.Where(x => x.CarId == model.ID))
                    {
                        IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//删除价格下面对应的地区
                                 {
                                    { nameof(RB_GuideCar_CarColor_Extend.Status),1},
                                    { nameof(RB_GuideCar_CarColor_Extend.UpdateDate),System.DateTime.Now},
                                  };
                        IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_GuideCar_CarColor_Extend.ID),FiledValue=itemRegion.ID,OperatorEnum=OperatorEnum.Equal}
                                };
                        CarColorRepository.Update(filedsRegion, whereHelpersRegion, trans);
                    }
                    //}
                }
                if (model.ColorList != null && model.ColorList.Any())
                {
                    foreach (var item in model.ColorList)
                    {
                        if (item.ID == 0)
                        {
                            item.TenantId = model.TenantId;
                            item.CreateDate = System.DateTime.Now;
                            item.ID = 0;
                            item.CarId = rulesId;
                            item.MallBaseId = model.MallBaseId;
                            CarColorRepository.Insert(item, trans);
                        }
                        else
                        {
                            IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//更新之前的信息
                                 {
                                    { nameof(RB_GuideCar_CarColor_Extend.ColorName),item.ColorName},
                                     { nameof(RB_GuideCar_CarColor_Extend.Status),0},
                                     { nameof(RB_GuideCar_CarColor_Extend.CarPic),item.CarPic},
                                    { nameof(RB_GuideCar_CarColor_Extend.UpdateDate),System.DateTime.Now},
                                  };
                            IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_GuideCar_CarColor_Extend.ID),FiledValue=item.ID,OperatorEnum=OperatorEnum.Equal}
                                };
                            CarColorRepository.Update(filedsRegion, whereHelpersRegion, trans);
                        }
                    }
                }
                GuideCarRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateGuideCar");
                GuideCarRepository.DBSession.Rollback("AddOrUpdateGuideCar");
                return false;
            }
            return flag;
        }
        #endregion

        #region 车辆搜索模块
        /// <summary>
        /// 设置车辆搜索模块
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGuideCarSearchInfo(RB_GuideCar_CarSearch demodel)
        {
            var OModel = carSearchSearchRepository.GetGuideCarSearchList(new RB_GuideCar_CarSearch() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (OModel != null)
            {
                demodel.ID = OModel.ID;
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>() {
                    { nameof(RB_GuideCar_CarSearch.Background),demodel.Background},
                    { nameof(RB_GuideCar_CarSearch.SearchBackground),demodel.SearchBackground},
                    { nameof(RB_GuideCar_CarSearch.SearchTips),demodel.SearchTips},
                    { nameof(RB_GuideCar_CarSearch.IsShowDate),demodel.IsShowDate},
                    { nameof(RB_GuideCar_CarSearch.IsShowCity),demodel.IsShowCity},
                    { nameof(RB_GuideCar_CarSearch.IsShowAddress),demodel.IsShowAddress},
                    { nameof(RB_GuideCar_CarSearch.IsShowCarpooling),demodel.IsShowCarpooling},
                    { nameof(RB_GuideCar_CarSearch.IsShowGuideCarGoodsType),demodel.IsShowGuideCarGoodsType},
                    { nameof(RB_GuideCar_CarSearch.IsShowCarClass),demodel.IsShowCarClass},
                    { nameof(RB_GuideCar_CarSearch.IsShowTravelGuestNum),demodel.IsShowTravelGuestNum},
                    { nameof(RB_GuideCar_CarSearch.Tips),demodel.Tips},
                    { nameof(RB_GuideCar_CarSearch.TipsIco),demodel.TipsIco},
                    { nameof(RB_GuideCar_CarSearch.SearchIco),demodel.SearchIco},
                    { nameof(RB_GuideCar_CarSearch.SearchFilletPX),demodel.SearchFilletPX},
                    { nameof(RB_GuideCar_CarSearch.ButtonFilletPX),demodel.ButtonFilletPX},
                    { nameof(RB_GuideCar_CarSearch.ButtonText),demodel.ButtonText},
                    { nameof(RB_GuideCar_CarSearch.ButtonColor),demodel.ButtonColor},
                    { nameof(RB_GuideCar_CarSearch.ButtonTextColor),demodel.ButtonTextColor},
                    { nameof(RB_Distributor_Custom.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Custom.Id),
                          FiledValue=demodel.ID,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Custom.TenantId),
                          FiledValue=demodel.TenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Custom.MallBaseId),
                          FiledValue=demodel.MallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return carSearchSearchRepository.Update(keyValuePairs, whereHelpers);
            }
            else
            {
                return carSearchSearchRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 获取车辆搜索模块信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_GuideCar_CarSearch GetGuideCarSearchInfo(string uid, int mallBaseId)
        {
            var model = carSearchSearchRepository.GetGuideCarSearchList(new RB_GuideCar_CarSearch() { TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return new RB_GuideCar_CarSearch();
            }
            return model;
        }
        #endregion

        #region 车辆品牌
        /// <summary>
        /// 车辆品牌列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_GuideCar_CarBrand_Extend> GetGuideCarBrandPageList(int pageIndex, int pageSize, out long rowCount, RB_GuideCar_CarBrand_Extend query)
        {
            List<RB_GuideCar_CarBrand_Extend> list = carBrandRepository.GetPageListRepository(pageIndex, pageSize, out rowCount, query);

            return list;
        }

        /// <summary>
        /// 车辆品牌
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_GuideCar_CarBrand_Extend GetGuideCarBrandModel(RB_GuideCar_CarBrand_Extend query)
        {
            RB_GuideCar_CarBrand_Extend model = carBrandRepository.GetGuideCarCarBrandList(query).FirstOrDefault();

            return model;
        }



        /// <summary>
        /// 车辆品牌
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_GuideCar_CarBrand_Extend> GetGuideCarBrandList(RB_GuideCar_CarBrand_Extend query)
        {
            var list = carBrandRepository.GetGuideCarCarBrandList(query);

            return list;
        }

        /// <summary>
        /// 新增/修改车辆品牌
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateGuideCarBrand(RB_GuideCar_CarBrand model)
        {
            bool flag = false;
            try
            {
                if (model.ID == 0)
                {
                    flag = carBrandRepository.Insert(model) > 0;
                }
                else
                {
                    IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//
                                 {
                                    { nameof(RB_GuideCar_CarBrand.Name),model.Name},
                                      { nameof(RB_GuideCar_CarBrand.BrandLogo),model.BrandLogo},
                                    { nameof(RB_GuideCar_CarBrand.UpdateDate),System.DateTime.Now},
                                  };
                    IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_GuideCar_CarBrand.ID),FiledValue=model.ID,OperatorEnum=OperatorEnum.Equal}
                                };
                    flag = carBrandRepository.Update(filedsRegion, whereHelpersRegion);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateGuideCarBrand");
                return false;
            }
            return flag;
        }



        /// <summary>
        /// 批量启用/禁用站点
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelGuideCarBrandInfo(List<string> ids, int uid, int mallBaseId)
        {
            var trans = carBrandRepository.DbTransaction;
            bool flag = false;
            try
            {
                foreach (var item in ids)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        Dictionary<string, object> cols = new Dictionary<string, object>()
                        {
                            { nameof(RB_GuideCar_CarBrand.Status),1},
                            { nameof(RB_GuideCar_CarBrand.UpdateDate),DateTime.Now},
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_CarBrand.ID),
                                    FiledValue=Convert.ToInt32(item),
                                    OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_CarBrand.TenantId),
                                    FiledValue=Convert.ToInt32(uid),
                                    OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                    FiledName=nameof(RB_GuideCar_CarBrand.MallBaseId),
                                    FiledValue=Convert.ToInt32(mallBaseId),
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        flag = carBrandRepository.Update(cols, wheres1, trans);
                    }
                }
                carBrandRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelGuideCarBrandInfo");
                carBrandRepository.DBSession.Rollback("DelGuideCarBrandInfo");
                return false;
            }
            return flag;
        }
        #endregion

        #region 司导评论
        /// <summary>
        /// 管理新增评论
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGoodsCommentInfo(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.CarId.HasValue && dmodel.CarId.Value > 0)
                    {
                        var carScoreList = goods_CommentRepository.GetAppletGoodsCommentscore(dmodel.CarId.Value, 0, dmodel.TenantId, dmodel.MallBaseId);
                        decimal carScore = 0;
                        if (carScoreList != null && carScoreList.Any())
                        {
                            carScore = carScoreList.FirstOrDefault().TotalScore / carScoreList.FirstOrDefault().CommentNum;
                            //carScore = (carScoreList.FirstOrDefault().TotalScore + (Convert.ToDecimal(list.Where(x => x.CarId == dmodel.CarId).FirstOrDefault().CommentScore ?? 0))) / (carScoreList.FirstOrDefault().CommentNum + 1);
                        }
                        else
                        {
                            carScore = Convert.ToDecimal(list.Where(x => x.CarId == dmodel.CarId).FirstOrDefault().CommentScore);
                        }
                        if (carScore > 0)//更新车辆的评分
                        {
                            //更新订单商品为已评价
                            Dictionary<string, object> keyValuesCar = new Dictionary<string, object>() {
                                { nameof(RB_GuideCar_Car.Score),Math.Round(carScore,1, MidpointRounding.AwayFromZero)}
                            };
                            List<WhereHelper> wheresCar = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_GuideCar_Car.ID),
                                      FiledValue=dmodel.CarId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            GuideCarRepository.Update(keyValuesCar, wheresCar);
                        }
                    }
                    if (dmodel.GuideId.HasValue && dmodel.GuideId.Value > 0)
                    {
                        decimal guidScore = 0;
                        var guideScoreList = goods_CommentRepository.GetAppletGoodsCommentscore(0, dmodel.GuideId.Value, dmodel.TenantId, dmodel.MallBaseId);
                        if (guideScoreList != null && guideScoreList.Any())
                        {
                            guidScore = guideScoreList.FirstOrDefault().TotalScore / guideScoreList.FirstOrDefault().CommentNum;
                            //guidScore = (guideScoreList.FirstOrDefault().TotalScore + (Convert.ToDecimal(list.Where(x => x.GuideId == dmodel.GuideId).FirstOrDefault().CommentScore ?? 0))) / (guideScoreList.FirstOrDefault().CommentNum + 1);
                        }
                        else
                        {
                            guidScore = Convert.ToDecimal(list.Where(x => x.GuideId == dmodel.GuideId).FirstOrDefault().CommentScore);
                        }

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


        /// <summary>
        /// 管理新增评论
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGoodsCommentInfo_V2(List<RB_Goods_Comment_Extend> list)
        {
            RB_Goods_OrderDetail dmodel = new RB_Goods_OrderDetail();
            dmodel.CarId = list.Where(x => x.CarId > 0).FirstOrDefault()?.CarId;
            dmodel.GuideId = list.Where(x => x.GuideId > 0).FirstOrDefault()?.GuideId;
            dmodel.TenantId = list.FirstOrDefault()?.TenantId ?? 0;
            dmodel.MallBaseId = list.FirstOrDefault()?.MallBaseId ?? 0;
            bool flag = goods_CommentRepository.InsertBatch(list);
            if (flag)
            {
                if (list.FirstOrDefault().OrderDetailId > 0)
                {
                    //更新订单对应对应的车辆和导游评分
                    //先查找已评论的车辆信息 
                    if (dmodel.CarId.HasValue && dmodel.CarId.Value > 0)
                    {
                        var carScoreList = goods_CommentRepository.GetAppletGoodsCommentscore(dmodel.CarId.Value, 0, dmodel.TenantId, dmodel.MallBaseId);
                        decimal carScore = 0;
                        if (carScoreList != null && carScoreList.Any())
                        {
                            carScore = carScoreList.FirstOrDefault().TotalScore / carScoreList.FirstOrDefault().CommentNum;
                        }
                        else
                        {
                            carScore = Convert.ToDecimal(list.Where(x => x.CarId == dmodel.CarId).FirstOrDefault().CommentScore);
                        }
                        if (carScore > 0)//更新车辆的评分
                        {
                            //更新订单商品为已评价
                            Dictionary<string, object> keyValuesCar = new Dictionary<string, object>() {
                                { nameof(RB_GuideCar_Car.Score),Math.Round(carScore,1, MidpointRounding.AwayFromZero)}
                            };
                            List<WhereHelper> wheresCar = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_GuideCar_Car.ID),
                                      FiledValue=dmodel.CarId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            GuideCarRepository.Update(keyValuesCar, wheresCar);
                        }
                    }
                    if (dmodel.GuideId.HasValue && dmodel.GuideId.Value > 0)
                    {
                        decimal guidScore = 0;
                        var guideScoreList = goods_CommentRepository.GetAppletGoodsCommentscore(0, dmodel.GuideId.Value, dmodel.TenantId, dmodel.MallBaseId);
                        if (guideScoreList != null && guideScoreList.Any())
                        {
                            guidScore = guideScoreList.FirstOrDefault().TotalScore / guideScoreList.FirstOrDefault().CommentNum;
                        }
                        else
                        {
                            guidScore = Convert.ToDecimal(list.Where(x => x.GuideId == dmodel.GuideId).FirstOrDefault().CommentScore);
                        }

                        if (guidScore > 0)//更新车辆的评分
                        {
                            //更新订单商品为已评价
                            Dictionary<string, object> keyValuesCar = new Dictionary<string, object>() {
                                { nameof(RB_GuideCar_Guide.Score),Math.Round(guidScore,1, MidpointRounding.AwayFromZero)}
                            };
                            List<WhereHelper> wheresCar = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_GuideCar_Guide.ID),
                                      FiledValue=dmodel.GuideId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            GuideRepository.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_Order_Extend> GetAppletGoodsMyOrderPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel)
        {
            var list = goods_OrderRepository.GetGuideCarOrderPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                }
                string areaIds1 = string.Join(",", list.Select(x => x.Province ?? 0).Distinct());
                string areaIds2 = string.Join(",", list.Select(x => x.City ?? 0).Distinct());
                string areaIds3 = string.Join(",", list.Select(x => x.District ?? 0).Distinct());
                string areaIds = "0";
                if (!string.IsNullOrEmpty(areaIds1))
                {
                    areaIds += "," + areaIds1;
                }
                if (!string.IsNullOrEmpty(areaIds2))
                {
                    areaIds += "," + areaIds2;
                }
                if (!string.IsNullOrEmpty(areaIds3))
                {
                    areaIds += "," + areaIds3;
                }
                var arealist = destinationRepository.GetDictvalueListForIds(areaIds);
                foreach (var item in list)
                {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

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



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

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

        /// <summary>
        /// 获取我的订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetAppletMyOrderInfo(int orderId, int userId, int tenantId, int mallBaseId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null || model.UserId != userId)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }
            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetGuideCarOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderId });
            foreach (var item in dlist)
            {
                item.CoverImagePath = item.CoverImage;
            }
            model.DetailList = dlist;
            //地址
            model.DistrictAddress = (destinationRepository.GetEntity(model.Province)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.City)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.District)?.Name ?? "");


            //是否可以申请售后
            var mallModel = mallBaseRepository.GetEntity(mallBaseId);
            model.IsCanApplyForAfterSale = 2;


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

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

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

            return ApiResult.Success("", new
            {
                template_message_list,
                model.OrderId,
                model.OrderNo,
                model.OrderStatus,
                OrderStatusName = ((GuidCarOrderStatusEnum)model.OrderStatus).GetEnumName(),//model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.PaymentWay,
                PaymentWayName = model.PaymentWay.GetEnumName(),
                model.DeliveryMethod,
                DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                CarTypeStr =  model.CarType.GetEnumName(),
                model.PreferPrice,
                model.Income,
                model.CouponMoney,
                model.FreightMoney,
                model.Consignee,
                model.Mobile,
                model.DistrictAddress,
                model.ShoppingAddress,
                DetailList = model.DetailList.Select(x => new
                {
                    DetailId = x.Id,
                    x.GoodsId,
                    x.GoodsName,
                    x.CoverImagePath,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(x.Specification),
                    x.Number,
                    x.Final_Price,
                    x.IsComment,
                    x.IsApplyForAfterSale,
                    x.FreeShippingRemarks,
                    x.UseDay,
                    x.IsSpell,
                    x.CarNumber,
                    x.LineName,
                    TripSTime = x.TripSTime.HasValue ? x.TripSTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    TripETime = x.TripETime.HasValue ? x.TripETime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    x.CarBrandName,
                    x.CarColorName,
                    x.CarName,
                    x.RideNum,
                    x.GuideCarType,
                    CarClassStr = x.CarClass.HasValue ? EnumHelper.GetEnumName(x.CarClass) : "",
                    x.GuideName,
                    x.GuidePhoto,
                    x.GuideScore,
                    x.GuideTelephone,
                    x.GuideWorkYears,
                    x.CarId,
                    x.GuideId,
                    x.OrderId,
                    x.InsuranceMoney,
                    x.IntegralNumber,
                    x.IntegralMoney
                }),
                model.IsApplyForCancel,
                model.RejectRemark,
                model.IsCanApplyForAfterSale,
                model.PresentFXGrade,
                model.BuyerMessage,
                model.DestinationAddress
            });
        }



        /// <summary>
        /// 小程序商品详情评论分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<GoodsComment_Extend> GetGoodsDetailPageList(int pageIndex, int pageSize, out long count, RB_Goods_Comment_Extend dmodel)
        {
            var list = goods_CommentRepository.GetGoodsDetailPageList(pageIndex, pageSize, out count, dmodel);
            if (list != null && list.Any())
            {
                string goodsIds = string.Join(",", list.Select(x => x.GoodsId));
                string orderDetailIds = string.Join(",", list.Select(x => x.OrderDetailId));
                var carCommentList = goods_CommentRepository.GetCarCommentByOrderDetailId(orderDetailIds, goodsIds, dmodel.TenantId, dmodel.MallBaseId);
                var guideCommentList = goods_CommentRepository.GetGuideCommentByOrderDetailId(orderDetailIds, dmodel.TenantId, dmodel.MallBaseId);

                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));
                    userList = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = uids, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    item.CommentList = new List<RB_Goods_Comment_Extend>();
                    item.CommentList.AddRange(carCommentList.Where(x => x.OrderDetailId == item.OrderDetailId));
                    item.CommentList.AddRange(guideCommentList.Where(x => x.OrderDetailId == item.OrderDetailId));
                    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 ?? "";
                    }
                    foreach (var itemComment in item.CommentList)
                    {
                        itemComment.CommentImgList = new List<string>();

                        if (!string.IsNullOrEmpty(itemComment.CommentImage))
                        {
                            itemComment.CommentImgList = JsonConvert.DeserializeObject<List<string>>(itemComment.CommentImage);
                        }

                    }

                }
            }
            return list;
        }




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


        #endregion

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

        }
        #endregion
    }
}
