using Siger.Middlelayer.DashboardRepository.Entities;
using Siger.Middlelayer.DashboardRepository.Repositories.Interface;
using Siger.Middlelayer.DashboardRepository.Response;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Share.Enum.ModuleEnum;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Siger.Middlelayer.Common.Helpers;
using System.Linq.Expressions;
using Siger.Middlelayer.Repository.Extensions;
using Microsoft.EntityFrameworkCore;

namespace Siger.Middlelayer.DashboardRepository.Repositories
{
    internal class SigerProjectAutoCalculationTotalRepository : DashboardRepositoryBase<siger_project_auto_calculation_data_ttl>, ISigerProjectAutoCalculationTotal
    {
        private readonly ApiDashboardDbContext _context;
        public SigerProjectAutoCalculationTotalRepository(ApiDashboardDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseTotalRate> GetRateDataPagedList(List<int> sectionIds, DateTime begin, DateTime end, DashboardTotalRate rateType, int projectId, int page, int pagesize)
        {
            Expression<Func<ResponseTotalRate, bool>> Funsection = f => true;
            Expression<Func<ResponseTotalRate, bool>> FunmRate = f => true;
            var query = from f in _context.siger_project_auto_calculation_data_ttl
                        join s in _context.siger_project_level_section on f.section equals s.id
                        where f.projectid == projectId && f.busidate >= begin && f.busidate <= end && sectionIds.Contains(f.section)
                        select new ResponseTotalRate
                        {
                            id=f.id,
                            section=f.section,
                            Title=s.title,
                            Date=f.busidate.ToString("yyyy-MM-dd"),
                            ActVal=f.numerator,
                            TargetVal=f.denominator,
                            RateType=f.ratetype,
                            Percent=f.rate,
                            RateDesc=EnumHelper.GetEnumDesc(f.ratetype),
                            
                        };
            if (rateType != DashboardTotalRate.Default)
                FunmRate = f => f.RateType == rateType;

            var predicate = Funsection.And(FunmRate);
            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
          
            return new PagedCollectionResult<ResponseTotalRate>(entities, totalCount);
        }
    }
}
