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

namespace Siger.Middlelayer.QmsRepository.Repositories
{
    internal class QmsReworkPositionSettingRepository :  QMSRepositoryBase<siger_qms_rework_postion_setting>, IQmsReworkPositionSetting
    {
        private readonly ApiQmsDbContext _context;
        public QmsReworkPositionSettingRepository(ApiQmsDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseReworkPositionSetting> GetPositionSettingPagedList(int prestation, int station, int projectId, int page, int pagesize)
        {
            Expression<Func<ResponseReworkPositionSetting, bool>> funprestation = f => true;
            Expression<Func<ResponseReworkPositionSetting, bool>> funstation = f => true;

            if (prestation != 0)
                funprestation = f => f.PreStation == prestation;
            if (station != 0)
                funstation = f => f.Staion == station;



            var predicates = funprestation.And(funstation);
            var query = from p in _context.siger_qms_rework_postion_setting
                       
                        join ps in _context.siger_project_level_section on p.Prestation equals ps.id
                        join line in _context.siger_project_level_section on ps.parentid equals line.id
                        join s in _context.siger_project_level_section on p.Station equals s.id
                        where p.projectid == projectId && p.status == (int)RowState.Valid
                        select new ResponseReworkPositionSetting
                        {
                            Id=p.id,
                            Line=ps.parentid,
                            LineDesc=line.title,
                            PreStation =p.Prestation,
                            Staion=p.Station,
                            PreSationDesc=ps.title,
                            StationDesc=s.title,
                            Date=p.DateTime.ToString("yyyy-MM-dd HH:mm:ss")
                        };
            var total = query.Count(predicates);
            var entities = query.Where(predicates).Skip((page - 1) * pagesize).Take(pagesize).ToList();

            return new PagedCollectionResult<ResponseReworkPositionSetting>(entities, total);
       
        }

        public CommonImportResult ImportReworkSetting(IEnumerable<ReworkPositionReworkSetting> standards, int projectid)
        {

            var errors = new List<string>();
            var rowIndex = 1;

            var reworkEntity = new List<siger_qms_rework_postion_setting>();
            foreach (var p in standards)
            {
                rowIndex++;

                var line = _context.siger_project_level_section.FirstOrDefault(f =>f.projectid==projectid && f.title == p.Line);
                if (line == null)
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                else
                {
                    var preStation = _context.siger_project_level_section.FirstOrDefault(f => f.projectid == projectid && f.title == p.PreStation && f.parentid == line.id);
                    if (preStation == null)
                        errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                    var station = _context.siger_project_level_section.FirstOrDefault(f => f.projectid == projectid && f.title == p.Station && f.parentid == line.id);
                    if (station == null)
                        errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");

                    var obj = _context.siger_qms_rework_postion_setting.FirstOrDefault(f => f.projectid == projectid && f.Prestation == preStation.id && f.Station == station.id);
                    if (obj != null)
                        errors.Add($"{rowIndex},{(int)CommonEnum.RecordExits}");

                    if (!errors.Any())
                    {
                        reworkEntity.Add(new siger_qms_rework_postion_setting
                        {
                            projectid = projectid,
                            Prestation = preStation.id,
                            Station = station.id,
                            DateTime = DateTime.Now,
                            status = (int)RowState.Valid
                        });
                    }
                }
            }
            if (errors.Any())
                return new CommonImportResult(0, string.Join(";", errors));
            try
            {
                _context.siger_qms_rework_postion_setting.AddRange(reworkEntity);
                _context.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }

        }

        public IEnumerable<ReponseKeyValueItem> GetReworkStation(int projectId,List<int>sections)
        {
            var query = from r in _context.siger_qms_rework_postion_setting
                        join s in _context.siger_project_level_section on r.Prestation equals s.id
                        join s1 in _context.siger_project_level_section on r.Station equals s1.id
                        where r.projectid == projectId && sections.Contains(r.Prestation) && r.status == (int)RowState.Valid
                        select new ReponseKeyValueItem
                        {
                            SettingId=r.id,
                            Id = r.Prestation, //返工工位
                            NextId=r.Station,//目标工位
                            Item = $"{s.title}->{s1.title}"
                        };
            return query.Distinct();
        }
    }
}
