using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.TlmRepository.Entities;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Siger.Middlelayer.TlmRepository.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.TlmRepository.Repositories
{
    public class ProjectToollifeDetectionRepository : RepositoryBase<ProjectToollifeDetectionEntity>, IProjectToollifeDetectionRepository
    {
        private readonly ApiTlmDbContext _context;
        public ProjectToollifeDetectionRepository(ApiTlmDbContext context) : base(context)
        {
            _context = context;
        }

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

        }

        public CommonImportResult ImportProjectToollifeDetection(IEnumerable<ProjectToollifeDetectionReportEntity> types, TlmSettingCategory toolConfigType, int user, int projectId)
        {


            var now = DateTime.Now;
            var errors = new List<string>();
            var rowIndex = 0;
            var properties = typeof(ProjectToollifeDetectionReportEntity).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_toollife_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.ProjectToollifeDetectionEntities.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_toollife_tool.FirstOrDefault(f => f.project_id == projectId && f.status != 0 && f.number == item.ToolNumber);
                //存在校验
                var entity = _context.ProjectToollifeDetectionEntities.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<ProjectToollifeDetectionReportEntity, ProjectToollifeDetectionEntity>.Map(item);
                    entity.Projectid = projectId;
                    entity.CreateTime = now;
                    entity.Editor = user;
                    entity.Creator = user;
                    entity.ToolId = tool.id;
                    entity.ToolType = toolConfigType;
                    _context.ProjectToollifeDetectionEntities.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.ProjectToollifeDetectionEntities.Update(entity);
                }
            }
            if (_context.SaveChanges() <= 0)
            {
                return new CommonImportResult(0, CommonEnum.Fail.ToString());
            }
            return new CommonImportResult(1, "1");
        }
    }
}
