using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal  class SigerProjectEmailMachineRepository : ApiConfigRepositoryBase<SigerProjectEmailMachine>, ISigerProjectEmailMachine
    {
        private readonly ApiConfigDbContext _context;
        public SigerProjectEmailMachineRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<AlarmMachineSettingList> GetSettingLists(int project, int section, int page, int pageCount, out int total)
        {

            var mids = GetLevelSectionMachineIds(section, project);

            var queryList = from m in _context.siger_project_machine
                            join s in _context.siger_project_machine_attribution on m.id equals s.machine
                            join set in _context.siger_project_email_machine on s.machine equals set.machineid
                            join u in _context.siger_project_user on set.mid equals u.mid
                            where m.status == (int)RowState.Valid && s.status == (int)RowState.Valid
                                  && m.projectid == project && mids.Contains(m.id)
                            select new AlarmMachineSettingList
                            {
                                Id=set.id,
                                Mid=u.mid,
                                MachinCode=m.code,
                                UserID=u.work_code,
                                Email=u.work_email,
                                MachinId=m.id,
                                MachineTitle=m.title,
                                UserName=u.name
                            };
            total = queryList.Count();
            return queryList.OrderBy(o=>o.MachinId).Skip((page - 1) * pageCount).Take(pageCount).AsNoTracking().ToList();
        }
    }
}
