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.Text;
using System.Linq;
using Siger.Middlelayer.Repository.Extensions;
using Microsoft.EntityFrameworkCore;

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

        public IPagedCollectionResult<ResponsePackage> GetPackagePagedList(string productCode, List<int> stations,string boxid, DateTime begin, DateTime end, int projectid, int page, int pagesize)
        {
            Expression<Func<ResponsePackage, bool>> funProductCode = f => true;
            Expression<Func<ResponsePackage, bool>> funBoxid = f => true;
            Expression<Func<ResponsePackage, bool>> funDate = f => true;

            var query = from b in accDbContext.siger_tr_package
                        where b.projectId == projectid && stations.Contains(b.section) && b.busidate >= begin && b.busidate <= end
                        select new ResponsePackage
                        {

                            BoxId = b.boxid,
                            ProductCode = b.productcode,
                            PartNo = b.partno,
                            Count = b.count,
                            Weight = b.weight,
                            Suppler = b.supplier,
                            Busidate = b.busidate,
                            Batch = b.batch,
                            SendCh = b.send_ch,
                            SendEn = b.send_en,
                            ReciveCh = b.recive_ch,
                            ReciveEn = b.recive_en,
                            IsOpen = b.open == 1 ? "Yes" : "No",

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

            //Sn 不为空时 与时间无关
            if (!string.IsNullOrEmpty(boxid))
                funBoxid = q => q.BoxId.Contains(boxid);
            else
                funDate = q => q.Busidate >= begin && q.Busidate <= end;

            var predicate = funProductCode.And(funBoxid).And(funDate);

            var entities = query.Where(predicate).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            var totalCount = query.Where(predicate).Count();
            return new PagedCollectionResult<ResponsePackage>(entities, totalCount);
        }
    }
}
