using Edu.Common.Enum;
using Edu.Model.Entity.Question;
using Edu.Model.ViewModel.Question;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB.Dapper;

namespace Edu.Repository.Question
{
    /// <summary>
    /// 题库仓储层
    /// </summary>
    public class RB_Question_BankRepository : BaseRepository<RB_Question_Bank>
    {
        /// <summary>
        /// 获取题库分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Question_Bank_ViewModel> GetQuestionBankPageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_Question_Bank_ViewModel query)
        {
            rowsCount = 0;
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.*,IFNULL(B.QuestionCount,0) AS QuestionCount
FROM  RB_Question_Bank AS A LEFT JOIN (SELECT BankId,COUNT(1) AS QuestionCount FROM rb_question WHERE `Status`=0 GROUP BY BankId) AS B ON A.BankId=B.BankId
WHERE 1=1 ");
            builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Question_Bank_ViewModel.Status), (int)DateStateEnum.Normal);
            if (query == null)
            {
                return new List<RB_Question_Bank_ViewModel>();
            }
            else
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Question_Bank_ViewModel.Group_Id), query.Group_Id);
                }
                if (query.BankId > 0)
                {
                    builder.AppendFormat(" AND A.{0}={1} ", nameof(RB_Question_Bank_ViewModel.BankId), query.BankId);
                }
                if (!string.IsNullOrEmpty(query.BankName))
                {
                    builder.AppendFormat(" AND (A.{0} LIKE @BankName OR A.{1} LIKE @BankName)", nameof(RB_Question_Bank_ViewModel.BankName), nameof(RB_Question_Bank_ViewModel.BankNo));
                    parameters.Add("BankName", "%" + query.BankName.Trim() + "%");
                }
                builder.AppendFormat(" ORDER BY A.{0} ASC ", nameof(RB_Question_Bank_ViewModel.BankNo));
                return GetPage<RB_Question_Bank_ViewModel>(pageIndex, pageSize, out rowsCount, builder.ToString(), parameters).ToList();
            }
        }
    }
}