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

namespace Siger.Middlelayer.KpiRespository.Repositories
{
    internal class SigerKpiAutoCalculationRespository : KpiRepositoryBase<SigerProjectKpiIAutoCalculation>, ISigerKpiAutoCalculation
    {
        private ApiKpiDbContext _kpiDbContext;
        public SigerKpiAutoCalculationRespository(ApiKpiDbContext context) : base(context)
        {
            _kpiDbContext = context;
        }

        public IPagedCollectionResult<ResponseAutoCalcution> GetPagedCollectionResult(int section, string item, int projectId, int page, int pagesize)
        {
            Expression<Func<ResponseAutoCalcution, bool>> FunSection = f => true;
            Expression<Func<ResponseAutoCalcution, bool>> FunItem = f => true;
            var query = from f in _kpiDbContext.siger_project_kpi_auto_calculation
                        join s in _kpiDbContext.siger_project_section on f.Section equals s.id
                        join i in _kpiDbContext.siger_project_kpi_item on f.Item equals i.id
                        join u in _kpiDbContext.siger_project_user on f.Mid equals u.mid
                        where f.projectId == projectId && f.status == (int)RowState.Valid
                        select new ResponseAutoCalcution
                        {
                            Id=f.id,
                            Line=f.Line,
                            Section=f.Section,
                            SectionDesc=s.title,
                            Item=i.id,
                            ItemDesc=i.Item,
                            AutoKey=f.AutoTarget,
                            User=u.name,
                            Datetime=f.Datetime.ToString(),
                            Cycle=(int)i.KpiCycle,
                            CycleDesc= EnumHelper.GetEnumDesc(i.KpiCycle),
                            Interval= EnumHelper.GetEnumDesc(i.KpiCycle)

                        };

            if (section != 0)
                FunSection = f => f.Section == section;
            if (!string.IsNullOrEmpty(item))
                FunItem = f => f.ItemDesc.Contains(item);

            var predicate = FunSection.And(FunItem);
            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).OrderByDescending(q => q.Id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            return new PagedCollectionResult<ResponseAutoCalcution>(entities, totalCount);
        }
    }
}
