using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.WmsRepository.Entities;
using Siger.Middlelayer.WmsRepository.Repositories.Interface;
using Siger.Middlelayer.WmsRepository.Response;

namespace Siger.Middlelayer.WmsRepository.Repositories
{
    internal class siger_wms_stock_quantity_change_historyRepository : WMSRepositoryBase<siger_wms_stock_quantity_change_history>, Isiger_wms_stock_quantity_change_historyRepository
    {
        private readonly ApiWmsDbContext dbContext;
        public siger_wms_stock_quantity_change_historyRepository(ApiWmsDbContext context) : base(context)
        {
            dbContext = context;
        }

        public IEnumerable<ResponseChangeHistory> GetChangeHistory(int businessid,int projectid, int locationid, string sn, int page, int pageSize, out int totalCount)
        {
            IQueryable<siger_wms_stock_quantity_change_history> data;
            if (locationid == 0)
            {
                data = GetList(f => f.projectid == projectid);
            }
            else
            {
                data = GetList(f => f.projectid == projectid && f.storage_location_id == locationid);
            }
            if(businessid!=0)
            {
                data = data.Where(f => f.businessid == businessid);
            }
            if (!string.IsNullOrEmpty(sn))
            {
                data = data.Where(f => f.material_pn == sn.Trim());
            }
            totalCount = data.Count();
            data = data.Skip((page - 1) * pageSize).Take(pageSize);

            var result = new List<ResponseChangeHistory>();
            var locationids = data.Select(f => f.storage_location_id).ToList();
            var locationDic = dbContext.siger_wms_storage_location.Where(f => f.status == (int)RowState.Valid && f.projectid == projectid &&
                                                                          locationids.Contains(f.id)).ToDictionary(f => f.id, f => f.name);

            foreach (var item in data)
            {
                var tmp = Mapper<siger_wms_stock_quantity_change_history, ResponseChangeHistory>.Map(item);
                //´¢Î»Ãû³Æ
                tmp.storagename = locationDic[item.storage_location_id];
                result.Add(tmp);
            }
            return result;
        }

        public IEnumerable<siger_wms_stock_quantity_change_history> GetMaterilStockChangeHistory(string pn, int projectId)
        {
            return dbContext.siger_wms_stock_quantity_change_history.Where(t =>
                t.projectid == projectId && t.material_pn == pn);
        }
    }
}

