using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
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.ImportEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

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

        public IPagedCollectionResult<ReponseInspectStandardItem> GetPagedList(int projectId, int page, int pagesize, int toexel)
        {
            var query = _context.siger_qms_inspection_standard_item.Where(q => q.projectid == projectId && q.status == (int)RowState.Valid);
            var querylist = from q in query
                            join p in _context.siger_qms_inspection_standard_category on q.categoryid equals p.id
                            select new ReponseInspectStandardItem
                            {
                                id = q.id,
                                categoryid = q.categoryid,
                                categoryname = p.name,
                                upperlimit = q.upperlimit,
                                lowerlimit = q.lowerlimit,
                                samplequantity = q.samplequantity,
                                receivestandard = q.receivestandard
                            };

            if(toexel > 0)
            {
                var entities = querylist.OrderByDescending(t => t.id).ToList();
                return new PagedCollectionResult<ReponseInspectStandardItem>(entities, entities.Count);
            }
            else
            {
                var totalCount = querylist.Count();
                var entities = querylist.OrderByDescending(t => t.id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
                return new PagedCollectionResult<ReponseInspectStandardItem>(entities, totalCount);
            }
        }

        public CommonImportResult ImportInspectStandardItem(IEnumerable<InspectStandardItemTemplate> datas, int projectid)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            var entities = new List<siger_qms_inspection_standard_item>();
            //检查输入信息
            foreach (var data in datas)
            {
                rowIndex++;
                //获取相关实体
                
                if (errors.Any())
                {
                    return new CommonImportResult(0, string.Join(";", errors));
                }

                if ((string.IsNullOrEmpty(data.LowerLimit) && string.IsNullOrEmpty(data.UpperLimit)) ||
                    string.IsNullOrEmpty(data.SampleQuantity))
                {
                    throw new BadRequestException(RequestEnum.ParameterMiss);
                }

                if (data.UpperLimit.ToInt() <= data.LowerLimit.ToInt())
                {
                    throw new BadRequestException(RequestEnum.MaxMinError);
                }                

                var category = _context.siger_qms_inspection_standard_category.FirstOrDefault(t => t.name == data.Category &&
                    t.projectid == projectid && t.status == (int)RowState.Valid);
                if(category == null)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.CategoryNotNull}");
                }
                else
                {
                    var exsit1 = _context.siger_qms_inspection_standard_item.FirstOrDefault(t => t.categoryid == category.id && ((data.UpperLimit.ToInt() >= t.lowerlimit &&
                        data.UpperLimit.ToInt() <= t.upperlimit || data.LowerLimit.ToInt() >= t.lowerlimit && data.LowerLimit.ToInt() <= t.upperlimit) &&
                        t.upperlimit.HasValue && t.lowerlimit.HasValue || t.upperlimit.HasValue && !t.lowerlimit.HasValue && (data.LowerLimit.ToInt() <= t.upperlimit ||
                        data.UpperLimit.ToInt() <= t.upperlimit) || t.lowerlimit.HasValue && !t.upperlimit.HasValue && (data.LowerLimit.ToInt() >= t.lowerlimit ||
                        data.UpperLimit.ToInt() >= t.lowerlimit)) && t.projectid == projectid && t.status == (int)RowState.Valid);
                    var exist2 = datas.Count(t => t.Category == data.Category && ((data.UpperLimit.ToInt() >= t.LowerLimit.ToInt() &&
                         data.UpperLimit.ToInt() <= t.UpperLimit.ToInt() || data.LowerLimit.ToInt() >= t.LowerLimit.ToInt() && data.LowerLimit.ToInt() <= t.UpperLimit.ToInt()) &&
                         !string.IsNullOrEmpty(t.UpperLimit) && !string.IsNullOrEmpty(t.LowerLimit) || !string.IsNullOrEmpty(t.UpperLimit) && string.IsNullOrEmpty(t.LowerLimit) && (data.LowerLimit.ToInt() <= t.UpperLimit.ToInt() ||
                         data.UpperLimit.ToInt() <= t.UpperLimit.ToInt() || !string.IsNullOrEmpty(t.LowerLimit) && string.IsNullOrEmpty(t.UpperLimit) && (data.LowerLimit.ToInt() >= t.LowerLimit.ToInt() ||
                         data.UpperLimit.ToInt() >= t.LowerLimit.ToInt()))));
                    if (exsit1 != null || exist2 > 1)
                    {
                        throw new BadRequestException(CommonEnum.RecordExits);
                    }
                }

                var entity = new siger_qms_inspection_standard_item
                {
                    categoryid = category.id,
                    upperlimit = data.UpperLimit.ToInt(),
                    lowerlimit = data.LowerLimit.ToInt(),
                    samplequantity = data.SampleQuantity.ToInt(),
                    receivestandard = data.ReceiveStandard.ToInt(),
                    projectid = projectid
                };
                entities.Add(entity);
            }
            try
            {
                _context.siger_qms_inspection_standard_item.AddRange(entities);
                if (_context.SaveChanges() > 0)
                {
                    return new CommonImportResult(1, "1");
                }
                else
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }
            }
            catch
            {
                throw;
            }
        }
    }
}
