using System;
using System.Collections.Generic;
using System.Text;
using Mall.Model.Entity.Product;
using Mall.Model.Extend.Product;
using System.Linq;

namespace Mall.Repository.Product
{
    /// <summary>
    /// 网课学习仓储层
    /// </summary>
    public class RB_Goods_WK_CourseStudyRepository : BaseRepository<RB_Goods_WK_CourseStudy>
    {

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Goods_WK_CourseStudy_Extend> GetList(RB_Goods_WK_CourseStudy_Extend dmodel)
        {
            string where = $" 1=1";
            if (dmodel.Id > 0) {
                where += $@" and gc.{nameof(RB_Goods_WK_CourseStudy.Id)}={dmodel.Id}";
            }
            if (dmodel.UserId > 0) {
                where += $@" and gc.{nameof(RB_Goods_WK_CourseStudy.UserId)}={dmodel.UserId}";
            }
            if (dmodel.GoodsId > 0) {
                where += $@" and gc.{nameof(RB_Goods_WK_CourseStudy.GoodsId)}={dmodel.GoodsId}";
            }
            if (dmodel.CourseId > 0) {
                where += $@" and gc.{nameof(RB_Goods_WK_CourseStudy.CourseId)}={dmodel.CourseId}";
            }
            if (!string.IsNullOrEmpty(dmodel.GoodsIds)) {
                where += $@" and gc.{nameof(RB_Goods_WK_CourseStudy.GoodsId)} in({dmodel.GoodsIds})";
            }
            if (!string.IsNullOrEmpty(dmodel.CourseIds)) {
                where += $@" and gc.{nameof(RB_Goods_WK_CourseStudy.CourseId)} in({dmodel.CourseIds})";
            }
            
            string sql = $@"
SELECT gc.* FROM RB_Goods_WK_CourseStudy gc 
WHERE {where} ORDER BY gc.Id desc ";
            return Get<RB_Goods_WK_CourseStudy_Extend>(sql).ToList();
        }

        /// <summary>
        /// 课程观看
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="goodsIds"></param>
        /// <returns></returns>
        public List<RB_Goods_WK_CourseStudy_Extend> GetCourseWatchList(int userId, string goodsIds)
        {
            string sql = $@"SELECT c.GoodsId,COUNT(0) AS TNum,SUM(CASE WHEN cs.Id IS NULL THEN 0 ELSE 1 END) AS WNum FROM rb_goods_wk_course c
LEFT JOIN rb_goods_wk_coursestudy cs on c.Id = cs.CourseId AND cs.UserId = {userId}
WHERE c.GoodsId in({goodsIds})
GROUP BY c.GoodsId";
            return Get<RB_Goods_WK_CourseStudy_Extend>(sql).ToList();
        }
    }
}
