
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace Siger.Middlelayer.Repository.Repositories
{
    /// <summary>
	/// siger_project_machine_nodeRepository
	/// </summary>
    internal class SigerProjectMachineNodeRepository : ApiConfigRepositoryBase<siger_project_machine_node>, ISigerProjectMachineNodeRepository
    {
        private readonly ApiConfigDbContext _context;

        public SigerProjectMachineNodeRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }
        public IPagedCollectionResult<ResponseMachineNode> GetData(RequestMachineNode condition, int pid)
        {
            Expression<Func<siger_project_machine_node, bool>> funTime = f => true;
            if (condition.starttime != 0 && condition.endtime != 0 && condition.starttime <= condition.endtime)
            {
                funTime = f => f.node_time >= condition.starttime && f.node_time <= condition.endtime;
            }
            Expression<Func<siger_project_machine_node, bool>> funMachine = f => true;
            if (condition.machine != 0)
            {
                funMachine = f => f.machine.Equals(condition.machine);
            }
            var query = _context.siger_project_machine_node.Where(f => f.projectid.Equals(pid) && f.status == (int)RowState.Valid).OrderBy(o=>o.node_time);
            var predicates = funTime.And(funMachine);
            var count = query.Count(predicates);
            var data = query.Where(predicates).Skip((condition.page - 1) * condition.pagesize).Take(condition.pagesize).AsNoTracking().ToList();
            var entity = Mapper<siger_project_machine_node, ResponseMachineNode>.MapList(data);
            foreach (var item in entity)
            {
                item.node_operator_name = _context.siger_project_user.FirstOrDefault(f => f.mid.Equals(item.node_operator) && f.projectid.Equals(pid) && f.status == (int)RowState.Valid)?.name ?? "";
                item.machine_name = _context.siger_project_machine.FirstOrDefault(f => f.id.Equals(item.machine) && f.projectid.Equals(pid) && f.status == (int)RowState.Valid)?.title ?? "";
            }
            return new PagedCollectionResult<ResponseMachineNode>(entity, count);
        }
    }
}
