using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Paged;

namespace Siger.Middlelayer.CncRepository.Repositories
{
    internal class ProductionAllocationRepository : CncRepositoryBase<siger_project_production_allocation>, IProductionAllocationRepository
    {
        private readonly ApiCncDbContext _context;
        public ProductionAllocationRepository(ApiCncDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<siger_project_production_allocation> GetPagedList(int sectionid, int projectId, int page, int pagesize)
        {
            var queryList = from q in _context.siger_project_production_allocation
                where q.projectid == projectId && q.status == (int) RowState.Valid orderby q.add_time descending
                select q;
                            
            Expression<Func<siger_project_production_allocation, bool>> sectionExpression = q => true;
            if (sectionid != 0)
            {
                var sectionIds = GetLevelSectionIds(sectionid, projectId);
                sectionExpression = q => sectionIds.Contains(q.section_id);
            }
           
            var predicate = sectionExpression;

            var totalCount = queryList.Count(predicate);
            var entities = queryList.Where(predicate).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

            return new PagedCollectionResult<siger_project_production_allocation>(entities, totalCount);
        }
    }
}
