using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Response;

namespace Siger.Middlelayer.TpmRepository.Repositories
{
    internal class SigerAndonStationConfigRepository : TpmRepositoryBase<siger_andon_station_config>, ISigerAndonStationConfigRepository
    {
        private readonly ApiTpmDbContext _context;
        public SigerAndonStationConfigRepository(ApiTpmDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseAndonStationConfig> GetPagedConfig(int project_id, int page, int pagesize)
        {
            var query = from q in _context.siger_andon_station_config
                        join m in _context.siger_project_machine on q.machine_id equals m.id
                        join t in _context.siger_andon_expection_type on q.default_error_id equals t.id into tt
                        from temp in tt.DefaultIfEmpty()
                        where q.status == (int)RowState.Valid && q.project_id == project_id
                        select new ResponseAndonStationConfig
                        {
                            change_cycle = q.change_cycle,
                            create_time = q.create_time,
                            creator_mid = q.creator_mid,
                            kicktank_time = q.kicktank_time,
                            machine_id = q.machine_id,
                            qualified_time = q.qualified_time,
                            selfdeal_time = q.selfdeal_time,
                            default_error_id = q.default_error_id,
                            default_error_name = temp != null ? temp.name : "",
                            machine_name = m.title,
                            id = q.id,
                            station_type = q.station_type,
                            speed_time = q.speed_time
                        };
            var totalCount = query.Count();
            var entities = query.OrderByDescending(q => q.machine_id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            foreach (var item in entities)
            {
                var attrdata = _context.siger_project_machine_attribution.FirstOrDefault(f => f.projectid == project_id && f.status != 0 && f.machine == item.machine_id);
                if (attrdata != null)
                {
                    var section = _context.siger_project_level_section.FirstOrDefault(f => f.id == attrdata.station);
                    if (section != null)
                    {
                        item.machine_name = section.title + "-" + item.machine_name;
                    }
                    section = _context.siger_project_level_section.FirstOrDefault(f => f.id == section.parentid);
                    if (section != null)
                    {
                        item.machine_name = section.title + "-" + item.machine_name;
                    }
                }
            }
            return new PagedCollectionResult<ResponseAndonStationConfig>(entities, totalCount);
        }
        /// <summary>
        /// Get Andon machine
        /// </summary>
        /// <param name="project_id"></param>
        /// <param name="channels"></param>
        /// <returns></returns>
        public List<siger_project_machine_attribution> GetBottleMachines(int project_id, List<int> channels)
        {
            var ret = new List<siger_project_machine_attribution>();
            var vaildRow = (int)RowState.Valid;
            //machines which attt=1
            var query = from cfg in _context.siger_andon_station_config
                        join attr in _context.siger_project_machine_attribution on
                        new { machine = cfg.machine_id, pid = cfg.project_id, cfg.status } equals
                        new { machine = attr.machine, pid = attr.projectid, attr.status } into temp
                        from attr in temp.DefaultIfEmpty()
                        where attr.attribution == 1 && cfg.project_id == project_id && cfg.status == vaildRow
                        select attr;
            //find channel sons
            var sons = new List<int>();
            foreach (var item in channels)
            {
                var sections = GetSonLevelSections(item, project_id).Select(s => s.id).ToList();
                if (!sections.Any())
                {
                    sons.Add(item);
                }
                sons.AddRange(sections);
            }
            return query.Where(f => sons.Contains(f.station)).ToList();
        }
    }
}
