using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Response;
using Siger.Middlelayer.Repository.Paged;

namespace Siger.Middlelayer.QmsRepository.Repositories
{
    internal class SendTestParameterRepository : QMSRepositoryBase<siger_qms_sendtest_parameter>, ISendTestParameterRepository
    {
        private readonly ApiQmsDbContext _context;
        public SendTestParameterRepository(ApiQmsDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseSendTestParameter> GetSendTestParameters(IEnumerable<int> sectionids, int projectId,
            int page, int pagesize, int toexcel)
        {
            var querylist = from q in _context.siger_qms_sendtest_parameter
                join u in _context.siger_project_user on q.update_mid equals u.mid
                where q.projectid == projectId && q.status == (int) RowState.Valid
                select new ResponseSendTestParameter
                {
                    id = q.id,
                    section_id = q.section_id,
                    serial_number = q.serial_number,
                    category = q.category,
                    is_required = q.is_required,
                    name = q.name,
                    parameters = q.parameters,
                    update_mid = q.update_mid,
                    updator = u.name,
                    update_time = q.update_time.ToString(ParameterConstant.DateTimeFormat),
                };
            Expression<Func<ResponseSendTestParameter, bool>> sectionExpression = f => true;
            if (sectionids.Any())
            {
                sectionExpression = q => sectionids.Contains(q.section_id);
            }
            var expression = sectionExpression;
            var totalCount = querylist.Count(expression);

            if (toexcel == 1)
            {
                return new PagedCollectionResult<ResponseSendTestParameter>(querylist.Where(expression).ToList(), 0);
            }
            var entities = querylist.Where(expression).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            return new PagedCollectionResult<ResponseSendTestParameter>(entities, totalCount);
        }
    }
}
