using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.IMSRepository.Entities;
using Siger.Middlelayer.IMSRepository.Repositories.Interface;
using Siger.Middlelayer.IMSRepository.Request;
using Siger.Middlelayer.Utility.ImportEntities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using Siger.Middlelayer.Repository.Response;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Common.FieldEnum;
using OfficeOpenXml.FormulaParsing.Utilities;

namespace Siger.Middlelayer.IMSRepository.Repositories
{
    public class ProjectIMSDetectionRepository : RepositoryBase<ProjectIMSDetectionEntity>, IProjectIMSDetectionRepository
    {
        private readonly ApiIMSDbContext _context;
        public ProjectIMSDetectionRepository(ApiIMSDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ProjectIMSDetectionEntity> GetPagedList(RequestProjectIMSDetection req)
        {
            Expression<Func<ProjectIMSDetectionEntity, bool>> conditionExp = q => q.Status == (int)RowState.Valid && q.Projectid == req.ProjectId && q.ToolType == req.ToolType && q.ToolId == req.Id;
            var totalCount = _context.ProjectIMSDetectionEntities.Count(conditionExp);
            List<ProjectIMSDetectionEntity> entities;
            if (req.Page != 0)
            {
                entities = _context.ProjectIMSDetectionEntities.Where(conditionExp).Skip((req.Page - 1) * req.PageSize).Take(req.PageSize).AsNoTracking().ToList();
            }
            else
            {
                entities = _context.ProjectIMSDetectionEntities.Where(conditionExp).AsNoTracking().ToList();
            }
            return new PagedCollectionResult<ProjectIMSDetectionEntity>(entities, totalCount);

        }

        public CommonImportResult ImportProjectIMSDetection(IEnumerable<ProjectIMSDetectionReportEntity> types, ImsSettingCategory toolConfigType, int user, int projectId)
        {


            var now = DateTime.Now;
            var errors = new List<string>();
            var rowIndex = 0;
            var properties = typeof(ProjectIMSDetectionReportEntity).GetProperties();
            foreach (var item in types)
            {
                rowIndex++;
                foreach (var property in properties)
                {
                    var type = property.PropertyType;
                    if (type == typeof(string) && string.IsNullOrEmpty((string)property.GetValue(item)))
                    {
                        errors.Add($"{rowIndex},{Convert.ToString((int)TlmEnum.CheckRequiredFields)}");
                        break;
                    }
                    //if (type == typeof(double) && (double)property.GetValue(item) == 0)
                    //{
                    //    errors.Add($"{rowIndex},{Convert.ToString((int)TlmEnum.CheckRequiredFields)}");
                    //    break;
                    //}
                }
                //下拉框卡控
                //数值输入
                //OK/NOK
                if (item.Type != "数值输入" && item.Type != "OK/NOK")
                {
                    throw new BadRequestException(TlmEnum.DetectionTypeError);
                }
                //重复检验
                if (types.Count(f => f.ToolNumber == item.ToolNumber && f.Seq == item.Seq) > 1)
                {
                    errors.Add($"{rowIndex},{Convert.ToString((int)TlmEnum.RecordItemExist)}");
                }
                //关联校验
                var tool = _context.siger_project_ims_tool.FirstOrDefault(f => f.project_id == projectId && f.status != 0 && f.number == item.ToolNumber);
                if (tool == null)
                {
                    errors.Add($"{rowIndex},{Convert.ToString((int)TlmEnum.ToolNotFound)}");
                }
                if (tool != null)
                {
                    if (tool.category != toolConfigType)
                    {
                        errors.Add($"{rowIndex},{Convert.ToString((int)TlmEnum.ToolNotFound)}");
                    }
                    //重复检验
                    var temp = _context.ProjectIMSDetectionEntities.FirstOrDefault(f => f.Seq == item.Seq && f.Status != 0 && f.ToolId == tool.id && f.Projectid == projectId);
                    if (temp != null)
                    {
                        errors.Add($"{rowIndex},{Convert.ToString((int)TlmEnum.RecordItemExist)}");
                    }
                }
            }
            if (errors.Any())
            {
                return new CommonImportResult(0, string.Join(";", errors));
            }

            //insert
            foreach (var item in types)
            {
                var tool = _context.siger_project_ims_tool.FirstOrDefault(f => f.project_id == projectId && f.status != 0 && f.number == item.ToolNumber);
                //存在校验
                var entity = _context.ProjectIMSDetectionEntities.FirstOrDefault(f => f.ToolId == tool.id && f.Seq == item.Seq && f.Status != 0 && f.Projectid == projectId);
                if (item.Type == "OK/NOK")//去除无效检验类型
                {
                    item.Max = 0;
                    item.Mini = 0;
                }
                if (entity == null)
                {
                    //实体映射
                    entity = Mapper<ProjectIMSDetectionReportEntity, ProjectIMSDetectionEntity>.Map(item);
                    entity.Projectid = projectId;
                    entity.CreateTime = now;
                    entity.Editor = user;
                    entity.Creator = user;
                    entity.ToolId = tool.id;
                    entity.ToolType = toolConfigType;
                    _context.ProjectIMSDetectionEntities.Add(entity);
                }
                else
                {
                    entity.Editor = user;
                    entity.Max = item.Max;
                    entity.Mini = item.Mini;
                    entity.Seq = item.Seq;
                    entity.StandardValues = item.StandardValues;
                    entity.Tools = item.Tools;
                    entity.Type = item.Type;
                    _context.ProjectIMSDetectionEntities.Update(entity);
                }
            }
            if (_context.SaveChanges() <= 0)
            {
                return new CommonImportResult(0, CommonEnum.Fail.ToString());
            }
            return new CommonImportResult(1, "1");
        }
    }
}
