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

namespace Siger.Middlelayer.DashboardRepository.Repositories
{
    internal class SaasMonitorRepository : DashboardRepositoryBase<siger_tr_saas_monitor>, ISaasMonitorRepository
    {
        private readonly ApiDashboardDbContext _context;

        public SaasMonitorRepository(ApiDashboardDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<siger_tr_saas_monitor> GetPagedSaaS(RequestSelect ret, int projectid)
        {
            var query = from a in _context.siger_tr_saas_monitor
                        where a.ProjectId == projectid && a.status == (int)RowState.Valid
                        select a;
            Expression<Func<siger_tr_saas_monitor, bool>> customerNameExpression = q => true;
            if (!string.IsNullOrEmpty(ret.customer_name))
            {
                customerNameExpression = q => q.customer_name.Contains(ret.customer_name);
            }
            Expression<Func<siger_tr_saas_monitor, bool>> timeExpression = q => true;
            if (!(string.IsNullOrEmpty(ret.startTime) && string.IsNullOrEmpty(ret.endTime)))
            {
                DateTime.TryParse(ret.startTime, out var start);
                DateTime.TryParse(ret.endTime, out var end);
                end = end.AddDays(1).AddSeconds(-1);
                timeExpression = q => q.signing_time >= start && q.signing_time <= end;
            }
            var predicate = customerNameExpression.And(timeExpression);
            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).Skip((ret.page - 1) * ret.pagesize).Take(ret.pagesize).AsNoTracking().ToList();

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