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

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class MonthReportSendRecordRepository : ApiConfigRepositoryBase<siger_project_monthreport_sendrecord>, IMonthReportSendRecordRepository
    {
        private readonly ApiConfigDbContext _context;
        public MonthReportSendRecordRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseMonthReportSendRecord> GetPagedCollectionResult(string name, string starttime, string endtime, int projectId, int page,
            int pagesize)
        {
            var queryList = from q in _context.siger_project_monthreport_sendrecord
                join c in _context.siger_project_monthreport_config on q.config_id equals c.id
                where c.status == (int) RowState.Valid && c.project_id == projectId && q.file_path != ""
                select new ResponseMonthReportSendRecord
                {
                    id = q.id,
                    name = c.name,
                    cycle = (int)c.cycle,
                    remark = c.remark,
                    send_time = q.send_time.ToString(ParameterConstant.DateTimeFormat),
                    sendTime = q.send_time,
                    user_name = q.accept_usernames
                };
            Expression<Func<ResponseMonthReportSendRecord, bool>> nameExpression = q => true;
            if (!string.IsNullOrEmpty(name))
            {
                nameExpression = q => q.name.Contains(name);
            }

            Expression<Func<ResponseMonthReportSendRecord, bool>> startExpression = q => true;
            if (!string.IsNullOrEmpty(starttime))
            {
                var start = starttime.ToDateTime();
                startExpression = q => q.sendTime >= start;
            }

            Expression<Func<ResponseMonthReportSendRecord, bool>> endExpression = q => true;
            if (!string.IsNullOrEmpty(endtime))
            {
                var end = endtime.ToDateTime();
                endExpression = q => q.sendTime <= end;
            }

            var pre = nameExpression.And(startExpression).And(endExpression);
            var totalCount = queryList.Count(pre);
            var entities = queryList.Where(pre).OrderByDescending(q => q.send_time).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

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