//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2022-03-28 16:46:23 
//     对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
//--------------------------------------------------------------------
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common;
using MassTransit;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
namespace IRaCIS.Core.Application.Service
{
    /// 
    /// FrontAuditConfigService
    /// 	
    [ApiExplorerSettings(GroupName = "Reviewer")]
    public class FrontAuditConfigService(IRepository _frontAuditConfigRepository,
        IRepository _qCChallengeDialogRepository,
        IRepository _dataInspectionRepository,
        IRepository _qCChallengeRepository,
        IRepository _dictionaryRepository,
        IRepository _trialRepository,
        IRepository _userRoleRepository,
        IRepository _checkChallengeDialogRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IFrontAuditConfigService
    {
        /// 
        /// 获取数据库所有表
        /// 
        /// 
        [HttpPost]
        public List GetDatabaseTables()
        {
            return _frontAuditConfigRepository._dbContext.GetContextTablesList();
        }
        /// 
        /// 获取查询对象
        /// 
        /// 
        /// 
        [HttpPost]
        public async Task> GetDialogList(AccessToDialogueInDto inDto)
        {
            List data = new List();
            switch (inDto.Type)
            {
                case AccessToDialogueEnum.Question:
                    AccessToDialogueOutDto title = (await _qCChallengeRepository.Where(x => x.Id == inDto.Id).Include(x => x.CreateUserRole).Select(x => new AccessToDialogueOutDto()
                    {
                        CreateTime = x.CreateTime,
                        CreateUserName = x.CreateUserRole.UserName,
                        TalkContent = x.Content,
                        IsTitle = true,
                    }).FirstOrDefaultAsync()) ?? new AccessToDialogueOutDto();
                    data = await _qCChallengeDialogRepository.Where(x => x.QCChallengeId == inDto.Id && x.CreateTime <= inDto.Createtime).Include(x => x.CreateUserRole).Select(
                        x => new AccessToDialogueOutDto()
                        {
                            CreateTime = x.CreateTime,
                            CreateUserName = x.CreateUserRole.UserName,
                            TalkContent = x.TalkContent
                        }
                        ).OrderBy(x => x.CreateTime).ToListAsync();
                    data.Insert(0, title);
                    break;
                case AccessToDialogueEnum.Consistency:
                    data = await _checkChallengeDialogRepository.Where(x => x.SubjectVisitId == inDto.Id && x.CreateTime <= inDto.Createtime).Include(x => x.CreateUserRole).Select(
                        x => new AccessToDialogueOutDto()
                        {
                            CreateTime = x.CreateTime,
                            CreateUserName = x.CreateUserRole.UserName,
                            TalkContent = x.TalkContent
                        }
                        ).OrderBy(x => x.CreateTime).ToListAsync();
                    break;
            }
            return data;
        }
        /// 
        /// 获取表列名
        /// 
        /// 
        [HttpPost]
        public List GetTableColumn(string tableName)
        {
            return _frontAuditConfigRepository._dbContext.GetContextTableColumnList(tableName);
        }
        /// 
        /// 复制配置项及其子项
        /// 
        /// 传入对象
        /// 
        [HttpPost]
        public async Task CopyFrontAuditConfigItem(CopyFrontAuditConfigItemDto input)
        {
            var id = NewId.NextGuid();
            List frontAudits = new List();
            var frontAuditConfig = (await _frontAuditConfigRepository.FirstOrDefaultAsync(x => x.Id == input.ChildId)).Clone();
            var fronts = await _frontAuditConfigRepository.Where(x => x.ParentId == frontAuditConfig.Id).ToListAsync();
            fronts.ForEach(x =>
            {
                x.Id = NewId.NextGuid();
                x.ParentId = id;
            });
            frontAuditConfig.ParentId = input.ParentId;
            frontAuditConfig.Id = id;
            frontAudits.Add(frontAuditConfig);
            frontAudits.AddRange(fronts);
            await _frontAuditConfigRepository.AddRangeAsync(frontAudits);
            await _frontAuditConfigRepository.SaveChangesAsync();
        }
        /// 
        /// 批量添加字段
        /// 
        /// 数据集
        /// 
        public async Task BatchAddFrontAudit(BatchAddFrontAudit data)
        {
            var maxSort = await _frontAuditConfigRepository.Where(x => x.ParentId == data.ParentId).MaxAsync(x => x.Sort);
            List fronts = new List();
            foreach (var item in data.Columns)
            {
                maxSort++;
                fronts.Add(new FrontAuditConfig()
                {
                    Sort = maxSort,
                    Code = item.Name,
                    ValueCN = item.Remake,
                    IsEnable = true,
                    ParentId = data.ParentId
                });
            }
            await _frontAuditConfigRepository.AddRangeAsync(fronts);
        }
        /// 
        /// 翻译稽查数据
        /// 
        /// 
        /// 
        [HttpPost]
        public async Task> SetInspectionEnumValue(SetInspectionEnumValueDto dto)
        {
            return await SetInspectionEnumValueDataList(dto, dto.AuditDataIds.FirstOrDefault());
        }
        public async Task> GetInspectionJsonDataList(Guid trialId, Guid id)
        {
            //找到上一条Id
            var currentInspection = await _dataInspectionRepository.Where(t => t.Id == id).Select(t => new { t.GeneralId, t.ObjectRelationParentId, t.CreateTime }).FirstNotNullAsync();
            var beforeId = await _dataInspectionRepository.Where(x => x.GeneralId == currentInspection.GeneralId && x.CreateTime <= currentInspection.CreateTime && x.Id != id).OrderByDescending(x => x.CreateTime).Select(t => t.Id)
                .FirstOrDefaultAsync();
            List searchGuidList = new List() { id };
            if (beforeId != Guid.Empty)
            {
                searchGuidList.Add(beforeId);
            }
            return await SetInspectionEnumValueDataList(new SetInspectionEnumValueDto() { TrialId = trialId, AuditDataIds = searchGuidList }, id);
        }
        /// 
        /// 翻译稽查数据
        /// 
        /// 
        /// 
        /// 
        private async Task> SetInspectionEnumValueDataList(SetInspectionEnumValueDto dto, Guid currentInspectionId)
        {
            var auditDatas = await _dataInspectionRepository.AsQueryable().Where(x => dto.AuditDataIds.Contains(x.Id)).Select(x => new SetInspectionEnumDataDto()
            {
                Id = x.Id,
                JsonStr = x.JsonDetail,
                Identification = x.Identification,
                ObjectRelationParentId = x.ObjectRelationParentId,
                ObjectRelationParentId2 = x.ObjectRelationParentId2,
                ObjectRelationParentId3 = x.ObjectRelationParentId3,
                CreateTime = x.CreateTime,
                BatchId = x.BatchId,
            }).ToListAsync();
            var listIdentification = auditDatas.Select(x => x.Identification).Distinct().ToList();
            foreach (var item in auditDatas)
            {
                Dictionary jsonDict = (JsonConvert.DeserializeObject>(item.JsonStr)).IfNullThrowException();
                if (!jsonDict.ContainsKey(nameof(InspectionJsonDetail.CommonData)))
                {
                    jsonDict.Add(nameof(InspectionJsonDetail.CommonData), new { });
                }
                //查询关联父层级数据
                if (item.Id == currentInspectionId)
                {
                    //把父层级的数据的 CommonData 数据合并(每一个层级把下面层级需要的数据放在CommonData 里面)  麻烦点是每个层级都需要记录一些信息,而且名称不能重复
                    var objectLsit = new List