using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Response;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.Middlelayer.TpmRepository.Repositories
{
    internal class FaultTypeRepository : TpmRepositoryBase<siger_project_machine_fault>, IFaultTypeRepository
    {
        private readonly ApiTpmDbContext _context;
        public FaultTypeRepository(ApiTpmDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseGetInvalidMode> GetPagedInvalidMode(int machineTypeId, int projectId, int page,
            int pagesize)
        {
            var queryList = from q in _context.siger_project_machine_fault
                            join qq in _context.siger_project_machine_fault on q.parentid equals qq.id
                            where q.projectid == projectId && q.parentid != 0 && q.typeid == machineTypeId && qq.status == (int)RowState.Valid
                            select new ResponseGetInvalidMode
                            {
                                faultcontents = q.title,
                                faultcontentid = q.id,
                                faulttypeid = q.parentid,
                                status = q.status,
                                faulttype = qq.title
                            };

            var totalCount = queryList.Count();
            var entities = queryList.OrderBy(q => q.faulttypeid)
                .Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

            return new PagedCollectionResult<ResponseGetInvalidMode>(entities, totalCount);
        }

        public CommonImportResult ImportFaultType(IEnumerable<FaultTypeList> types, int projectId, int userId)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            var enums = EnumHelper.EnumToList<FaultType>();

            foreach (var type in types)
            {
                rowIndex++;
                var machineType = _context.siger_project_machine_type.FirstOrDefault(q => q.title == type.MachineChildType && q.projectid == projectId
                                                                                     && q.status == (int)RowState.Valid);
                if (machineType == null)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.MachineTypeNotFound}");
                    continue;
                }

                var fault = enums.FirstOrDefault(f => f.Description == type.FaultType);
                if (fault == null)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.ImportFailed}");//枚举类型未找到
                    continue;
                }
                var isExist = _context.siger_project_machine_fault.Any(f => f.projectid == projectId && f.status == (int)RowState.Valid
                && f.typeid == machineType.id && f.fault_type == fault.EnumValue && f.title == type.title);
                if (isExist)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.DataExist}");
                    continue;
                }
            }
            if (errors.Any())
            {
                return new CommonImportResult(0, string.Join(";", errors));
            }
            try
            {
                var typeEntities = types.ToList();
                for (int i = 0; i < typeEntities.Count; i++)
                {
                    var type = typeEntities[i];
                    var machineType = _context.siger_project_machine_type.FirstOrDefault(q => q.title == type.MachineChildType && q.projectid == projectId
                                                                                          && q.status == (int)RowState.Valid);
                    var fault = _context.siger_project_machine_fault.FirstOrDefault(q =>
                        q.title == type.FaultType && q.projectid == projectId
                                                  && q.status == (int)RowState.Valid
                                                  && q.typeid == machineType.id);
                    var parentId = 0;
                    var fault_type = enums.FirstOrDefault(f => f.Description.Equals(type.FaultType));
                    if (fault == null)
                    {
                        var entity = new siger_project_machine_fault
                        {
                            title = type.title,
                            typeid = machineType.id,
                            projectid = projectId,
                            create_mid = userId,
                            create_ip = "0.0.0.1",
                            parentid = 0,
                            description = type.description,
                            fault_type = fault_type?.EnumValue??0
                        };
                        _context.siger_project_machine_fault.Add(entity);
                        _context.SaveChanges();

                        parentId = entity.id;
                    }
                }
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }
    }
}
