using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.ToolRepository.Entities;
using Siger.Middlelayer.ToolRepository.Repositories.Interface;

namespace Siger.Middlelayer.ToolRepository.Repositories
{
    internal class SigerToolblxBdRepository : ApiToolRepositoryBase<siger_project_tool_blx_bd>, ISigerToolblxBdRepository
    {
        ApiToolDbContext apiToolDbContext;
        public SigerToolblxBdRepository(ApiToolDbContext context) : base(context)
        {
            apiToolDbContext = context;
        }

        public IEnumerable<OutLineCalibration> GetToolCalibration(int sectionId, string programNo, int projectId, int page, int pagesize, out int totalCount)
        {
            var mids = GetMachineIds(sectionId, projectId);

            Expression<Func<OutLineCalibration, bool>> Funcat = f => true;
            var query = from m in apiToolDbContext.siger_project_machine
                        join sp in apiToolDbContext.siger_project_tool_spindle_true on m.id equals sp.equipid
                        join tl in apiToolDbContext.siger_project_tool_cutter_location_true on sp.id equals tl.spindleid
                        where m.projectid == projectId && m.status == (int)RowState.Valid && sp.status == (int)RowState.Valid && tl.status == (int)RowState.Valid
                        && mids.Contains(m.id) && tl.is_processing_program != (int)ProcessProgram.NoConfig
                        select new OutLineCalibration
                        {
                            machine_id = m.id,
                            machine_code = m.code,
                            machine_name = m.title,
                            spindle_name = sp.name,
                            cutter_location_name = tl.name,
                            programno = tl.is_processing_program == (int)ProcessProgram.MainProgram ? tl.programno : tl.subprogramno
                           
                        };

            if (!string.IsNullOrEmpty(programNo))
            {
                Funcat = f => f.programno.Contains(programNo);
            }

            var groupData=  query.Where(Funcat).GroupBy(x => new {  x.machine_id, x.machine_name, x.machine_code, x.spindle_name, x.cutter_location_name, x.programno }).Select(g => new OutLineCalibration
            {
                machine_id = g.Key.machine_id,
                machine_name = g.Key.machine_name,
                machine_code = g.Key.machine_code,
                spindle_name = g.Key.spindle_name,
                cutter_location_name = g.Key.cutter_location_name,
                programno = g.Key.programno

            }).AsEnumerable();
            totalCount = groupData.Count();
            return groupData.OrderBy(o => o.machine_id).ThenBy(o => o.spindle_name).Skip((page - 1) * pagesize).Take(pagesize).ToList();
        }
    }
}
