using Siger.Middlelayer.CncRepository.Entities;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.CncRepository.Response;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Utility.ImportEntities;
using System;
using Microsoft.Extensions.Logging;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.Middlelayer.CncRepository.Repositories
{
    internal class MachineWordingModeRepository : CncRepositoryBase<siger_project_machine_wordingmode>,
        IMachineWordingModeRepository
    {
        private ApiCncDbContext _context;

        public MachineWordingModeRepository(ApiCncDbContext context) : base(context)
        {
            _context = context;
        }

        public IEnumerable<siger_project_machine_wordingmode> GetWorkModeList(int projectId)
        {
            var querylist = from q in _context.siger_project_machine_wordingmode
                join p in _context.siger_project_machine_wordingmode on q.parentid equals p.id into pp
                from p in pp.DefaultIfEmpty()
                where q.status == (int) RowState.Valid && q.projectid == projectId //&& q.machinectype1Id == typeid
                select new siger_project_machine_wordingmode
                {
                    id = q.id,
                    workingmodename = q.workingmodename,
                    parentid = q.parentid,
                    parentname = p != null ? p.workingmodename : ""
                };

            return querylist.AsNoTracking().ToList();
        }

        public CommonImportResult ImportWorkModeLists(IEnumerable<WorkModeList> WorkModeListEntities, int projectid)
        {
            try
            {
                var errors = new List<string>();
                var WorkModeLists = new List<siger_project_machine_wordingmode>();
                var rowIndex = 2;
                var WorkModeParent = WorkModeListEntities.Select(t => t.parent).Distinct().ToList();
                if (WorkModeParent.Contains("") && WorkModeParent.Count > 1)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }

                foreach (var Parent in WorkModeParent)
                {
                    if (!string.IsNullOrEmpty(Parent))
                    {
                        var list = WorkModeListEntities.Where(t => t.parent == Parent);
                        foreach (var item in list)
                        {
                            if (string.IsNullOrEmpty(item.parent) || string.IsNullOrEmpty(item.WorkingMode))
                                errors.Add($"{rowIndex},{(int) RequestEnum.ParameterMiss}");

                            if (list.Count(t => t.parent == item.parent && t.WorkingMode == item.WorkingMode) > 1)
                            {
                                errors.Add($"{rowIndex},{(int) RequestEnum.RepeatBoxListCodeExsit}");
                            }

                            var workMode = _context.siger_project_machine_wordingmode.FirstOrDefault(q =>
                                q.projectid == projectid && q.status == (int) RowState.Valid &&
                                q.workingmodename == item.parent && q.parentid == 0);
                            if (workMode == null)
                            {
                                errors.Add($"{rowIndex},{(int) RequestEnum.ParentSelectMachineTypeNull}");
                            }

                            var workModeid = workMode != null ? workMode.id : 0;
                            var workModes = _context.siger_project_machine_wordingmode.FirstOrDefault(q =>
                                q.projectid == projectid && q.status == (int) RowState.Valid &&
                                q.parentid == workModeid && q.workingmodename == item.WorkingMode);
                            if (workModes != null)
                            {
                                errors.Add($"{rowIndex},{800266}");
                            }

                            var machineWordingmode = new siger_project_machine_wordingmode
                            {
                                parentid = workModeid,
                                notelist = item.note,
                                projectid = projectid,
                                workingmodename = item.WorkingMode,
                                add_time = UnixTimeHelper.GetNow(),
                            };
                            WorkModeLists.Add(machineWordingmode);

                            rowIndex++;
                        }
                    }
                    else
                    {
                        var list = WorkModeListEntities.Where(t => t.parent == Parent);
                        foreach (var item in list)
                        {
                            if (string.IsNullOrEmpty(item.WorkingMode))
                                errors.Add($"{rowIndex},{(int) RequestEnum.ParameterMiss}");

                            if (list.Count(t => t.parent == item.parent && t.WorkingMode == item.WorkingMode) > 1)
                            {
                                errors.Add($"{rowIndex},{(int) RequestEnum.RepeatBoxListCodeExsit}");
                            }

                            var workMode = _context.siger_project_machine_wordingmode.Where(q =>
                                q.projectid == projectid && q.status == (int) RowState.Valid &&
                                q.workingmodename == item.WorkingMode && q.parentid == 0).ToList();
                            if (workMode.Any())
                            {
                                errors.Add($"{rowIndex},{(int) RequestEnum.ParentSelectMachineTypeOk}");
                            }

                            var machineWordingmode = new siger_project_machine_wordingmode
                            {
                                notelist = item.note,
                                projectid = projectid,
                                workingmodename = item.WorkingMode,
                                add_time = UnixTimeHelper.GetNow(),
                            };
                            WorkModeLists.Add(machineWordingmode);
                            rowIndex++;
                        }
                    }
                }

                if (errors.Any())
                {
                    return new CommonImportResult(0, string.Join(";", errors));
                }

                _context.siger_project_machine_wordingmode.AddRange(WorkModeLists);
                if (_context.SaveChanges() > 0)
                {
                    return new CommonImportResult(1, "1");
                }

                throw new BadRequestException(CommonEnum.Fail);
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
                throw;
            }
        }
    }
}
