using New_College.IRepository;
using New_College.IRepository.UnitOfWork;
using New_College.Model;
using New_College.Model.Models;
using New_College.Model.ViewModels.Query;
using New_College.Model.ViewModels.Result;
using New_College.Repository.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace New_College.Repository
{
    /// <summary>
    /// T_EnrollmentPlaneRepository
    /// </summary>
    public class T_EnrollmentPlaneRepository : BaseRepository<T_EnrollmentPlane>, IT_EnrollmentPlaneRepository
    {

        private readonly ID_UniversityRepository d_University;
        public T_EnrollmentPlaneRepository(IUnitOfWork unitOfWork, ID_UniversityRepository d_UniversityRepository) : base(unitOfWork)
        {
            this.d_University = d_UniversityRepository;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageModel<EnrollmentPlansResult>> GetEnrollmentPlans(EnrollmentPlanRequest request)
        {
            var ulist = new List<int>();
            RefAsync<int> totalNumber = 0;
            if (!string.IsNullOrWhiteSpace(request.UniversityName))
            {
                ulist = (await this.d_University.Query(e => e.Name.Contains(request.UniversityName))).Select(s => s.Id).ToList();
            }
            var planinfo = await this.Db.Queryable<T_EnrollmentPlanedesc, D_University, T_EnrollmentBatch>((plans, universitys, Batchtype) => new object[] { JoinType.Left, plans.UniversityId == universitys.Id, JoinType.Left, plans.BatchtypeId == Batchtype.Id })
                    .Where(plans => plans.PlanId == request.PlanId && plans.BatchtypeId == request.BatchtypeId)
                    .WhereIF(ulist.Any() && ulist.Count() > 0, plans => ulist.Contains(plans.UniversityId))
                    .WhereIF(!string.IsNullOrEmpty(request.MajorName), plans => plans.MajorName.Contains(request.MajorName))
                    .OrderBy((plans) => plans.OrderSort, OrderByType.Desc).Select((plans, universitys, Batchtype) => new EnrollmentPlansResult
                     {
                         Id = plans.Id,
                         BatchName = Batchtype.Batch_name,
                         MajorName = plans.MajorName,
                         PlanCount = plans.Plancount,
                         UniversityName = universitys.Name
                     }).ToPageListAsync(request.PageIndex, request.PageSize, totalNumber);
            return new PageModel<EnrollmentPlansResult>()
            {
                data = planinfo,
                page = request.PageIndex,
                PageSize = request.PageSize,
                dataCount = totalNumber,
                pageCount = (int)Math.Ceiling(totalNumber / Convert.ToDecimal(request.PageSize))
            };

        }


        



    }
}