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

namespace Siger.Middlelayer.AccRepository.Repositories
{
    internal class SigerTrPackageDetials : AccRepositoryBase<siger_tr_package_details>, ISigerTrPackageDetials
    {
        private ApiAccDbContext accDbContext;
        public SigerTrPackageDetials(ApiAccDbContext context) : base(context)
        {
            accDbContext = context;
        }

        public IPagedCollectionResult<PackageDetailsObj> GetBoxDetailsPagedList(string sn,string productCode,List<int> stations, DateTime begin, DateTime end, int projectid, int page, int pagesize)
        {
            Expression<Func<PackageDetailsObj, bool>> funSn = f => true;
            Expression<Func<PackageDetailsObj, bool>> funPn = f => true;
            Expression<Func<PackageDetailsObj, bool>> funDate = f => true;

            var query = from d in accDbContext.siger_tr_package_details
                        join p in accDbContext.siger_tr_package on d.boxid equals p.boxid 
                        where d.projectId == projectid && stations.Contains(p.section)
                        select new PackageDetailsObj
                        {
                            ProductCode=p.productcode,
                            BoxId=p.boxid,
                            Busidate=p.busidate,
                            Section=p.section,
                            Sn=d.sn,
                            Id=d.id
                        };
            //Sn 不为空时 与时间无关
            if (!string.IsNullOrEmpty(sn))
                funSn = f => f.Sn.Contains(sn);
            else
                funDate = f => f.Busidate >= begin && f.Busidate <= end;

            if (!string.IsNullOrEmpty(productCode))
                funPn = f => f.ProductCode.Contains(productCode);

            var predicate = funSn.And(funPn).And(funDate);
            var entities = query.Where(predicate).OrderByDescending(d=>d.Id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

            var totalCount = query.Where(predicate).Count();
            return new PagedCollectionResult<PackageDetailsObj>(entities, totalCount);
        }
    }
}
