using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Response;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Utility.ImportEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Siger.Middlelayer.QmsRepository.Repositories
{
    internal class QmsCellStationRepository : QMSRepositoryBase<siger_qms_cell_station>, IQmsCellStationRepository
    {
        private ApiQmsDbContext _context;
        public QmsCellStationRepository(ApiQmsDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseCellStation> GetCellStationPagedList(int productId, IEnumerable<int> sections, int projectId, int page, int pagesize)
        {
            Expression<Func<ResponseCellStation, bool>> funProduct = f => true;
            var query = from q in _context.siger_qms_cell_station
                        join c in _context.siger_qms_cell on q.cell equals c.id
                        join cf in _context.siger_qms_cell_cfg on c.cell equals cf.id
                        join ncf in _context.siger_qms_cell_cfg on c.nextcell equals ncf.id into temp
                        from ncfg in temp.DefaultIfEmpty()
                        join l in _context.siger_project_level_section on q.section equals l.id
                        where sections.Contains(q.section) && q.projectid == projectId
                        select new ResponseCellStation
                        {
                            id = q.id,
                            Line=l.parentid,
                            Section = q.section,
                            CellId = q.cell,
                            Cell = cf.cell,
                            NextCell = ncfg!=null? ncfg.cell:"",
                            Index = q.step
                        };
            var total = query.Count();
            var entities = query.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            return new PagedCollectionResult<ResponseCellStation>(entities, total);

        }

        public CommonImportResult ImportWorkCellStation(IEnumerable<ImportWorkCellStation> datas, int projectid)
        {
            var errors = new List<string>();
            var rowIndex = 1;

            var dataArry = new List<siger_qms_cell_station>();
            foreach (var d in datas)
            {
                var cellCfg = _context.siger_qms_cell_cfg.FirstOrDefault(f => f.projectid == projectid && f.cell == d.Cell);
                if (cellCfg==null)
                {
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                //下单元允许为空
                siger_qms_cell_cfg cellCfg2;
                siger_qms_cell objCell;
                if (!string.IsNullOrEmpty(d.NextCell))
                {
                    cellCfg2 = _context.siger_qms_cell_cfg.FirstOrDefault(f => f.projectid == projectid && f.cell == d.NextCell);
                    if (cellCfg2 == null)
                    {
                        errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                        return new CommonImportResult(0, string.Join(";", errors));
                    }
                     objCell = _context.siger_qms_cell.FirstOrDefault(f => f.projectid == projectid && f.cell == cellCfg.id && f.nextcell == cellCfg2.id);
                    if (objCell == null)
                    {
                        errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                        return new CommonImportResult(0, string.Join(";", errors));
                    }
                }else
                {
                     objCell = _context.siger_qms_cell.FirstOrDefault(f => f.projectid == projectid && f.cell == cellCfg.id && f.nextcell ==0);
                    if (objCell == null)
                    {
                        errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                        return new CommonImportResult(0, string.Join(";", errors));
                    }
                }
                var objLine = _context.siger_project_level_section.FirstOrDefault(f => f.projectid == projectid && f.title == d.Line) ;
                if (objLine == null)
                {
                    errors.Add($"{rowIndex},{(int)ConfigEnum.StationNotFound}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                var objSection = _context.siger_project_level_section.FirstOrDefault(f => f.projectid == projectid && f.title == d.Section && f.parentid==objLine.id);
                if (objSection == null)
                {
                    errors.Add($"{rowIndex},{(int)ConfigEnum.StationNotFound}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                var exitsObj = _context.siger_qms_cell_station.FirstOrDefault(f => f.projectid == projectid && f.cell == objCell.id && f.section == objSection.id && f.step == d.Index);
                if (exitsObj!=null)
                {
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordExits}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                dataArry.Add(new siger_qms_cell_station
                {
                    projectid=projectid,
                    section=objSection.id,
                    cell=objCell.id,
                    step=d.Index,
                    status=(int)RowState.Valid
                });
                rowIndex += 1;
            }
            if (errors.Any())
                return new CommonImportResult(0, string.Join(";", errors));

            if (dataArry.Any())
            {
                _context.siger_qms_cell_station.AddRange(dataArry);
                _context.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            return new CommonImportResult(0, "0");
        }
    }
}
