//------------------------------------------------------------------------------
//    *****注意*****
//     此代码由工具生成。
//
//     对此文件的更改可能会导致不正确的行为，并且如果
//     重新生成代码，这些更改将会丢失。
//    *****注意*****
//------------------------------------------------------------------------------
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.IMSRepository;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.IMSRepository.Response;
using Siger.Middlelayer.Common.FieldEnum;
using Siger.Middlelayer.Common.ModuleEnum;

namespace Siger.MiddlelayerIMSRepository.Repositories
{
    public class ProjectIMSToolConfigRepository : RepositoryBase<ProjectIMSToolConfigEntity>, IProjectIMSToolConfigRepository
    {
        private readonly ApiIMSDbContext _context;
        public ProjectIMSToolConfigRepository(ApiIMSDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseGetToolConfig> GetPagedList(RequestProjectIMSToolConfig req)
        {
            Expression<Func<ProjectIMSToolConfigEntity, bool>> conditionCommon = q => q.Status == (int)RowState.Valid && q.Projectid == req.ProjectId;
            Expression<Func<ProjectIMSToolConfigEntity, bool>> conditionCode = q => true;
            if (!string.IsNullOrEmpty(req.code))
            {
                conditionCode = q => q.Code.StartsWith(req.code);
            }
            var predictes = conditionCommon.And(conditionCode);
            var totalCount = _context.ProjectIMSToolConfigEntities.Where(predictes).Select(s => s.Code).Distinct().Count();
            var entities = _context.ProjectIMSToolConfigEntities.Where(predictes).OrderByDescending(o => o.CreateTime).AsNoTracking().ToList();
            var ret = new List<ResponseGetToolConfig>();
            var userList = _context.siger_project_user.Where(q => q.status == (int)RowState.Valid && q.projectid == req.ProjectId).ToList();
            var toolList = _context.siger_project_ims_tool.Where(q => q.status == (int)RowState.Valid && q.project_id == req.ProjectId).ToList();
            var boomCodes = entities.OrderByDescending(o => o.Id).Select(s => s.Code).Distinct();
            if (req.Page != 0)
            {
                boomCodes = boomCodes.Skip((req.Page - 1) * req.PageSize).Take(req.PageSize);
            }
            foreach (var boomCode in boomCodes)
            {
                var model = entities.First(f => f.Code == boomCode);
                var toolids = entities.Where(f => f.Code == boomCode).Select(s => s.ToolId).ToList();
                ret.Add(new ResponseGetToolConfig
                {
                    Code = boomCode,
                    CreateTime = model.CreateTime,
                    Creator = model.Creator,
                    Editor = model.Editor,
                    CreatorName = userList.FirstOrDefault(f => f.mid == model.Creator)?.name ?? "",
                    EditorName = userList.FirstOrDefault(f => f.mid == model.Editor)?.name ?? "",
                    toolids = toolids,
                    material = toolList.Where(f => toolids.Contains(f.id)).Select(s => new ResponseGetToolConfigMaterial
                    {
                        Category = Convert.ToInt32(s.category),
                        CategoryName = s.category_name,
                        Id = s.id,
                        Name = s.name,
                        ToolNumber = s.number,
                        MaterialId = s.material_id
                    }).ToList()
                });
            }
            return new PagedCollectionResult<ResponseGetToolConfig>(ret, totalCount);
        }

        public List<ProjectToollifeToolConfigReportEntity> ExportToolConfigData(RequestProjectIMSToolConfig req)
        {
            var ret = new List<ProjectToollifeToolConfigReportEntity>();
            Expression<Func<ProjectIMSToolConfigEntity, bool>> conditionCommon = q => q.Status == (int)RowState.Valid && q.Projectid == req.ProjectId;
            Expression<Func<ProjectIMSToolConfigEntity, bool>> conditionCode = q => true;
            if (!string.IsNullOrEmpty(req.code))
            {
                conditionCode = q => q.Code.StartsWith(req.code);
            }
            var predictes = conditionCommon.And(conditionCode);
            var entities = _context.ProjectIMSToolConfigEntities.Where(predictes).OrderByDescending(o => o.CreateTime).AsNoTracking().ToList();
            var userList = _context.siger_project_user.Where(q => q.status == (int)RowState.Valid && q.projectid == req.ProjectId).ToList();
            var toolList = _context.siger_project_ims_tool.Where(q => q.status == (int)RowState.Valid && q.project_id == req.ProjectId).ToList();
            foreach (var item in entities)
            {
                var toolData = toolList.FirstOrDefault(f => f.id == item.ToolId);
                ret.Add(new ProjectToollifeToolConfigReportEntity
                {
                    Creator = userList.FirstOrDefault(f => f.mid == item.Creator)?.name ?? "",
                    Category = toolData?.category_name ?? "",
                    ToolNumber = toolData?.number ?? "",
                    Code = item.Code,
                    CreateTime = item.CreateTime
                });
            }
            return ret;
        }

        public CommonImportResult ImportProjectIMSToolConfig(IEnumerable<ProjectToollifeToolConfigReportEntity> types, int userId, int projectId)
        {
            var now = DateTime.Now;
            var errors = new List<string>();
            var categoryList = EnumHelper.EnumToList(typeof(ImsSettingCategory));
            var toolList = _context.siger_project_ims_tool.Where(f => f.project_id == projectId && f.status != 0).ToList();
            var rowIndex = 0;

            foreach (var item in types)
            {
                rowIndex++;
                var category = categoryList.FirstOrDefault(f => f.Description == item.Category);
                if (category == null)
                {
                    errors.Add($"{rowIndex},{(int)TlmEnum.CategoryNotFound}");
                    continue;
                }
                var tool = toolList.FirstOrDefault(f => f.number == item.ToolNumber && f.category_id == category.EnumValue);
                if (tool == null)
                {
                    errors.Add($"{rowIndex},{(int)TlmEnum.NumberNotFound}");
                    continue;
                }
                if (_context.ProjectIMSToolConfigEntities.FirstOrDefault(f => f.Code == item.Code && f.Projectid == projectId && f.Status != 0) != null)
                {
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordExits}");
                }
                if (item.Category == EnumHelper.GetEnumDesc(ImsSettingCategory.Core) && types.Count(f => f.Category == EnumHelper.GetEnumDesc(ImsSettingCategory.Core)) > 1)
                {
                    errors.Add($"{rowIndex},{(int)TlmEnum.HandleNoMore}");
                }
            }
            if (errors.Any())
            {
                return new CommonImportResult(0, string.Join(";", errors));
            }

            //insert
            foreach (var item in types)
            {
                var category = categoryList.First(f => f.Description == item.Category);
                var tool = toolList.First(f => f.number == item.ToolNumber && f.category_id == category.EnumValue);
                var model = new ProjectIMSToolConfigEntity()
                {
                    Code = item.Code,
                    Editor = userId,
                    Creator = userId,
                    CreateTime = now,
                    Projectid = projectId,
                    ToolId = tool.id,
                };
                _context.ProjectIMSToolConfigEntities.Add(model);
            }
            if (_context.SaveChanges() <= 0)
            {
                return new CommonImportResult(0, CommonEnum.Fail.ToString());
            }
            return new CommonImportResult(1, "1");
        }
    }
}
