using Edu.Common.Enum;
using Edu.Model.ViewModel.Course;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB.Dapper;
using System;
using VT.FW.DB;
using Edu.Model.Entity.Goods;
using Edu.Common.Plugin;
using Edu.Common.Enum.Mall;
using Edu.Common;
using Edu.Model.ViewModel.Mall;
using Edu.Model.ViewModel.Grade;
using Edu.Repository.Grade;
using Edu.Model.Entity.Mall;

namespace Edu.Repository.Course
{
    /// <summary>
    /// 课程仓储层
    /// </summary>
    public class RB_CourseRepository : BaseRepository<Model.Entity.Course.RB_Course>
    {
        /// <summary>
        /// 小程序对应的商品仓储对象
        /// </summary>
        private readonly Mall.RB_GoodsRepository mallGoodsRepository = new Mall.RB_GoodsRepository();

        /// <summary>
        /// 小程序对应的商品分类仓储对象
        /// </summary>
        private readonly Mall.RB_Goods_CategoryRepository MallGoodsCategoryRepository = new Mall.RB_Goods_CategoryRepository();

        /// <summary>
        /// 小程序对应的商品优惠仓储对象
        /// </summary>
        private readonly Mall.RB_Goods_PreferentialRepository MallGoodsPreferentialRepository = new Mall.RB_Goods_PreferentialRepository();

        /// <summary>
        /// 商品规格
        /// </summary>
        private readonly Mall.RB_Goods_SpecificationRepository goods_SpecificationRepository = new Mall.RB_Goods_SpecificationRepository();
        /// <summary>
        /// 商品规格值
        /// </summary>
        private readonly Mall.RB_Goods_SpecificationValueRepository goods_SpecificationValueRepository = new Mall.RB_Goods_SpecificationValueRepository();
       
        /// <summary>
        /// 商品规格价格
        /// </summary>
        private readonly Mall.RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new Mall.RB_Goods_SpecificationPriceRepository();

        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 获取课程列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_ViewModel> GetCourseListRepository(RB_Course_ViewModel query)
        {
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.*,IFNULL(B.CateName,'') AS CateName
FROM RB_Course AS A LEFT JOIN rb_course_category AS B ON A.CateId=B.CateId
WHERE 1=1 
");

            builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.Status), (int)DateStateEnum.Normal);
            if (query != null)
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.Group_Id), query.Group_Id);
                }
                if (!string.IsNullOrWhiteSpace(query.CourseName))
                {
                    builder.AppendFormat(" AND A.{0} LIKE @CourseName ", nameof(RB_Course_ViewModel.CourseName));
                    parameters.Add("CourseName", "%" + query.CourseName.Trim() + "%");
                }
                if (query.CateId > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.CateId), query.CateId);
                }
                if (!string.IsNullOrEmpty(query.QCourseIds))
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Course_ViewModel.CourseId), query.QCourseIds);
                }
                //取随机前几条
                if (query.IsRand && query.RandNum > 0 && query.CourseId > 0)
                {
                    builder.AppendFormat(" AND A.{0}<>{1} ORDER BY RAND() LIMIT {2} ", nameof(RB_Course_ViewModel.CourseId), query.CourseId, query.RandNum);
                }
                //销售平台
                if (!string.IsNullOrEmpty(query.Saleplat))
                {
                    var salePlatList = Common.ConvertHelper.StringToList(query.Saleplat);

                    string str = "";
                    if (salePlatList != null && salePlatList.Count > 0)
                    {
                        for (var i = 0; i < salePlatList.Count; i++)
                        {
                            if (i == 0)
                            {
                                str += string.Format(" FIND_IN_SET('{0}', A.Saleplat)>0 ", salePlatList[i]);
                            }
                            else
                            {
                                str += string.Format(" AND FIND_IN_SET('{0}', A.Saleplat)>0 ", salePlatList[i]);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(str))
                    {
                        builder.AppendFormat("  AND ({0}) ", str);
                    }
                }
                //所属科目
                if (query.CourseSubject > 0)
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Course_ViewModel.CourseSubject), query.CourseSubject);
                }
                if (query.IsScrollClass > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.IsScrollClass), query.IsScrollClass);
                }
                if (query.SaleState > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.SaleState), query.SaleState);
                }
            }
            return Get<RB_Course_ViewModel>(builder.ToString(), parameters).ToList();
        }

        /// <summary>
        /// 获取课程分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_ViewModel> GetCoursePageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_Course_ViewModel query)
        {
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat($@"
SELECT A.*,IFNULL(B.CateName,'') AS CateName,IFNULL(C.SubjectName,'') AS CourseSubjectName, t.OrderNum, t.GuestNum
FROM RB_Course AS A 
LEFT JOIN rb_course_category AS B ON A.CateId=B.CateId
LEFT JOIN rb_course_subject AS C ON A.CourseSubject=C.Id
LEFT JOIN (
	SELECT o.CourseId,COUNT(0) AS OrderNum, SUM(o.GuestNum) AS GuestNum FROM rb_order o WHERE o.Group_Id ={query.Group_Id} AND o.OrderState <>3 GROUP BY o.CourseId
) t on t.CourseId = A.CourseId
WHERE 1=1 
");
            builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.Group_Id), query.Group_Id);
            if (query != null)
            {
                if ((int)query.Status > -1)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.Status), (int)query.Status);
                }
                if (!string.IsNullOrWhiteSpace(query.CourseName))
                {
                    builder.AppendFormat(" AND A.{0} LIKE @CourseName ", nameof(RB_Course_ViewModel.CourseName));
                    parameters.Add("CourseName", "%" + query.CourseName.Trim() + "%");
                }
                if (query.CateId > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.CateId), query.CateId);
                }
                if (!string.IsNullOrWhiteSpace(query.QCateIds))
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Course_ViewModel.CateId), query.QCateIds);
                }
                //销售平台
                if (!string.IsNullOrEmpty(query.Saleplat))
                {
                    var salePlatList = Common.ConvertHelper.StringToList(query.Saleplat);
                    string str = "";
                    if (salePlatList != null && salePlatList.Count > 0)
                    {
                        for (var i = 0; i < salePlatList.Count; i++)
                        {
                            if (i == 0)
                            {
                                str += string.Format(" FIND_IN_SET('{0}', A.Saleplat)>0 ", salePlatList[i]);
                            }
                            else
                            {
                                str += string.Format(" AND FIND_IN_SET('{0}', A.Saleplat)>0 ", salePlatList[i]);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(str))
                    {
                        builder.AppendFormat("  AND ({0}) ", str);
                    }
                }
                //所属科目
                if (query.CourseSubject > 0)
                {
                    builder.AppendFormat(" AND A.{0} IN({1}) ", nameof(RB_Course_ViewModel.CourseSubject), (int)query.CourseSubject);
                }
                if (query.Q_OrderBy > 0) {
                    if (query.Q_OrderBy == 1)
                    {
                        builder.AppendFormat(" AND t.OrderNum asc ");
                    }
                    else if (query.Q_OrderBy == 2)
                    {
                        builder.AppendFormat(" AND t.OrderNum desc ");
                    }
                    else if (query.Q_OrderBy == 3)
                    {
                        builder.AppendFormat(" AND t.GuestNum asc ");
                    }
                    else if (query.Q_OrderBy == 4)
                    {
                        builder.AppendFormat(" AND t.GuestNum desc ");
                    }
                }
                if (query.SaleState > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Course_ViewModel.SaleState), query.SaleState);
                }
            }
            builder.AppendFormat(" ORDER BY A.{0} DESC ", nameof(RB_Course_ViewModel.CourseId));
            return GetPage<RB_Course_ViewModel>(pageIndex, pageSize, out rowsCount, builder.ToString(), parameters).ToList();
        }

        /// <summary>
        /// 查询所有正常课程的章节信息
        /// </summary>
        /// <returns></returns>
        public List<RB_Course_ViewModel> GetCourseAllChapterCount(int groupId, int courseId)
        {
            StringBuilder sql = new StringBuilder("select CourseId,CourseName,(select Count(0) from rb_course_chapter b where b.CourseId=a.CourseId and ParentId=0 and b.`Status`=0) as UnitCount,(select Count(0) from rb_course_chapter b where b.CourseId=a.CourseId and ParentId>0 and b.`Status`=0) as ChapterCount from rb_course a where Status=0");
            sql.AppendFormat(" AND a.{0}={1} ", nameof(RB_Course_ViewModel.Group_Id), groupId);
            sql.AppendFormat(" AND a.{0}<>{1} ", nameof(RB_Course_ViewModel.CourseId), courseId);
            return Get<RB_Course_ViewModel>(sql.ToString()).ToList();
        }

        /// <summary>
        /// 获取课程的章节数量
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public int GetMaxChapterNum(int courseId, int group_Id)
        {
            string sql = $@"select Count(0) from rb_course_chapter b where b.Group_Id ={group_Id} and b.ParentId=0 and b.`Status`=0 and b.CourseId ={courseId}";
            var obj = ExecuteScalar(sql);
            return obj != null ? Convert.ToInt32(obj) : 0;
        }

        /// <summary>
        /// 新增修改课程
        /// </summary>
        /// <param name="model"></param>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public bool SetCourseRepository(RB_Course_ViewModel model, out int courseId)
        {
            bool flag;
            if (model.IsRenew == 0)
            {
                model.RenewOgPrice = 0;
                model.RenewSlPrice = 0;
            }
            model.ClassHours = model.ChineseHours + model.ForeignHours;
            if (model.CourseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_ViewModel.CoverImg),model.CoverImg },
                    {nameof(RB_Course_ViewModel.CourseName),model.CourseName },
                    {nameof(RB_Course_ViewModel.CourseIntro),model.CourseIntro },
                    {nameof(RB_Course_ViewModel.CateId),model.CateId },
                    {nameof(RB_Course_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Course_ViewModel.UpdateTime),model.UpdateTime },
                    {nameof(RB_Course_ViewModel.Teacher_Ids),model.Teacher_Ids },
                    {nameof(RB_Course_ViewModel.CourseFeature),model.CourseFeature },
                    {nameof(RB_Course_ViewModel.IsOpenStepPrice),model.IsOpenStepPrice },
                    {nameof(RB_Course_ViewModel.IsRenew),model.IsRenew },
                    {nameof(RB_Course_ViewModel.RenewOgPrice),model.RenewOgPrice },
                    {nameof(RB_Course_ViewModel.RenewSlPrice),model.RenewSlPrice },
                    {nameof(RB_Course_ViewModel.Saleplat),model.Saleplat },
                    {nameof(RB_Course_ViewModel.IsKCourse),model.IsKCourse },
                    {nameof(RB_Course_ViewModel.ClassHours),model.ClassHours },
                    {nameof(RB_Course_ViewModel.CourseRate),model.CourseRate },
                    {nameof(RB_Course_ViewModel.CourseSubject),model.CourseSubject },
                    {nameof(RB_Course_ViewModel.B2BIcon),model.B2BIcon },
                    {nameof(RB_Course_ViewModel.B2BBackground),model.B2BBackground },
                    {nameof(RB_Course_ViewModel.CourseEmphasis),model.CourseEmphasis },
                    {nameof(RB_Course_ViewModel.ContractInfo),model.ContractInfo },
                    {nameof(RB_Course_ViewModel.IsScrollClass),model.IsScrollClass },
                    {nameof(RB_Course_ViewModel.ScrollMinNum),model.ScrollMinNum },
                    {nameof(RB_Course_ViewModel.ScrollMaxNum),model.ScrollMaxNum },
                    {nameof(RB_Course_ViewModel.CourseTimeId),model.CourseTimeId },
                    {nameof(RB_Course_ViewModel.OpenBankLevel),model.OpenBankLevel },
                    {nameof(RB_Course_ViewModel.FreeCoffeeNum),model.FreeCoffeeNum },
                    {nameof(RB_Course_ViewModel.AddHoursMoney),model.AddHoursMoney },
                    {nameof(RB_Course_ViewModel.ChineseHours),model.ChineseHours },
                    {nameof(RB_Course_ViewModel.ForeignHours),model.ForeignHours },
                    {nameof(RB_Course_ViewModel.SaleState),model.SaleState },
                };
                flag = base.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), model.CourseId));
            }
            else
            {
                var newId = base.Insert(model);
                model.CourseId = newId;
                flag = newId > 0;
            }
            courseId = model.CourseId;
            if (model.SalePlatList != null && model.SalePlatList.Any(x => x == 4))//上架小程序端,则要同步到小程序
            {
                int GoodsId = SetMallGoodsRepository(model);//新增字段保存返回电商商品ID
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_ViewModel.MallGoodsId),GoodsId },
                };
                flag = base.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), model.CourseId));
            }
            if (model.MallGoodsId > 0 && !model.SalePlatList.Any(x => x == 4))//之前上架了小程序端,现在取消了则下架商品
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(Model.Entity.Mall.RB_Goods.GoodsStatus),2 },
                };
                mallGoodsRepository.Update(fileds, new WhereHelper(nameof(Model.Entity.Mall.RB_Goods.Id), model.MallGoodsId));
            }
            return flag;
        }

        /// <summary>
        /// 新增商城商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int SetMallGoodsRepository(RB_Course_ViewModel model)
        {
            int goodsId = 0;
            RB_Goods_Extend demodel = new RB_Goods_Extend();
            if (model.MallGoodsId > 0)
            {
                demodel = mallGoodsRepository.GetGoodsList(new RB_Goods_Extend { Id = model.MallGoodsId }).FirstOrDefault();
                if (demodel == null || demodel.Id == 0)//不存在
                {
                    demodel = new RB_Goods_Extend();
                }
            }
            demodel.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrWhiteSpace(model.CoverImg))
            {
                demodel.CarouselImageList.Add(new RB_ImageCommonModel
                {
                    Id = 0,
                    Name = "",
                    Path = model.CoverImg,
                    Type = 0
                });
                demodel.CarouselImage = JsonHelper.Serialize(demodel.CarouselImageList.Select(x => x.Path));
            }
            demodel.Name = model.CourseName;
            demodel.Remark ??= model.CourseFeature;
            demodel.VideoAddress = "";
            demodel.CustomShareTitles = "";
            demodel.CustomShareImage = "";
            demodel.GoodsStatus = 1;
            demodel.InventoryNum = 100;//
            demodel.DefaultSpecificationName = "";
            demodel.SellingPrice = model.SellPrice;
            demodel.OriginalPrice = model.OriginalPrice;
            demodel.Unit = "课";//
            demodel.CostPrice = 0;//
            demodel.IsGoodsNegotiable = 0;
            demodel.SalesNum = 0;
            demodel.GoodsNumbers = "";
            demodel.IsCustomSpecification = 1;//
            demodel.GoodsWeight = 0;
            demodel.IsDefaultService = 1;
            demodel.FreightId = -1;
            demodel.FormsId = 1;
            demodel.LimitBuyGoodsNum = -1;
            demodel.LimitBuyOrderNum = -1;
            demodel.IsAreaBuy = 0;
            demodel.IntegralPresent = 0;
            demodel.IntegralPresentType = 2;
            demodel.PointsDeduction = 0;
            demodel.PointsDeductionType = 2;
            demodel.IsMultipleDeduction = 2;
            demodel.GoodsDetails = model.CourseIntro;
            demodel.SeparateDistribution = 0;//
            demodel.SeparateDistributionType = 1;
            demodel.SeparateDistributionMoneyType = 2;
            demodel.EnjoyMember = 1;
            demodel.SeparateSetMember = 0;
            demodel.IsQuickBuy = 1;
            demodel.FullNumPinkage = 0;
            demodel.FullMoneyPinkage = 0;
            demodel.SupplierId = 0;
            demodel.Sort = 1;
            demodel.Commission = 0;
            demodel.SendArea = "";
            demodel.VideoType = 1;
            demodel.GoodsPageType = 0;
            demodel.IsNoTax = 0;
            demodel.GoodsCountry = "";
            demodel.FatCode = "";
            demodel.GoodsUrl = "";
            demodel.goodsLogo = "";
            demodel.SeparateDistributionMoneyType ??= 1;
            demodel.EnjoyMember ??= 2;
            demodel.SeparateSetMember ??= 2;
            demodel.IsQuickBuy ??= 2;
            demodel.IsSellWell ??= 2;
            demodel.GoodsType ??= OrderTypeEnum.Mall;
            demodel.GoodsStatus ??= 2;
            demodel.IsProxy ??= 2;
            demodel.ProxyType ??= 1;
            demodel.ProxyRises ??= 0;
            demodel.ProxyMoney ??= 0;
            demodel.IsProcurement = 2;//新增时
            demodel.PresentFXGrade ??= 0;//赠送粉象等级
            demodel.PresentFXMonth ??= 0;
            demodel.Advertising ??= "";//广告词
            demodel.SubName ??= "";//副标题
            demodel.IsLiveGoods ??= 2;//是否直播商品  1是  2否
            demodel.SendArea ??= "";//发货地
            demodel.GoodsClassify = 0;
            demodel.IntegralComment ??= 0;//评论反积分
            demodel.IntegralCommentType ??= 1;
            demodel.GoodsPageType ??= GoodsPageTypeEnum.All;
            demodel.TenantId = Convert.ToInt32(Config.JHTenantId);
            demodel.MallBaseId = Convert.ToInt32(Config.JHMallBaseId);

            #region 商品规格信息
            demodel.SpecificationList = new List<RB_Goods_Specification_Extend>();
            demodel.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();

            RB_Goods_Specification_Extend modelSpecification = new RB_Goods_Specification_Extend
            {
                Id = 0,//暂定
                EnabledImage = 2,
                Name = "开班日期",
                Sort = 1,
                SpecificationValueList = new List<RB_Goods_SpecificationValue_Extend>()
            };
            //查询课程对应班级开课时间大于今天的班级
            var classList = classRepository.GetClassAndCourseListRepository(new RB_Class_ViewModel { CouseId = model.CourseId, StartTime = DateTime.Now.ToString("yyyy-MM-dd") }).Where(x => x.ClassStatus == Common.Enum.Course.ClassStatusEnum.NonOpenClass && x.OpenTime > DateTime.Now).ToList();
            if (classList != null && classList.Any())
            {
                int Sort = 1;
                foreach (var item in classList)
                {
                    RB_Goods_SpecificationValue_Extend modelSpecificationValue = new RB_Goods_SpecificationValue_Extend
                    {
                        Id = 0,
                        Image = "",
                        ImagePath = "",
                        Name = item.OpenTime.ToString("MM月dd日"),
                        Sort = Sort,///暂定1
                        ClassId = item.ClassId
                    };
                    modelSpecification.SpecificationValueList.Add(modelSpecificationValue);

                    RB_Goods_SpecificationPrice_Extend pModel = new RB_Goods_SpecificationPrice_Extend()
                    {
                        Commission = 0,
                        CostMoney = 0,
                        GoodsNumbers = item.ClassNo,
                        GoodsWeight = 0,
                        InventoryNum = item.ClassPersion - item.OrderStudentCount,//暂
                        SellingPrice = model.SellPrice,
                        SpecificationSort = Sort.ToString(),//暂定
                        AttrList = new object()
                    };
                    demodel.SpecificationPriceList.Add(pModel);
                    Sort += 1;
                }
            }
            demodel.SpecificationList.Add(modelSpecification);
            #endregion

            if (demodel.Id == 0)//已存在,更新
            {
                demodel.Status = 0;
                demodel.CreateDate = DateTime.Now;
                demodel.UpdateDate = DateTime.Now;
                goodsId = mallGoodsRepository.Insert(demodel);

                if (goodsId > 0)
                {
                    //插入分类
                    foreach (var item in model.CategoryList)
                    {
                        MallGoodsCategoryRepository.Insert(new RB_Goods_Category()
                        {
                            CategoryId = item.CategoryId,
                            CreateDate = demodel.CreateDate,
                            GoodsId = goodsId,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        });
                    }

                }
            }
            else
            {
                //修改
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(Model.Entity.Mall.RB_Goods.Name),demodel.Name},
                    { nameof(Model.Entity.Mall.RB_Goods.CarouselImage),demodel.CarouselImage},
                    { nameof(Model.Entity.Mall.RB_Goods.VideoAddress),demodel.VideoAddress},
                    { nameof(Model.Entity.Mall.RB_Goods.CustomShareTitles),demodel.CustomShareTitles},
                    { nameof(Model.Entity.Mall.RB_Goods.CustomShareImage),demodel.CustomShareImage},
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsStatus),demodel.GoodsStatus},
                    { nameof(Model.Entity.Mall.RB_Goods.InventoryNum),demodel.InventoryNum},
                    { nameof(Model.Entity.Mall.RB_Goods.DefaultSpecificationName),demodel.DefaultSpecificationName},
                    { nameof(Model.Entity.Mall.RB_Goods.IsCustomSpecification),demodel.IsCustomSpecification},
                    { nameof(Model.Entity.Mall.RB_Goods.Sort),demodel.Sort},
                    { nameof(Model.Entity.Mall.RB_Goods.SellingPrice),demodel.SellingPrice},
                    { nameof(Model.Entity.Mall.RB_Goods.OriginalPrice),demodel.OriginalPrice},
                    { nameof(Model.Entity.Mall.RB_Goods.Unit),demodel.Unit},
                    { nameof(Model.Entity.Mall.RB_Goods.CostPrice),demodel.CostPrice},
                    { nameof(Model.Entity.Mall.RB_Goods.IsGoodsNegotiable),demodel.IsGoodsNegotiable},
                    { nameof(Model.Entity.Mall.RB_Goods.SalesNum),demodel.SalesNum},
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsNumbers),demodel.GoodsNumbers},
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsWeight),demodel.GoodsWeight},
                    { nameof(Model.Entity.Mall.RB_Goods.IsDefaultService),demodel.IsDefaultService},
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsService),demodel.GoodsService},
                    { nameof(Model.Entity.Mall.RB_Goods.FreightId),demodel.FreightId},
                    { nameof(Model.Entity.Mall.RB_Goods.FormsId),demodel.FormsId},
                    { nameof(Model.Entity.Mall.RB_Goods.LimitBuyGoodsNum),demodel.LimitBuyGoodsNum},
                    { nameof(Model.Entity.Mall.RB_Goods.LimitBuyOrderNum),demodel.LimitBuyOrderNum},
                    { nameof(Model.Entity.Mall.RB_Goods.FullNumPinkage),demodel.FullNumPinkage},
                    { nameof(Model.Entity.Mall.RB_Goods.FullMoneyPinkage),demodel.FullMoneyPinkage},
                    { nameof(Model.Entity.Mall.RB_Goods.IsAreaBuy),demodel.IsAreaBuy},
                    { nameof(Model.Entity.Mall.RB_Goods.IntegralPresent),demodel.IntegralPresent},
                    { nameof(Model.Entity.Mall.RB_Goods.IntegralPresentType),demodel.IntegralPresentType},
                    { nameof(Model.Entity.Mall.RB_Goods.PointsDeduction),demodel.PointsDeduction},
                    { nameof(Model.Entity.Mall.RB_Goods.PointsDeductionType),demodel.PointsDeductionType},
                    { nameof(Model.Entity.Mall.RB_Goods.IsMultipleDeduction),demodel.IsMultipleDeduction},
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsDetails),demodel.GoodsDetails},
                    { nameof(Model.Entity.Mall.RB_Goods.UpdateDate),demodel.UpdateDate},
                    { nameof(Model.Entity.Mall.RB_Goods.SeparateDistribution),demodel.SeparateDistribution},
                    { nameof(Model.Entity.Mall.RB_Goods.SeparateDistributionType),demodel.SeparateDistributionType},
                    { nameof(Model.Entity.Mall.RB_Goods.SeparateDistributionMoneyType),demodel.SeparateDistributionMoneyType},
                    { nameof(Model.Entity.Mall.RB_Goods.EnjoyMember),demodel.EnjoyMember},
                    { nameof(Model.Entity.Mall.RB_Goods.SeparateSetMember),demodel.SeparateSetMember},
                    { nameof(Model.Entity.Mall.RB_Goods.IsQuickBuy),demodel.IsQuickBuy},
                    { nameof(Model.Entity.Mall.RB_Goods.SupplierId),demodel.SupplierId},
                    { nameof(Model.Entity.Mall.RB_Goods.IsProxy),demodel.IsProxy},
                    { nameof(Model.Entity.Mall.RB_Goods.ProxyType),demodel.ProxyType},
                    { nameof(Model.Entity.Mall.RB_Goods.ProxyRises),demodel.ProxyRises},
                    { nameof(Model.Entity.Mall.RB_Goods.ProxyMoney),demodel.ProxyMoney},
                    { nameof(Model.Entity.Mall.RB_Goods.Commission),demodel.Commission},
                    { nameof(Model.Entity.Mall.RB_Goods.PresentFXGrade),demodel.PresentFXGrade},
                    { nameof(Model.Entity.Mall.RB_Goods.PresentFXMonth),demodel.PresentFXMonth},
                    { nameof(Model.Entity.Mall.RB_Goods.Advertising),demodel.Advertising},
                    { nameof(Model.Entity.Mall.RB_Goods.SubName),demodel.SubName},
                    { nameof(Model.Entity.Mall.RB_Goods.MarketingLogo),demodel.MarketingLogo},
                    { nameof(Model.Entity.Mall.RB_Goods.IsLiveGoods),demodel.IsLiveGoods},
                    { nameof(Model.Entity.Mall.RB_Goods.ShelvesDate),demodel.ShelvesDate },
                    { nameof(Model.Entity.Mall.RB_Goods.DownDate),demodel.DownDate },
                    { nameof(Model.Entity.Mall.RB_Goods.SendArea),demodel.SendArea },
                    { nameof(Model.Entity.Mall.RB_Goods.VideoType),demodel.VideoType },
                    { nameof(Model.Entity.Mall.RB_Goods.IntegralComment),demodel.IntegralComment },
                    { nameof(Model.Entity.Mall.RB_Goods.IntegralCommentType),demodel.IntegralCommentType },
                    { nameof(Model.Entity.Mall.RB_Goods.Remark),demodel.Remark },
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsPageType),demodel.GoodsPageType },
                    { nameof(Model.Entity.Mall.RB_Goods.IsNoTax),demodel.IsNoTax },
                    { nameof(Model.Entity.Mall.RB_Goods.MinProfitRate),demodel.MinProfitRate },
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsCountry),demodel.GoodsCountry },
                    { nameof(Model.Entity.Mall.RB_Goods.FatCode),demodel.FatCode },
                    { nameof(Model.Entity.Mall.RB_Goods.GoodsUrl),demodel.GoodsUrl },
                    { nameof(Model.Entity.Mall.RB_Goods.goodsLogo),demodel.goodsLogo },
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                        FiledName=nameof(Model.Entity.Mall.RB_Goods.Id),
                        FiledValue=demodel.Id,
                        OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(Model.Entity.Mall.RB_Goods.TenantId),
                        FiledValue=demodel.TenantId,
                        OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(Model.Entity.Mall.RB_Goods.MallBaseId),
                        FiledValue=demodel.MallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = mallGoodsRepository.Update(keyValues, wheres);
                if (flag)
                {
                    #region 删除规格
                    var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (slist != null && slist.Any())
                    {
                        //删除后新增
                        goods_SpecificationRepository.DeleteBatch(slist);
                    }
                    if (svlist != null && svlist.Any())
                    {
                        goods_SpecificationValueRepository.DeleteBatch(svlist);
                    }
                    if (splist != null && splist.Any())
                    {
                        goods_SpecificationPriceRepository.DeleteBatch(splist);
                    }
                    #endregion

                    #region 修改分类
                    var clist = MallGoodsCategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var insertList = model.CategoryList.Where(x => !clist.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                    var deleteList = clist.Where(x => !model.CategoryList.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                    foreach (var item in insertList)
                    {
                        MallGoodsCategoryRepository.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)
                    {
                        MallGoodsCategoryRepository.Delete(item.Id);
                    }
                    #endregion
                }
                goodsId = demodel.Id;
            }
            //插入规格
            if (demodel.IsCustomSpecification == 1)
            {
                foreach (var item in demodel.SpecificationList)
                {
                    int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                    {
                        CreateDate = demodel.CreateDate,
                        EnabledImage = item.EnabledImage,
                        GoodsId = goodsId,
                        Id = 0,
                        MallBaseId = demodel.MallBaseId,
                        Name = item.Name,
                        Sort = item.Sort,
                        Status = 0,
                        TenantId = demodel.TenantId
                    });
                    if (sid > 0)
                    {
                        foreach (var qitem in item.SpecificationValueList)
                        {
                            goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                            {
                                CreateDate = demodel.CreateDate,
                                GoodsId = goodsId,
                                Id = 0,
                                Image = qitem.Image,
                                MallBaseId = demodel.MallBaseId,
                                Name = qitem.Name,
                                Sort = qitem.Sort,
                                Status = 0,
                                TenantId = demodel.TenantId,
                                SpecificationId = sid,
                                ClassId = qitem.ClassId
                            });
                        }
                    }
                }
                foreach (var item in demodel.SpecificationPriceList)
                {
                    goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                    {
                        CreateDate = demodel.CreateDate,
                        GoodsId = goodsId,
                        Id = 0,
                        GoodsNumbers = item.GoodsNumbers,
                        GoodsWeight = item.GoodsWeight,
                        InventoryNum = item.InventoryNum,
                        MallBaseId = demodel.MallBaseId,
                        SellingPrice = item.SellingPrice,
                        SpecificationSort = item.SpecificationSort,
                        Status = 0,
                        TenantId = demodel.TenantId,
                        UpdateDate = DateTime.Now,
                        Commission = item.Commission,
                        CostMoney = item.CostMoney
                    });
                }
            }

            #region  商品优惠价格
            var oldList = MallGoodsPreferentialRepository.GetGoodsPreferentialListRepostory(new RB_Goods_Preferential_Extend() { GoodsId = goodsId });
            List<RB_Goods_Preferential_Extend> goodsPreferentialLsit = new List<RB_Goods_Preferential_Extend>();
            if (model.PreferentialList != null && model.PreferentialList.Any())
            {
                foreach (var item in model.PreferentialList)
                {
                    RB_Goods_Preferential_Extend goodsPreferential = new RB_Goods_Preferential_Extend()
                    {
                        Id = 0,
                        GoodsId = goodsId,
                        PreferentialTerms = item.PreferentialTerms,
                        SaleCommissionType = item.SaleCommissionType,
                        SaleCommissionMoney = item.SaleCommissionMoney,
                        B2BCommissionType = item.B2BCommissionType,
                        B2BCommissionMoney = item.B2BCommissionMoney,
                        PriceDiscountType = item.PriceDiscountType,
                        BuyNum = item.BuyNum,
                        SendNum = item.SendNum,
                        PriceType = item.PriceType,
                        PriceMoney = item.PriceMoney,
                        TenantId = Convert.ToInt32(Config.JHTenantId),
                        MallBaseId = Convert.ToInt32(Config.JHMallBaseId),
                        Status = 0,
                        EduCommissionType = item.EduCommissionType,
                        EduCommissionMoney = item.EduCommissionMoney
                    };
                    goodsPreferentialLsit.Add(goodsPreferential);
                }
            }

            if (oldList == null || !oldList.Any())
            {
                foreach (var item in goodsPreferentialLsit)
                {
                    MallGoodsPreferentialRepository.Insert(item);
                }
            }
            //原来有优惠数据
            else
            {
                if (model.PreferentialList == null || (model.PreferentialList != null && model.PreferentialList.Count == 0))
                {
                    MallGoodsPreferentialRepository.DeleteGoodsPreferentialRepostory(goodsId);
                }
                else
                {
                    //找出差异的数据
                    var deleteList = oldList.Where(qitem => !goodsPreferentialLsit.Any(oldItem => qitem.PriceDiscountType == oldItem.PriceDiscountType)).ToList();
                    foreach (var dItem in deleteList)
                    {
                        if (dItem.Id > 0)
                        {
                            MallGoodsPreferentialRepository.Delete(dItem.Id);
                        }
                    }
                    foreach (var priceItem in goodsPreferentialLsit)
                    {
                        var nowItem = oldList.Where(x => x.PriceDiscountType == priceItem.PriceDiscountType).FirstOrDefault();
                        if (nowItem != null && nowItem.Id > 0)
                        {
                            priceItem.Id = nowItem.Id;
                        }
                        if (priceItem.Id == 0)
                        {
                            MallGoodsPreferentialRepository.Insert(priceItem);
                        }
                        else
                        {
                            MallGoodsPreferentialRepository.Update(priceItem);
                        }
                    }
                }
            }
            #endregion

            return goodsId;
        }


        /// <summary>
        /// 更新商品的售价-卖价;原价-基础收费以及优惠政策
        /// </summary>
        /// <param name="courseModel"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool UpdateMallGoodsPriceRepository(RB_Course_ViewModel courseModel, List<RB_Course_Preferential_Extend> list)
        {
            bool flag = false;
            if (courseModel.MallGoodsId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(Model.Entity.Mall.RB_Goods.SellingPrice),courseModel.SellPrice },
                    {nameof(Model.Entity.Mall.RB_Goods.OriginalPrice),courseModel.OriginalPrice },
                };
                flag = mallGoodsRepository.Update(fileds, new WhereHelper(nameof(Model.Entity.Mall.RB_Goods.Id), courseModel.MallGoodsId));
                var oldList = MallGoodsPreferentialRepository.GetGoodsPreferentialListRepostory(new RB_Goods_Preferential_Extend() { GoodsId = courseModel.MallGoodsId });

                List<RB_Goods_Preferential_Extend> goodsPreferentialLsit = new List<RB_Goods_Preferential_Extend>();
                foreach (var item in list)
                {
                    RB_Goods_Preferential_Extend goodsPreferential = new RB_Goods_Preferential_Extend()
                    {
                        Id = 0,
                        GoodsId = courseModel.MallGoodsId,
                        PreferentialTerms = item.PreferentialTerms,
                        SaleCommissionType = item.SaleCommissionType,
                        SaleCommissionMoney = item.SaleCommissionMoney,
                        B2BCommissionType = item.B2BCommissionType,
                        B2BCommissionMoney = item.B2BCommissionMoney,
                        PriceDiscountType = item.PriceDiscountType,
                        BuyNum = item.BuyNum,
                        SendNum = item.SendNum,
                        PriceType = item.PriceType,
                        PriceMoney = item.PriceMoney,
                        TenantId = Convert.ToInt32(Config.JHTenantId),
                        MallBaseId = Convert.ToInt32(Config.JHMallBaseId),
                        Status = 0,
                        EduCommissionType = item.EduCommissionType,
                        EduCommissionMoney = item.EduCommissionMoney
                    };
                    goodsPreferentialLsit.Add(goodsPreferential);
                }


                var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = courseModel.MallGoodsId, TenantId = Convert.ToInt32(Config.JHTenantId), MallBaseId = Convert.ToInt32(Config.JHMallBaseId) });

                if (splist != null && splist.Any())
                {
                    splist.ForEach(x => x.SellingPrice = courseModel.SellPrice);
                    goods_SpecificationPriceRepository.UpdateBatch(splist);
                }
                if (oldList == null || !oldList.Any())
                {
                    foreach (var item in goodsPreferentialLsit)
                    {

                        flag = MallGoodsPreferentialRepository.Insert(item) > 0;
                    }
                }
                //原来有优惠数据
                else
                {
                    if (list == null || (list != null && list.Count == 0))
                    {
                        flag = MallGoodsPreferentialRepository.DeleteGoodsPreferentialRepostory(courseModel.MallGoodsId);
                    }
                    else
                    {
                        //找出差异的数据
                        var deleteList = oldList.Where(qitem => !goodsPreferentialLsit.Any(oldItem => qitem.PriceDiscountType == oldItem.PriceDiscountType)).ToList();
                        foreach (var dItem in deleteList)
                        {
                            if (dItem.Id > 0)
                            {
                                flag = MallGoodsPreferentialRepository.Delete(dItem.Id) > 0;
                            }
                        }
                        foreach (var priceItem in goodsPreferentialLsit)
                        {
                            var nowItem = oldList.Where(x => x.PriceDiscountType == priceItem.PriceDiscountType).FirstOrDefault();
                            if (nowItem != null && nowItem.Id > 0)
                            {
                                priceItem.Id = nowItem.Id;
                            }
                            if (priceItem.Id == 0)
                            {
                                flag = MallGoodsPreferentialRepository.Insert(priceItem) > 0;
                            }
                            else
                            {
                                flag = MallGoodsPreferentialRepository.Update(priceItem);
                            }
                        }
                    }
                }
            }
            return flag;
        }

        public List<RB_Goods_Category_Extend> GetGoodsCategoryListRepository(RB_Goods_Category_Extend query)
        {
           return  MallGoodsCategoryRepository.GetList( query);
        }
    }
}