using System;
using System.Linq;
using System.Linq.Expressions;
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 StandardPartsRepository : QMSRepositoryBase<siger_qms_standard_parts>, IStandardPartsRepository
    {
        private readonly ApiQmsDbContext _context;
        public StandardPartsRepository(ApiQmsDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseStandardParts> GetPagedList(int machineid, int page, int pagesize, int projectid, int toexcel)
        {
            var query = _context.siger_project_machine.Where(t => t.projectid == projectid && 
                t.projectid == projectid && t.status == (int)RowState.Valid);
            var querylist = from m in query
                            join q in _context.siger_qms_standard_parts on m.id equals q.machineid into part
                            from q in part.DefaultIfEmpty()
                            join u in _context.siger_user on q.update_mid equals u.id into user
                            from u in user.DefaultIfEmpty()
                            where m.attribution == (int)MachineAttributionEnum.equipment
                            select new ResponseStandardParts
                            {
                                id = q != null ? q.id : 0,
                                machineid = m.id,
                                machinename = m.title,
                                frequency = q != null ? q.calibration_frequency : 0,
                                updator = u.nickname ?? "",
                                updatetime = q != null ? q.update_time.ToString(ParameterConstant.DateTimeFormat) : "",
                                status = q != null ? q.status : 0
                            };
            Expression<Func<ResponseStandardParts, bool>> machineExpression = q => true;
            if (machineid > 0)
            {
                machineExpression = q => q.machineid == machineid;
            }

            var expression = machineExpression;
            var totalCount = querylist.Count(expression);

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