using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Data.Acc;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.Middlelayer.AccRepository.Repositories
{
    internal class AutomationFixtureToolsCategoryRepository : AccRepositoryBase<siger_automation_fixture_tools_category>, IAutomationFixtureToolsCategoryRepository
    {
        private ApiAccDbContext _context;
        public AutomationFixtureToolsCategoryRepository(ApiAccDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseFixtureToolsCategory> GetPagedList(List<int> id, int projectid, int page, int pagesize, string toexcel = "")
        {
            Expression<Func<ResponseFixtureToolsCategory, bool>> FunNum = f => true;
            var query = from q in _context.siger_automation_fixture_tools_category
                        join p in _context.siger_automation_fixture_tools_category on q.parent equals p.guid into pp
                        from p in pp.DefaultIfEmpty()
                        where q.projectId == projectid && q.status == (int)RowState.Valid
                        select new ResponseFixtureToolsCategory
                        {
                            id = q.id,
                            name = q.name,
                            parentid = p == null ? 0 : p.id,
                            parentname = p.name ?? "",
                            parent = q.parent,
                            guid = q.guid,
                            createtime = q.createtime.ToString(ParameterConstant.DateTimeFormat),
                            time = q.createtime
                        };
            if (id.Any())
            {
                FunNum = q => id.Contains(q.id);
            }
            if(toexcel.ToInt() == 1)
            {
                var entities = query.Where(FunNum).OrderBy(q => q.parentid).OrderBy(q => q.createtime).AsNoTracking().ToList();
                return new PagedCollectionResult<ResponseFixtureToolsCategory>(entities, entities.Count);
            }
            else
            {
                var entities = query.Where(FunNum).OrderBy(q => q.parentid).OrderBy(q => q.createtime).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
                var totalCount = query.Where(FunNum).Count();
                return new PagedCollectionResult<ResponseFixtureToolsCategory>(entities, totalCount);
            }
        }

        public CommonImportResult ImportData(IEnumerable<FixtureToolsCategoryTemplate> list, int projectid)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            foreach (var item in list)
            {
                rowIndex++;

                if (string.IsNullOrEmpty(item.Fixture))
                {
                    errors.Add($"{rowIndex}, {(int)RequestEnum.ParameterMiss}");
                }

                var data = _context.siger_automation_fixture_tools_category.FirstOrDefault(q => q.projectId == projectid && q.status == (int)RowState.Valid && q.name == item.Fixture);
                if (data != null)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.DataExist}");
                }
                var parent = "";
                if (!string.IsNullOrEmpty(item.Parent))
                {
                    var exsit = _context.siger_automation_fixture_tools_category.FirstOrDefault(q => q.projectId == projectid && q.status == (int)RowState.Valid && q.name == item.Parent);
                    if (exsit == null)
                    {
                        errors.Add($"{rowIndex},{(int)RequestEnum.ParentTypeError}");
                    }
                    else
                    {
                        parent = exsit.guid;
                    }
                }

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

                try
                {
                    var entity = new siger_automation_fixture_tools_category
                    {
                        guid = Guid.NewGuid().ToString(),
                        name = item.Fixture,
                        parent = parent,
                        createtime = DateTime.Now,
                        updatetime = DateTime.Now,
                        projectId = projectid
                    };
                    _context.siger_automation_fixture_tools_category.Add(entity);
                    _context.SaveChanges();
                }
                catch (Exception e)
                {
                    Logger.WriteLineError(e.Message);
                    throw;
                }
            }
            return new CommonImportResult(1, "1");
        }
    }
}
